blink 1.1.20 → 1.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/agent/client/index.cjs +7 -7
- package/dist/browser/agent/client/index.js +6 -6
- package/dist/cli/{auth-CoJASYGP.js → auth-DbpOUCTO.js} +2 -2
- package/dist/cli/{chat-BDAEIrJW.js → chat-CAtArOPl.js} +1 -1
- package/dist/cli/chat-manager-GWR_v50X.js +21 -0
- package/dist/cli/connect-DWScpJzS.js +1 -0
- package/dist/cli/{dev-C5PZ-A_f.js → dev-BSh59jdn.js} +211 -181
- package/dist/cli/execAsync-Dwktgsum.js +1 -0
- package/dist/cli/execAsync-qNF4iDpO.js +1 -0
- package/dist/cli/{getMachineId-bsd-BQaAhwjO.js → getMachineId-bsd-0cOO_RKK.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cw8CWhxJ.js → getMachineId-bsd-BDrKPt3B.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DcR5dlLj.js → getMachineId-bsd-BJ3yH7j4.js} +1 -1
- package/dist/{node/getMachineId-bsd-BxqlJcyA.js → cli/getMachineId-bsd-BpxYEV3F.js} +1 -1
- package/dist/cli/getMachineId-bsd-BrJwIGYU.js +1 -0
- package/dist/cli/getMachineId-bsd-C6osJ6-S.js +1 -0
- package/dist/cli/{getMachineId-bsd-CbeuYR7X.js → getMachineId-bsd-CHVQhSq2.js} +1 -1
- package/dist/cli/getMachineId-bsd-DeIJ5F9l.js +1 -0
- package/dist/cli/{getMachineId-darwin-D7CuR-jd.js → getMachineId-darwin-0AdOS_kz.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DJ-H8l7s.js → getMachineId-darwin-BaA8JJgE.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DYCKXuZX.js → getMachineId-darwin-BeAdNwpL.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DyN_uugK.js → getMachineId-darwin-C8-xkmnZ.js} +1 -1
- package/dist/{node/getMachineId-darwin-Bf4P0U5b.js → cli/getMachineId-darwin-CJ2gOzlU.js} +1 -1
- package/dist/cli/getMachineId-darwin-CYvRIQbp.js +2 -0
- package/dist/cli/getMachineId-darwin-DWSKszGZ.js +2 -0
- package/dist/cli/getMachineId-darwin-wYLDmdQt.js +2 -0
- package/dist/cli/getMachineId-linux-D0cDy6Ik.js +1 -0
- package/dist/cli/getMachineId-linux-DgyKUIyK.js +1 -0
- package/dist/cli/getMachineId-linux-DnzutOBC.js +1 -0
- package/dist/cli/getMachineId-linux-nBO1QX9q.js +1 -0
- package/dist/cli/getMachineId-unsupported-DQBLgw4s.js +1 -0
- package/dist/cli/getMachineId-unsupported-DTFeADdG.js +1 -0
- package/dist/cli/getMachineId-unsupported-DgVzHx1H.js +1 -0
- package/dist/cli/getMachineId-unsupported-TE5qi9PD.js +1 -0
- package/dist/cli/{getMachineId-win-BB1s3SWz.js → getMachineId-win-4Psd7Tlr.js} +1 -1
- package/dist/cli/{getMachineId-win-BrQ4d5bO.js → getMachineId-win-BA0Li8oF.js} +1 -1
- package/dist/cli/{getMachineId-win-CgPYGelR.js → getMachineId-win-BvGLfEpq.js} +1 -1
- package/dist/cli/getMachineId-win-BzRwVWue.js +1 -0
- package/dist/cli/{getMachineId-win-B7f9VGFu.js → getMachineId-win-C4wjvjxC.js} +1 -1
- package/dist/cli/getMachineId-win-DXCyELQJ.js +1 -0
- package/dist/cli/getMachineId-win-hHwtD9GX.js +1 -0
- package/dist/cli/getMachineId-win-lhgCxX3y.js +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/init-Ciwa_eM0.js +23 -0
- package/dist/cli/{init-templates-CB4tNZfU.js → init-templates-By3gx42M.js} +33 -23
- package/dist/cli/login-BDP8JC4X.js +1 -0
- package/dist/cli/{run-bKDX6K46.js → run-CZZ6WAdr.js} +1 -1
- package/dist/cli/setup-slack-app-DagQxNol.js +1 -0
- package/dist/cli/{token-DNRiDJM-.js → token-BdYp2nw_.js} +1 -1
- package/dist/cli/token-util-C9doIH9w.js +1 -0
- package/dist/cli/{token-util-IqDtKhK6.js → token-util-KdD-UX1l.js} +1 -1
- package/dist/cli/undici-Bm_EanIy.js +1 -0
- package/dist/cli/util-CUfifM0g.js +5 -0
- package/dist/cli/{util-DDB5k1Go.js → util-k3x8m_i5.js} +9 -9
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.d.ts +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/build/index.d.ts +1 -1
- package/dist/node/execAsync-CY8juV7n.js +1 -0
- package/dist/node/{getMachineId-bsd-C10eVJgT.js → getMachineId-bsd-Ckr9jSoT.js} +1 -1
- package/dist/node/{getMachineId-bsd-B84ixt26.cjs → getMachineId-bsd-O0bNSuuh.cjs} +1 -1
- package/dist/node/{getMachineId-darwin-JB29MQsG.js → getMachineId-darwin-36SFRv2R.js} +1 -1
- package/dist/node/{getMachineId-darwin-Cyng5kFG.cjs → getMachineId-darwin-DivkCgLG.cjs} +1 -1
- package/dist/node/{getMachineId-win-CjJkZMZe.cjs → getMachineId-win-B_okYUv6.cjs} +1 -1
- package/dist/node/{getMachineId-win-C4G-fkEF.js → getMachineId-win-CGqZ4f4O.js} +1 -1
- package/dist/node/index.node-Bvp48I1R.cjs +50 -0
- package/dist/node/index.node-ppzOWVGE.js +50 -0
- package/dist/node/react/index.node.cjs +130 -121
- package/dist/node/react/index.node.d.cts +9 -2
- package/dist/node/react/index.node.d.ts +11 -4
- package/dist/node/react/index.node.js +84 -75
- package/dist/node/{token-DOfE6QlD.js → token-CI2_C_5D.js} +1 -1
- package/dist/node/{token-BBGr-czK.cjs → token-D4jFpAk0.cjs} +1 -1
- package/dist/node/token-util-BENsR1Bn.cjs +1 -0
- package/dist/node/{token-util-C_uzN2q9.js → token-util-idU3T5iM.js} +1 -1
- package/package.json +19 -1
- package/dist/cli/chat-manager-BRchJngj.js +0 -21
- package/dist/cli/connect-WyCmuQHj.js +0 -1
- package/dist/cli/init-CFrylDAP.js +0 -25
- package/dist/cli/login-DZFx5155.js +0 -1
- package/dist/cli/setup-slack-app-D_iwQuzr.js +0 -1
- package/dist/cli/token-util-C6Xu44iO.js +0 -1
- package/dist/cli/undici-L5V8WBce.js +0 -1
- package/dist/cli/util-BgbIWOFE.js +0 -6
- package/dist/node/execAsync-pJEPzmP4.cjs +0 -1
- package/dist/node/getMachineId-bsd-BudRe7J9.cjs +0 -1
- package/dist/node/getMachineId-darwin-ZVi3EKE3.cjs +0 -2
- package/dist/node/getMachineId-linux-CJXPQ8U5.cjs +0 -1
- package/dist/node/getMachineId-linux-CmMSYp7C.js +0 -1
- package/dist/node/getMachineId-unsupported-DM7fz1pP.cjs +0 -1
- package/dist/node/getMachineId-unsupported-Dtt3HTNZ.js +0 -1
- package/dist/node/getMachineId-win-D1szVnqR.js +0 -1
- package/dist/node/getMachineId-win-DDz2FyEp.cjs +0 -1
- package/dist/node/index.node-B6JXREDl.js +0 -55
- package/dist/node/index.node-BrLfthBj.cjs +0 -55
- package/dist/node/token-util-D9kCwzE6.cjs +0 -1
- /package/dist/cli/{connect-CQUVd44y.js → connect-BCK40kvG.js} +0 -0
- /package/dist/cli/{devtools-DvNholmW.js → devtools-DsAYEmyP.js} +0 -0
- /package/dist/cli/{execAsync-Bhq3YKvl.js → execAsync-BOPj9Mml.js} +0 -0
- /package/dist/cli/{execAsync-BnYBiViJ.js → execAsync-Bv4jTnD3.js} +0 -0
- /package/dist/cli/{execAsync-Djebuxfm.js → execAsync-CyP3Ojec.js} +0 -0
- /package/dist/cli/{execAsync-_tP2SNTy.js → execAsync-DHh3DKKp.js} +0 -0
- /package/dist/{node/execAsync-DzxhVi7q.js → cli/execAsync-DdLzES9n.js} +0 -0
- /package/dist/{node/execAsync-epR2wT1r.js → cli/execAsync-Dv6XOE2I.js} +0 -0
- /package/dist/cli/{getMachineId-linux-BCOAWAJr.js → getMachineId-linux-BQISLgy5.js} +0 -0
- /package/dist/cli/{getMachineId-linux-CBDQri3D.js → getMachineId-linux-Bg5YnekM.js} +0 -0
- /package/dist/cli/{getMachineId-linux-EqaaEzYC.js → getMachineId-linux-Boq-GGfA.js} +0 -0
- /package/dist/cli/{getMachineId-linux-QFNGh16E.js → getMachineId-linux-C9BHlxRm.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-BLalsIU8.js → getMachineId-unsupported-4qhSqb7w.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CNgpP2gn.js → getMachineId-unsupported-BsEK_LG9.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CQrnjCuH.js → getMachineId-unsupported-C6cVb167.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CcRcqdy3.js → getMachineId-unsupported-CqJy0sqq.js} +0 -0
- /package/dist/cli/{token-error-DVSfBVaT.js → token-error-COQY18OP.js} +0 -0
- /package/dist/cli/{undici-BUZTy5qm.js → undici-CRntNDHY.js} +0 -0
- /package/dist/node/{execAsync-C9Unrkco.cjs → execAsync-BMxJf0Eg.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-B-CtXK0L.cjs → getMachineId-linux-C8A0ak4z.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-BPnkHJah.js → getMachineId-linux-ZoT5w75D.js} +0 -0
- /package/dist/node/{getMachineId-unsupported--0R36RP6.cjs → getMachineId-unsupported-DSRCXJha.cjs} +0 -0
- /package/dist/node/{getMachineId-unsupported-C_4fnT4Z.js → getMachineId-unsupported-XVp8oFCM.js} +0 -0
- /package/dist/node/{index-CnBfy-54.d.ts → index-B4OXlWm3.d.ts} +0 -0
- /package/dist/node/{index.node-Dvc-cHCZ.d.ts → index.node-D5_czyKY.d.ts} +0 -0
- /package/dist/node/{token-util-BOoyY0PX.cjs → token-util-BxSJFXkT.cjs} +0 -0
- /package/dist/node/{token-util-_pz5CtFI.js → token-util-ChGcRyiF.js} +0 -0
|
@@ -1,90 +1,89 @@
|
|
|
1
|
-
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EventSourceParserStream as u,Hono as d,InvalidPromptError as f,InvalidResponseDataError as p,NoSuchModelError as m,StreamResponseFormatHeader as h,TooManyEmbeddingValuesForCallError as g,UnsupportedFunctionalityError as _,combineHeaders as v,convertBase64ToUint8Array as y,convertToBase64 as b,createBinaryResponseHandler as x,createEventSourceResponseHandler as S,createGatewayProvider as C,createJsonErrorResponseHandler as w,createJsonResponseHandler as T,createProviderDefinedToolFactory as E,createProviderDefinedToolFactoryWithOutputSchema as D,createServerAdapter as O,generateId as k,hc as A,isParsableJson as j,isToolApprovalOutput as ee,lastUIOptions as M,loadApiKey as te,loadOptionalSetting as ne,mediaTypeToExtension as re,parseProviderOptions as N,postFormDataToApi as P,postJsonToApi as F,require_has_flag as I,resolve as L,tools as R,validator as ie,withUserAgentSuffix as z,withoutTrailingSlash as ae}from"../index.node-B6JXREDl.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as oe}from"../build-DYI55eX2.js";import{createRequire as se}from"node:module";import ce,{z as B}from"zod/v4";import"zod/v3";import{Buffer as V}from"node:buffer";import*as H from"node:fs";import le,{existsSync as ue,mkdirSync as de,readFileSync as fe,unlinkSync as pe,writeFileSync as me}from"node:fs";import{fileURLToPath as he}from"node:url";import{Writable as ge}from"node:stream";import{promisify as _e,stripVTControlCharacters as ve}from"node:util";import{createHash as ye}from"node:crypto";import U,{createServer as be}from"http";import{dirname as xe,join as Se}from"path";import{existsSync as Ce,mkdirSync as we,readFileSync as Te,watch as Ee,writeFileSync as De}from"fs";import{convertToModelMessages as Oe,isToolOrDynamicToolUIPart as ke,readUIMessageStream as Ae,streamText as je,tool as W}from"ai";import{readFile as Me,stat as Ne,writeFile as Pe}from"fs/promises";import{spawn as Fe}from"child_process";import{useCallback as G,useEffect as K,useMemo as Ie,useRef as Le,useState as q}from"react";import J,{z as Y}from"zod";import*as Re from"node:path";import ze,{dirname as Be,join as Ve}from"node:path";import X,{stdin as He,stdout as Ue}from"node:process";import*as We from"node:readline";import Ge from"node:readline";import Ke,{execFile as qe}from"node:child_process";import Je,{constants as Ye}from"node:fs/promises";import Xe from"node:os";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Ze}from"@blink-sdk/compute-protocol/transport";var Qe=`2.0.23`,$e=B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),et=w({errorSchema:$e,errorToMessage:e=>e.error.message}),tt=B.object({citations:B.object({enabled:B.boolean()}).optional(),title:B.string().optional(),context:B.string().optional()}),nt=B.object({sendReasoning:B.boolean().optional(),thinking:B.object({type:B.union([B.literal(`enabled`),B.literal(`disabled`)]),budgetTokens:B.number().optional()}).optional(),disableParallelToolUse:B.boolean().optional(),cacheControl:B.object({type:B.literal(`ephemeral`),ttl:B.union([B.literal(`5m`),B.literal(`1h`)]).optional()}).optional()});function rt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var it=B.object({maxCharacters:B.number().optional()}),at=E({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),ot=(e={})=>at(e),st=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),userLocation:B.object({type:B.literal(`approximate`),city:B.string().optional(),region:B.string().optional(),country:B.string().optional(),timezone:B.string().optional()}).optional()}),ct=B.array(B.object({url:B.string(),title:B.string(),pageAge:B.string().nullable(),encryptedContent:B.string(),type:B.literal(`web_search_result`)})),lt=D({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:B.object({query:B.string()}),outputSchema:ct}),ut=(e={})=>lt(e),dt=B.object({maxUses:B.number().optional(),allowedDomains:B.array(B.string()).optional(),blockedDomains:B.array(B.string()).optional(),citations:B.object({enabled:B.boolean()}).optional(),maxContentTokens:B.number().optional()}),ft=B.object({type:B.literal(`web_fetch_result`),url:B.string(),content:B.object({type:B.literal(`document`),title:B.string(),citations:B.object({enabled:B.boolean()}).optional(),source:B.union([B.object({type:B.literal(`base64`),mediaType:B.literal(`application/pdf`),data:B.string()}),B.object({type:B.literal(`text`),mediaType:B.literal(`text/plain`),data:B.string()})])}),retrievedAt:B.string().nullable()}),pt=D({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:B.object({url:B.string()}),outputSchema:ft}),mt=(e={})=>pt(e);function ht({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=rt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=it.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=dt.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=st.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new _({functionality:`tool choice type: ${o}`})}}var gt=B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),_t=D({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:B.object({code:B.string()}),outputSchema:gt}),vt=(e={})=>_t(e);function yt(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new _({functionality:`URL-based text documents are not supported for citations`}):new _({functionality:`unsupported data type for text documents: ${typeof e}`})}async function bt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=xt(e),a,o=[];async function s(e){return(await N({provider:`anthropic`,providerOptions:e,schema:tt}))?.citations?.enabled??!1}async function c(e){let t=await N({provider:`anthropic`,providerOptions:e,schema:tt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new _({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:rt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=rt(a.providerOptions)??(o?rt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:b(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:b(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:yt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new _({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=rt(r.providerOptions)??(a?rt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new _({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=rt(s.providerOptions)??(c?rt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await N({provider:`anthropic`,providerOptions:s.providerOptions,schema:At});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=gt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=ft.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=ct.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function xt(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function St({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var Ct={webSearchResult:B.object({type:B.literal(`web_search_result_location`),cited_text:B.string(),url:B.string(),title:B.string(),encrypted_index:B.string()}),pageLocation:B.object({type:B.literal(`page_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_page_number:B.number(),end_page_number:B.number()}),charLocation:B.object({type:B.literal(`char_location`),cited_text:B.string(),document_index:B.number(),document_title:B.string().nullable(),start_char_index:B.number(),end_char_index:B.number()})},wt=B.discriminatedUnion(`type`,[Ct.webSearchResult,Ct.pageLocation,Ct.charLocation]);B.discriminatedUnion(`type`,[Ct.pageLocation,Ct.charLocation]);function Tt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=Et(e,t,n);i&&r(i)}}function Et(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var Dt=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??k}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await N({provider:`anthropic`,providerOptions:f,schema:nt}),{prompt:g,betas:v}=await bt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),y=h?.thinking?.type===`enabled`,b=h?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:g.system,messages:g.messages};if(y){if(b==null)throw new _({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(x.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(x.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=t+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=ht(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...p,...w],betas:new Set([...v,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return v(await L(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await F({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:et,successfulResponseHandler:T(Ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)Tt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:St({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await F({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:et,successfulResponseHandler:S(kt),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;Tt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=St({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},Ot=B.object({type:B.literal(`message`),id:B.string().nullish(),model:B.string().nullish(),content:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string(),citations:B.array(wt).optional()}),B.object({type:B.literal(`thinking`),thinking:B.string(),signature:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string(),input:B.unknown()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])),stop_reason:B.string().nullish(),stop_sequence:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})}),kt=B.discriminatedUnion(`type`,[B.object({type:B.literal(`message_start`),message:B.object({id:B.string().nullish(),model:B.string().nullish(),usage:B.looseObject({input_tokens:B.number(),cache_creation_input_tokens:B.number().nullish(),cache_read_input_tokens:B.number().nullish()})})}),B.object({type:B.literal(`content_block_start`),index:B.number(),content_block:B.discriminatedUnion(`type`,[B.object({type:B.literal(`text`),text:B.string()}),B.object({type:B.literal(`thinking`),thinking:B.string()}),B.object({type:B.literal(`tool_use`),id:B.string(),name:B.string()}),B.object({type:B.literal(`redacted_thinking`),data:B.string()}),B.object({type:B.literal(`server_tool_use`),id:B.string(),name:B.string(),input:B.record(B.string(),B.unknown()).nullish()}),B.object({type:B.literal(`web_fetch_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`web_fetch_result`),url:B.string(),retrieved_at:B.string(),content:B.object({type:B.literal(`document`),title:B.string().nullable(),citations:B.object({enabled:B.boolean()}).optional(),source:B.object({type:B.literal(`text`),media_type:B.string(),data:B.string()})})}),B.object({type:B.literal(`web_fetch_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`web_search_tool_result`),tool_use_id:B.string(),content:B.union([B.array(B.object({type:B.literal(`web_search_result`),url:B.string(),title:B.string(),encrypted_content:B.string(),page_age:B.string().nullish()})),B.object({type:B.literal(`web_search_tool_result_error`),error_code:B.string()})])}),B.object({type:B.literal(`code_execution_tool_result`),tool_use_id:B.string(),content:B.union([B.object({type:B.literal(`code_execution_result`),stdout:B.string(),stderr:B.string(),return_code:B.number()}),B.object({type:B.literal(`code_execution_tool_result_error`),error_code:B.string()})])})])}),B.object({type:B.literal(`content_block_delta`),index:B.number(),delta:B.discriminatedUnion(`type`,[B.object({type:B.literal(`input_json_delta`),partial_json:B.string()}),B.object({type:B.literal(`text_delta`),text:B.string()}),B.object({type:B.literal(`thinking_delta`),thinking:B.string()}),B.object({type:B.literal(`signature_delta`),signature:B.string()}),B.object({type:B.literal(`citations_delta`),citation:wt})])}),B.object({type:B.literal(`content_block_stop`),index:B.number()}),B.object({type:B.literal(`error`),error:B.object({type:B.string(),message:B.string()})}),B.object({type:B.literal(`message_delta`),delta:B.object({stop_reason:B.string().nullish(),stop_sequence:B.string().nullish()}),usage:B.looseObject({output_tokens:B.number(),cache_creation_input_tokens:B.number().nullish()})}),B.object({type:B.literal(`message_stop`)}),B.object({type:B.literal(`ping`)})]),At=B.object({signature:B.string().optional(),redactedData:B.string().optional()}),jt=E({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Mt=E({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:ce.object({command:ce.string(),restart:ce.boolean().optional()})}),Nt=E({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:B.object({action:B.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:B.array(B.number().int()).optional(),text:B.string().optional()})}),Pt=E({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:B.object({action:B.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:B.tuple([B.number().int(),B.number().int()]).optional(),duration:B.number().optional(),scroll_amount:B.number().optional(),scroll_direction:B.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:B.tuple([B.number().int(),B.number().int()]).optional(),text:B.string().optional()})}),Ft=E({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),It=E({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Lt=E({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:B.object({command:B.enum([`view`,`create`,`str_replace`,`insert`]),path:B.string(),file_text:B.string().optional(),insert_line:B.number().int().optional(),new_str:B.string().optional(),old_str:B.string().optional(),view_range:B.array(B.number().int()).optional()})}),Rt={bash_20241022:jt,bash_20250124:Mt,codeExecution_20250522:vt,computer_20241022:Nt,computer_20250124:Pt,textEditor_20241022:Ft,textEditor_20250124:It,textEditor_20250429:Lt,textEditor_20250728:ot,webFetch_20250910:mt,webSearch_20250305:ut};function zt(e={}){let t=ae(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>z({"anthropic-version":`2023-06-01`,"x-api-key":te({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Qe}`),r=r=>new Dt(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??k,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new m({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new m({modelId:e,modelType:`imageModel`})},i.tools=Rt,i}zt();var Bt=`2.0.17`,Vt=B.object({error:B.object({code:B.number().nullable(),message:B.string(),status:B.string()})}),Ht=w({errorSchema:Vt,errorToMessage:e=>e.error.message}),Ut=B.object({outputDimensionality:B.number().optional(),taskType:B.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Wt=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await N({provider:`google`,providerOptions:r,schema:Ut});if(e.length>this.maxEmbeddingsPerCall)throw new g({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=v(await L(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await F({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:Ht,successfulResponseHandler:T(Kt),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await F({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:Ht,successfulResponseHandler:T(Gt),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},Gt=B.object({embeddings:B.array(B.object({values:B.array(B.number())}))}),Kt=B.object({embedding:B.object({values:B.array(B.number())})});function qt(e){if(e==null||Jt(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=qt(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(qt):qt(a)),o&&(p.allOf=o.map(qt)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=qt(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(qt),p.nullable=!0}else p.anyOf=s.map(qt);return c&&(p.oneOf=c.map(qt)),d!==void 0&&(p.minLength=d),p}function Jt(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Yt(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new _({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:b(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new _({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new _({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:b(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
1
|
+
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-ppzOWVGE.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import ne,{existsSync as F,mkdirSync as I,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{useCallback as H,useEffect as U,useMemo as we,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Te from"node:path";import Ee,{dirname as De,join as Oe}from"node:path";import J,{stdin as ke,stdout as Ae}from"node:process";import je from"node:os";import Me from"node:tty";import*as Ne from"node:readline";import Pe from"node:readline";import Fe,{execFile as Ie}from"node:child_process";import Le,{constants as Re}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as ze}from"@blink-sdk/compute-protocol/transport";function Be(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Ve(e){return Object.fromEntries([...e.headers])}function He(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Ue(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function We(e,...t){let n=Ue(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ge=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Ke(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var qe=[`fetch failed`,`failed to fetch`];function Je({error:e,url:t,requestBodyValues:n}){if(Ke(e))return e;if(e instanceof TypeError&&qe.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Ye=`3.0.10`;function Xe({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Ze=/"__proto__"\s*:/,Qe=/"constructor"\s*:/;function $e(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Ze.test(e)===!1&&Qe.test(e)===!1?t:et(t)}function et(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function tt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return $e(e)}finally{Error.stackTraceLimit=t}}var nt=Symbol.for(`vercel.ai.validator`);function rt(e){return{[nt]:!0,validate:e}}function it(e){return typeof e==`object`&&!!e&&nt in e&&e[nt]===!0&&`validate`in e}function at(e){return it(e)?e:ot(e)}function ot(e){return rt(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function st({value:e,schema:t}){let n=await ct({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function ct({value:e,schema:t}){let n=at(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function lt({text:e,schema:t}){try{let n=tt(e);return t==null?n:st({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function ut({text:e,schema:t}){try{let n=tt(e);return t==null?{success:!0,value:n,rawValue:n}:await ct({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function dt({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await ut({text:e,schema:t}))}}))}async function ft({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await ct({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var pt=()=>globalThis.fetch,mt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ht({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ht=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=pt()})=>{try{let c=await o(e,{method:`POST`,headers:We(t,`ai-sdk/provider-utils/${Ye}`,He()),body:n.content,signal:a}),l=Ve(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Ke(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Ke(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Je({error:t,url:e,requestBodyValues:n.values})}};function gt(e){return e}function _t({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>gt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function vt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>gt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function yt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var bt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=Ve(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await lt({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},xt=e=>async({response:t})=>{let n=Ve(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:dt({stream:t.body,schema:e})}},St=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await ut({text:i,schema:e}),o=Ve(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:Ct,atob:wt}=globalThis;function Tt(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Ct(t)}function Et(e){return e instanceof Uint8Array?Tt(e):e}function Dt(e){return e?.replace(/\/$/,``)}var Ot=`2.0.23`,kt=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),At=bt({errorSchema:kt,errorToMessage:e=>e.error.message}),jt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Mt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Nt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Pt=N.object({maxCharacters:N.number().optional()}),Ft=_t({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),It=(e={})=>Ft(e),Lt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),Rt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),zt=vt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:Rt}),Bt=(e={})=>zt(e),Vt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ht=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Ut=vt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ht}),Wt=(e={})=>Ut(e);function Gt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Nt(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Pt.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Vt.parse(t.args);a.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Lt.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var Kt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),qt=vt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:Kt}),Jt=(e={})=>qt(e);function Yt(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Xt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Zt(e),a,o=[];async function s(e){return(await ft({provider:`anthropic`,providerOptions:e,schema:jt}))?.citations?.enabled??!1}async function c(e){let t=await ft({provider:`anthropic`,providerOptions:e,schema:jt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Nt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Nt(a.providerOptions)??(o?Nt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Et(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Et(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Yt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Nt(r.providerOptions)??(a?Nt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Nt(s.providerOptions)??(c?Nt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await ft({provider:`anthropic`,providerOptions:s.providerOptions,schema:sn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):n.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Kt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ht.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Rt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Zt(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function Qt({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var $t={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},en=N.discriminatedUnion(`type`,[$t.webSearchResult,$t.pageLocation,$t.charLocation]);N.discriminatedUnion(`type`,[$t.pageLocation,$t.charLocation]);function tn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=nn(e,t,n);i&&r(i)}}function nn(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var rn=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ge}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await ft({provider:`anthropic`,providerOptions:f,schema:Mt}),{prompt:g,betas:_}=await Xt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Gt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Be(await yt(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await mt({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:At,successfulResponseHandler:St(an),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)tn(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:Qt({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await mt({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:At,successfulResponseHandler:xt(on),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;tn(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=Qt({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},an=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(en).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),on=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:en})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),sn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),cn=_t({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),ln=_t({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=_t({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),dn=_t({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),fn=_t({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),pn=_t({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=_t({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn={bash_20241022:cn,bash_20250124:ln,codeExecution_20250522:Jt,computer_20241022:un,computer_20250124:dn,textEditor_20241022:fn,textEditor_20250124:pn,textEditor_20250429:mn,textEditor_20250728:It,webFetch_20250910:Wt,webSearch_20250305:Bt};function gn(e={}){let t=Dt(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>We({"anthropic-version":`2023-06-01`,"x-api-key":Xe({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ot}`),r=r=>new rn(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ge,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=hn,i}gn();function _n(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function vn(e){return Object.fromEntries([...e.headers])}function yn(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function bn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function xn(e,...t){let n=bn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Sn=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Cn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var wn=[`fetch failed`,`failed to fetch`];function Tn({error:e,url:t,requestBodyValues:n}){if(Cn(e))return e;if(e instanceof TypeError&&wn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var En=`3.0.10`;function Dn({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var On=/"__proto__"\s*:/,kn=/"constructor"\s*:/;function An(e){let t=JSON.parse(e);return typeof t!=`object`||!t||On.test(e)===!1&&kn.test(e)===!1?t:jn(t)}function jn(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Mn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return An(e)}finally{Error.stackTraceLimit=t}}var Nn=Symbol.for(`vercel.ai.validator`);function Pn(e){return{[Nn]:!0,validate:e}}function Fn(e){return typeof e==`object`&&!!e&&Nn in e&&e[Nn]===!0&&`validate`in e}function In(e){return Fn(e)?e:Ln(e)}function Ln(e){return Pn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Rn({value:e,schema:t}){let n=await zn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function zn({value:e,schema:t}){let n=In(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Bn({text:e,schema:t}){try{let n=Mn(e);return t==null?n:Rn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Vn({text:e,schema:t}){try{let n=Mn(e);return t==null?{success:!0,value:n,rawValue:n}:await zn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Hn({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Vn({text:e,schema:t}))}}))}async function Un({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await zn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Wn=()=>globalThis.fetch,Gn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Kn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Kn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Wn()})=>{try{let c=await o(e,{method:`POST`,headers:xn(t,`ai-sdk/provider-utils/${En}`,yn()),body:n.content,signal:a}),l=vn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Cn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Cn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Tn({error:t,url:e,requestBodyValues:n.values})}};function qn(e){return e}function Jn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>qn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Yn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>qn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Xn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Zn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=vn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Bn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Qn=e=>async({response:t})=>{let n=vn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Hn({stream:t.body,schema:e})}},$n=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Vn({text:i,schema:e}),o=vn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:er,atob:tr}=globalThis;function nr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return er(t)}function rr(e){return e instanceof Uint8Array?nr(e):e}function ir(e){return e?.replace(/\/$/,``)}var ar=`2.0.17`,or=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),sr=Zn({errorSchema:or,errorToMessage:e=>e.error.message}),cr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),lr=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await Un({provider:`google`,providerOptions:r,schema:cr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=_n(await Xn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Gn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:sr,successfulResponseHandler:$n(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Gn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:sr,successfulResponseHandler:$n(ur),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},ur=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),dr=N.object({embedding:N.object({values:N.array(N.number())})});function fr(e){if(e==null||pr(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=fr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(fr):fr(a)),o&&(p.allOf=o.map(fr)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=fr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(fr),p.nullable=!0}else p.anyOf=s.map(fr);return c&&(p.oneOf=c.map(fr)),d!==void 0&&(p.minLength=d),p}function pr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function mr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:rr(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:rr(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);r[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
5
|
-
`})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function Xt(e){return e.includes(`/`)?e:`models/${e}`}var Zt=B.object({responseModalities:B.array(B.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:B.object({thinkingBudget:B.number().optional(),includeThoughts:B.boolean().optional()}).optional(),cachedContent:B.string().optional(),structuredOutputs:B.boolean().optional(),safetySettings:B.array(B.object({category:B.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:B.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:B.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:B.boolean().optional(),labels:B.record(B.string(),B.string()).optional()});function Qt({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:qt(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new _({functionality:`tool choice type: ${l}`})}}function $t({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var en=B.object({web:B.object({uri:B.string(),title:B.string()}).nullish(),retrievedContext:B.object({uri:B.string(),title:B.string()}).nullish()}),tn=B.object({webSearchQueries:B.array(B.string()).nullish(),retrievalQueries:B.array(B.string()).nullish(),searchEntryPoint:B.object({renderedContent:B.string()}).nullish(),groundingChunks:B.array(en).nullish(),groundingSupports:B.array(B.object({segment:B.object({startIndex:B.number().nullish(),endIndex:B.number().nullish(),text:B.string().nullish()}),segment_text:B.string().nullish(),groundingChunkIndices:B.array(B.number()).nullish(),supportChunkIndices:B.array(B.number()).nullish(),confidenceScores:B.array(B.number()).nullish(),confidenceScore:B.array(B.number()).nullish()})).nullish(),retrievalMetadata:B.union([B.object({webDynamicRetrievalScore:B.number()}),B.object({})]).nullish()}),nn=E({id:`google.google_search`,name:`google_search`,inputSchema:B.object({mode:B.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:B.number().default(1)})}),rn=B.object({retrievedUrl:B.string(),urlRetrievalStatus:B.string()}),an=B.object({urlMetadata:B.array(rn)}),on=E({id:`google.url_context`,name:`url_context`,inputSchema:B.object({})}),sn=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??k}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await N({provider:`google`,providerOptions:f,schema:Zt});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=Yt(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=Qt({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?qt(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=v(await L(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await F({url:`${this.config.baseURL}/${Xt(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:Ht,successfulResponseHandler:T(mn),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=un({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:$t({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=v(await L(this.config.headers),e.headers),{responseHeaders:a,value:o}=await F({url:`${this.config.baseURL}/${Xt(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Ht,successfulResponseHandler:S(hn),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=un({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=ln(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=cn({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=$t({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function cn({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function ln(e){return e?.filter(e=>`inlineData`in e)}function un({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var dn=B.object({parts:B.array(B.union([B.object({functionCall:B.object({name:B.string(),args:B.unknown()}),thoughtSignature:B.string().nullish()}),B.object({inlineData:B.object({mimeType:B.string(),data:B.string()})}),B.object({executableCode:B.object({language:B.string(),code:B.string()}).nullish(),codeExecutionResult:B.object({outcome:B.string(),output:B.string()}).nullish(),text:B.string().nullish(),thought:B.boolean().nullish(),thoughtSignature:B.string().nullish()})])).nullish()}),fn=B.object({category:B.string().nullish(),probability:B.string().nullish(),probabilityScore:B.number().nullish(),severity:B.string().nullish(),severityScore:B.number().nullish(),blocked:B.boolean().nullish()}),pn=B.object({cachedContentTokenCount:B.number().nullish(),thoughtsTokenCount:B.number().nullish(),promptTokenCount:B.number().nullish(),candidatesTokenCount:B.number().nullish(),totalTokenCount:B.number().nullish()}),mn=B.object({candidates:B.array(B.object({content:dn.nullish().or(B.object({}).strict()),finishReason:B.string().nullish(),safetyRatings:B.array(fn).nullish(),groundingMetadata:tn.nullish(),urlContextMetadata:an.nullish()})),usageMetadata:pn.nullish(),promptFeedback:B.object({blockReason:B.string().nullish(),safetyRatings:B.array(fn).nullish()}).nullish()}),hn=B.object({candidates:B.array(B.object({content:dn.nullish(),finishReason:B.string().nullish(),safetyRatings:B.array(fn).nullish(),groundingMetadata:tn.nullish(),urlContextMetadata:an.nullish()})).nullish(),usageMetadata:pn.nullish(),promptFeedback:B.object({blockReason:B.string().nullish(),safetyRatings:B.array(fn).nullish()}).nullish()}),gn=D({id:`google.code_execution`,name:`code_execution`,inputSchema:B.object({language:B.string().describe(`The programming language of the code.`),code:B.string().describe(`The code to be executed.`)}),outputSchema:B.object({outcome:B.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:B.string().describe(`The output from the code execution.`)})}),_n={googleSearch:nn,urlContext:on,codeExecution:gn},vn=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await N({provider:`google`,providerOptions:s,schema:bn}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await F({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:v(await L(this.config.headers),c),body:m,failedResponseHandler:Ht,successfulResponseHandler:T(yn),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},yn=B.object({predictions:B.array(B.object({bytesBase64Encoded:B.string()})).default([])}),bn=B.object({personGeneration:B.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:B.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function xn(e={}){let t=ae(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>z({"x-goog-api-key":te({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${Bt}`),r=r=>new sn(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??k,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new Wt(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new vn(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=_n,o}xn();var Sn=B.object({error:B.object({message:B.string(),type:B.string().nullish(),param:B.any().nullish(),code:B.union([B.string(),B.number()]).nullish()})}),Cn=w({errorSchema:Sn,errorToMessage:e=>e.error.message});function wn({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${b(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new _({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:b(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:b(e.data),format:`mp3`}};default:throw new _({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new _({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${b(e.data)}`}}}else throw new _({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Tn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function En(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Dn=B.object({logitBias:B.record(B.coerce.number(),B.number()).optional(),logprobs:B.union([B.boolean(),B.number()]).optional(),parallelToolCalls:B.boolean().optional(),user:B.string().optional(),reasoningEffort:B.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:B.number().optional(),store:B.boolean().optional(),metadata:B.record(B.string().max(64),B.string().max(512)).optional(),prediction:B.record(B.string(),B.any()).optional(),structuredOutputs:B.boolean().optional(),serviceTier:B.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:B.boolean().optional(),textVerbosity:B.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:B.string().optional(),safetyIdentifier:B.string().optional()});function On({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new _({functionality:`tool choice type: ${o}`})}}var kn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await N({provider:`openai`,providerOptions:f,schema:Dn})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=wn({prompt:e,systemMessageMode:In(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};Nn(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!Pn(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!Fn(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=On({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await F({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:t,failedResponseHandler:Cn,successfulResponseHandler:T(jn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??k(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:k(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:En(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Tn(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await F({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:r,failedResponseHandler:Cn,successfulResponseHandler:S(Mn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Tn(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=En(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new p({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new p({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new p({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),j(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??k(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&j(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??k(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:k(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},An=B.object({prompt_tokens:B.number().nullish(),completion_tokens:B.number().nullish(),total_tokens:B.number().nullish(),prompt_tokens_details:B.object({cached_tokens:B.number().nullish()}).nullish(),completion_tokens_details:B.object({reasoning_tokens:B.number().nullish(),accepted_prediction_tokens:B.number().nullish(),rejected_prediction_tokens:B.number().nullish()}).nullish()}).nullish(),jn=B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({message:B.object({role:B.literal(`assistant`).nullish(),content:B.string().nullish(),tool_calls:B.array(B.object({id:B.string().nullish(),type:B.literal(`function`),function:B.object({name:B.string(),arguments:B.string()})})).nullish(),annotations:B.array(B.object({type:B.literal(`url_citation`),start_index:B.number(),end_index:B.number(),url:B.string(),title:B.string()})).nullish()}),index:B.number(),logprobs:B.object({content:B.array(B.object({token:B.string(),logprob:B.number(),top_logprobs:B.array(B.object({token:B.string(),logprob:B.number()}))})).nullish()}).nullish(),finish_reason:B.string().nullish()})),usage:An}),Mn=B.union([B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({delta:B.object({role:B.enum([`assistant`]).nullish(),content:B.string().nullish(),tool_calls:B.array(B.object({index:B.number(),id:B.string().nullish(),type:B.literal(`function`).nullish(),function:B.object({name:B.string().nullish(),arguments:B.string().nullish()})})).nullish(),annotations:B.array(B.object({type:B.literal(`url_citation`),start_index:B.number(),end_index:B.number(),url:B.string(),title:B.string()})).nullish()}).nullish(),logprobs:B.object({content:B.array(B.object({token:B.string(),logprob:B.number(),top_logprobs:B.array(B.object({token:B.string(),logprob:B.number()}))})).nullish()}).nullish(),finish_reason:B.string().nullish(),index:B.number()})),usage:An}),Sn]);function Nn(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Pn(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Fn(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function In(e){return Nn(e)?Ln[e]?.systemMessageMode??`developer`:`system`}var Ln={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function Rn({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
5
|
+
`})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function hr(e){return e.includes(`/`)?e:`models/${e}`}var gr=N.object({responseModalities:N.array(N.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:N.object({thinkingBudget:N.number().optional(),includeThoughts:N.boolean().optional()}).optional(),cachedContent:N.string().optional(),structuredOutputs:N.boolean().optional(),safetySettings:N.array(N.object({category:N.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:N.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:N.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:N.boolean().optional(),labels:N.record(N.string(),N.string()).optional()});function _r({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:fr(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${l}`})}}function vr({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var yr=N.object({web:N.object({uri:N.string(),title:N.string()}).nullish(),retrievedContext:N.object({uri:N.string(),title:N.string()}).nullish()}),br=N.object({webSearchQueries:N.array(N.string()).nullish(),retrievalQueries:N.array(N.string()).nullish(),searchEntryPoint:N.object({renderedContent:N.string()}).nullish(),groundingChunks:N.array(yr).nullish(),groundingSupports:N.array(N.object({segment:N.object({startIndex:N.number().nullish(),endIndex:N.number().nullish(),text:N.string().nullish()}),segment_text:N.string().nullish(),groundingChunkIndices:N.array(N.number()).nullish(),supportChunkIndices:N.array(N.number()).nullish(),confidenceScores:N.array(N.number()).nullish(),confidenceScore:N.array(N.number()).nullish()})).nullish(),retrievalMetadata:N.union([N.object({webDynamicRetrievalScore:N.number()}),N.object({})]).nullish()}),xr=Jn({id:`google.google_search`,name:`google_search`,inputSchema:N.object({mode:N.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:N.number().default(1)})}),Sr=N.object({retrievedUrl:N.string(),urlRetrievalStatus:N.string()}),Cr=N.object({urlMetadata:N.array(Sr)}),wr=Jn({id:`google.url_context`,name:`url_context`,inputSchema:N.object({})}),Tr=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Sn}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await Un({provider:`google`,providerOptions:f,schema:gr});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=mr(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=_r({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?fr(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=_n(await Xn(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await Gn({url:`${this.config.baseURL}/${hr(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:sr,successfulResponseHandler:$n(Mr),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=Or({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:vr({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=_n(await Xn(this.config.headers),e.headers),{responseHeaders:a,value:o}=await Gn({url:`${this.config.baseURL}/${hr(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:sr,successfulResponseHandler:Qn(Nr),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=Or({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Dr(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=Er({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=vr({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function Er({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Dr(e){return e?.filter(e=>`inlineData`in e)}function Or({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var kr=N.object({parts:N.array(N.union([N.object({functionCall:N.object({name:N.string(),args:N.unknown()}),thoughtSignature:N.string().nullish()}),N.object({inlineData:N.object({mimeType:N.string(),data:N.string()})}),N.object({executableCode:N.object({language:N.string(),code:N.string()}).nullish(),codeExecutionResult:N.object({outcome:N.string(),output:N.string()}).nullish(),text:N.string().nullish(),thought:N.boolean().nullish(),thoughtSignature:N.string().nullish()})])).nullish()}),Ar=N.object({category:N.string().nullish(),probability:N.string().nullish(),probabilityScore:N.number().nullish(),severity:N.string().nullish(),severityScore:N.number().nullish(),blocked:N.boolean().nullish()}),jr=N.object({cachedContentTokenCount:N.number().nullish(),thoughtsTokenCount:N.number().nullish(),promptTokenCount:N.number().nullish(),candidatesTokenCount:N.number().nullish(),totalTokenCount:N.number().nullish()}),Mr=N.object({candidates:N.array(N.object({content:kr.nullish().or(N.object({}).strict()),finishReason:N.string().nullish(),safetyRatings:N.array(Ar).nullish(),groundingMetadata:br.nullish(),urlContextMetadata:Cr.nullish()})),usageMetadata:jr.nullish(),promptFeedback:N.object({blockReason:N.string().nullish(),safetyRatings:N.array(Ar).nullish()}).nullish()}),Nr=N.object({candidates:N.array(N.object({content:kr.nullish(),finishReason:N.string().nullish(),safetyRatings:N.array(Ar).nullish(),groundingMetadata:br.nullish(),urlContextMetadata:Cr.nullish()})).nullish(),usageMetadata:jr.nullish(),promptFeedback:N.object({blockReason:N.string().nullish(),safetyRatings:N.array(Ar).nullish()}).nullish()}),Pr=Yn({id:`google.code_execution`,name:`code_execution`,inputSchema:N.object({language:N.string().describe(`The programming language of the code.`),code:N.string().describe(`The code to be executed.`)}),outputSchema:N.object({outcome:N.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:N.string().describe(`The output from the code execution.`)})}),Fr={googleSearch:xr,urlContext:wr,codeExecution:Pr},Ir=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await Un({provider:`google`,providerOptions:s,schema:Rr}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await Gn({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:_n(await Xn(this.config.headers),c),body:m,failedResponseHandler:sr,successfulResponseHandler:$n(Lr),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},Lr=N.object({predictions:N.array(N.object({bytesBase64Encoded:N.string()})).default([])}),Rr=N.object({personGeneration:N.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:N.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function zr(e={}){let t=ir(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>xn({"x-goog-api-key":Dn({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ar}`),r=r=>new Tr(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??Sn,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new lr(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Ir(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=Fr,o}zr();function Br(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Vr(e){return Object.fromEntries([...e.headers])}function Hr(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Ur(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Wr(e,...t){let n=Ur(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Gr=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Kr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var qr=[`fetch failed`,`failed to fetch`];function Jr({error:e,url:t,requestBodyValues:n}){if(Kr(e))return e;if(e instanceof TypeError&&qr.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Yr=`3.0.10`;function Xr({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Zr({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function Qr(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var $r=/"__proto__"\s*:/,ei=/"constructor"\s*:/;function ti(e){let t=JSON.parse(e);return typeof t!=`object`||!t||$r.test(e)===!1&&ei.test(e)===!1?t:ni(t)}function ni(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function ri(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ti(e)}finally{Error.stackTraceLimit=t}}var ii=Symbol.for(`vercel.ai.validator`);function ai(e){return{[ii]:!0,validate:e}}function oi(e){return typeof e==`object`&&!!e&&ii in e&&e[ii]===!0&&`validate`in e}function si(e){return oi(e)?e:ci(e)}function ci(e){return ai(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function li({value:e,schema:t}){let n=await ui({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function ui({value:e,schema:t}){let n=si(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function di({text:e,schema:t}){try{let n=ri(e);return t==null?n:li({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function fi({text:e,schema:t}){try{let n=ri(e);return t==null?{success:!0,value:n,rawValue:n}:await ui({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function pi(e){try{return ri(e),!0}catch{return!1}}function mi({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await fi({text:e,schema:t}))}}))}async function hi({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await ui({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var gi=()=>globalThis.fetch,_i=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>yi({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),vi=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>yi({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),yi=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=gi()})=>{try{let c=await o(e,{method:`POST`,headers:Wr(t,`ai-sdk/provider-utils/${Yr}`,Hr()),body:n.content,signal:a}),l=Vr(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Kr(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Kr(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Jr({error:t,url:e,requestBodyValues:n.values})}};function bi(e){return e}function xi({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>bi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Si({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>bi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}var Ci=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=Vr(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await di({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},wi=e=>async({response:t})=>{let n=Vr(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:mi({stream:t.body,schema:e})}},Ti=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await fi({text:i,schema:e}),o=Vr(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},Ei=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=Vr(e);if(!e.body)throw new s({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new s({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:Di,atob:Oi}=globalThis;function ki(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=Oi(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function Ai(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Di(t)}function ji(e){return e instanceof Uint8Array?Ai(e):e}function Mi(e){return e?.replace(/\/$/,``)}var Ni=N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),Pi=Ci({errorSchema:Ni,errorToMessage:e=>e.error.message});function Fi({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${ji(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new S({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:ji(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:ji(e.data),format:`mp3`}};default:throw new S({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new S({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${ji(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Ii({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Li(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Ri=N.object({logitBias:N.record(N.coerce.number(),N.number()).optional(),logprobs:N.union([N.boolean(),N.number()]).optional(),parallelToolCalls:N.boolean().optional(),user:N.string().optional(),reasoningEffort:N.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:N.number().optional(),store:N.boolean().optional(),metadata:N.record(N.string().max(64),N.string().max(512)).optional(),prediction:N.record(N.string(),N.any()).optional(),structuredOutputs:N.boolean().optional(),serviceTier:N.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:N.boolean().optional(),textVerbosity:N.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:N.string().optional(),safetyIdentifier:N.string().optional()});function zi({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var Bi=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await hi({provider:`openai`,providerOptions:f,schema:Ri})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=Fi({prompt:e,systemMessageMode:qi(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};Wi(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!Gi(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!Ki(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=zi({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await _i({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:t,failedResponseHandler:Pi,successfulResponseHandler:Ti(Hi),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??Gr(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:Gr(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:Li(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Ii(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await _i({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:r,failedResponseHandler:Pi,successfulResponseHandler:wi(Ui),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Ii(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Li(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new h({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new h({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new h({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),pi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Gr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&pi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Gr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:Gr(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Vi=N.object({prompt_tokens:N.number().nullish(),completion_tokens:N.number().nullish(),total_tokens:N.number().nullish(),prompt_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish(),accepted_prediction_tokens:N.number().nullish(),rejected_prediction_tokens:N.number().nullish()}).nullish()}).nullish(),Hi=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`).nullish(),content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string().nullish(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish(),annotations:N.array(N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()})).nullish()}),index:N.number(),logprobs:N.object({content:N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})).nullish()}).nullish(),finish_reason:N.string().nullish()})),usage:Vi}),Ui=N.union([N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({delta:N.object({role:N.enum([`assistant`]).nullish(),content:N.string().nullish(),tool_calls:N.array(N.object({index:N.number(),id:N.string().nullish(),type:N.literal(`function`).nullish(),function:N.object({name:N.string().nullish(),arguments:N.string().nullish()})})).nullish(),annotations:N.array(N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()})).nullish()}).nullish(),logprobs:N.object({content:N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})).nullish()}).nullish(),finish_reason:N.string().nullish(),index:N.number()})),usage:Vi}),Ni]);function Wi(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Gi(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Ki(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function qi(e){return Wi(e)?Ji[e]?.systemMessageMode??`developer`:`system`}var Ji={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function Yi({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
6
6
|
|
|
7
|
-
`,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new
|
|
7
|
+
`,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new m({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
|
|
8
8
|
${e}
|
|
9
9
|
|
|
10
|
-
`;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new
|
|
10
|
+
`;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new S({functionality:`tool-call messages`})}}).join(``);r+=`${n}:
|
|
11
11
|
${e}
|
|
12
12
|
|
|
13
|
-
`;break}case`tool`:throw new
|
|
13
|
+
`;break}case`tool`:throw new S({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
|
|
14
14
|
`,{prompt:r,stopSequences:[`
|
|
15
|
-
${t}:`]}}function zn({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Bn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Vn=B.object({echo:B.boolean().optional(),logitBias:B.record(B.string(),B.number()).optional(),suffix:B.string().optional(),user:B.string().optional(),logprobs:B.union([B.boolean(),B.number()]).optional()}),Hn=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await N({provider:`openai`,providerOptions:f,schema:Vn}),...await N({provider:this.providerOptionsName,providerOptions:f,schema:Vn})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=Rn({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await F({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:t,failedResponseHandler:Cn,successfulResponseHandler:T(Wn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:Bn(o.finish_reason),request:{body:t},response:{...zn(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await F({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:r,failedResponseHandler:Cn,successfulResponseHandler:S(Gn),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...zn(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Bn(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},Un=B.object({prompt_tokens:B.number(),completion_tokens:B.number(),total_tokens:B.number()}),Wn=B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({text:B.string(),finish_reason:B.string(),logprobs:B.object({tokens:B.array(B.string()),token_logprobs:B.array(B.number()),top_logprobs:B.array(B.record(B.string(),B.number())).nullish()}).nullish()})),usage:Un.nullish()}),Gn=B.union([B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({text:B.string(),finish_reason:B.string().nullish(),index:B.number(),logprobs:B.object({tokens:B.array(B.string()),token_logprobs:B.array(B.number()),top_logprobs:B.array(B.record(B.string(),B.number())).nullish()}).nullish()})),usage:Un.nullish()}),Sn]),Kn=B.object({dimensions:B.number().optional(),user:B.string().optional()}),qn=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new g({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await N({provider:`openai`,providerOptions:r,schema:Kn})??{},{responseHeaders:a,value:o,rawValue:s}=await F({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:v(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Cn,successfulResponseHandler:T(Jn),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},Jn=B.object({data:B.array(B.object({embedding:B.array(B.number())})),usage:B.object({prompt_tokens:B.number()}).nullish()}),Yn={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Xn=new Set([`gpt-image-1`]),Zn=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return Yn[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await F({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:v(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...Xn.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Cn,successfulResponseHandler:T(Qn),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},Qn=B.object({data:B.array(B.object({b64_json:B.string(),revised_prompt:B.string().optional()}))}),$n=B.object({code:B.string().nullish(),containerId:B.string()}),er=B.object({outputs:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`logs`),logs:B.string()}),B.object({type:B.literal(`image`),url:B.string()})])).nullish()}),tr=B.object({container:B.union([B.string(),B.object({fileIds:B.array(B.string()).optional()})]).optional()}),nr=D({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:$n,outputSchema:er}),rr=(e={})=>nr(e),ir=B.object({key:B.string(),type:B.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:B.union([B.string(),B.number(),B.boolean()])}),ar=B.object({type:B.enum([`and`,`or`]),filters:B.array(B.union([ir,B.lazy(()=>ar)]))}),or=B.object({vectorStoreIds:B.array(B.string()),maxNumResults:B.number().optional(),ranking:B.object({ranker:B.string().optional(),scoreThreshold:B.number().optional()}).optional(),filters:B.union([ir,ar]).optional()}),sr=B.object({queries:B.array(B.string()),results:B.array(B.object({attributes:B.record(B.string(),B.unknown()),fileId:B.string(),filename:B.string(),score:B.number(),text:B.string()})).nullable()}),cr=D({id:`openai.file_search`,name:`file_search`,inputSchema:B.object({}),outputSchema:sr}),lr=B.object({background:B.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:B.enum([`low`,`high`]).optional(),inputImageMask:B.object({fileId:B.string().optional(),imageUrl:B.string().optional()}).optional(),model:B.string().optional(),moderation:B.enum([`auto`]).optional(),outputCompression:B.number().int().min(0).max(100).optional(),outputFormat:B.enum([`png`,`jpeg`,`webp`]).optional(),quality:B.enum([`auto`,`low`,`medium`,`high`]).optional(),size:B.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),ur=B.object({result:B.string()}),dr=D({id:`openai.image_generation`,name:`image_generation`,inputSchema:B.object({}),outputSchema:ur}),fr=(e={})=>dr(e),pr=B.object({action:B.object({type:B.literal(`exec`),command:B.array(B.string()),timeoutMs:B.number().optional(),user:B.string().optional(),workingDirectory:B.string().optional(),env:B.record(B.string(),B.string()).optional()})}),mr=B.object({output:B.string()}),hr=D({id:`openai.local_shell`,name:`local_shell`,inputSchema:pr,outputSchema:mr}),gr=B.object({filters:B.object({allowedDomains:B.array(B.string()).optional()}).optional(),searchContextSize:B.enum([`low`,`medium`,`high`]).optional(),userLocation:B.object({type:B.literal(`approximate`),country:B.string().optional(),city:B.string().optional(),region:B.string().optional(),timezone:B.string().optional()}).optional()}),_r=E({id:`openai.web_search`,name:`web_search`,inputSchema:B.object({action:B.discriminatedUnion(`type`,[B.object({type:B.literal(`search`),query:B.string().nullish()}),B.object({type:B.literal(`open_page`),url:B.string()}),B.object({type:B.literal(`find`),url:B.string(),pattern:B.string()})]).nullish()})}),vr=(e={})=>_r(e),yr=B.object({searchContextSize:B.enum([`low`,`medium`,`high`]).optional(),userLocation:B.object({type:B.literal(`approximate`),country:B.string().optional(),city:B.string().optional(),region:B.string().optional(),timezone:B.string().optional()}).optional()}),br=E({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:B.object({action:B.discriminatedUnion(`type`,[B.object({type:B.literal(`search`),query:B.string().nullish()}),B.object({type:B.literal(`open_page`),url:B.string()}),B.object({type:B.literal(`find`),url:B.string(),pattern:B.string()})]).nullish()})}),xr={codeInterpreter:rr,fileSearch:cr,imageGeneration:fr,localShell:hr,webSearchPreview:br,webSearch:vr};function Sr(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Cr({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Sr(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${b(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Sr(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${b(e.data)}`}};else throw new _({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=pr.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await N({provider:`openai`,providerOptions:n.providerOptions,schema:wr}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:mr.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var wr=B.object({itemId:B.string().nullish(),reasoningEncryptedContent:B.string().nullish()});function Tr({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Er({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=or.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=yr.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=gr.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=tr.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=lr.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new _({functionality:`tool choice type: ${a}`})}}var Dr=B.object({type:B.literal(`web_search_call`),id:B.string(),status:B.string(),action:B.discriminatedUnion(`type`,[B.object({type:B.literal(`search`),query:B.string().nullish()}),B.object({type:B.literal(`open_page`),url:B.string()}),B.object({type:B.literal(`find`),url:B.string(),pattern:B.string()})]).nullish()}),Or=B.object({type:B.literal(`file_search_call`),id:B.string(),queries:B.array(B.string()),results:B.array(B.object({attributes:B.record(B.string(),B.unknown()),file_id:B.string(),filename:B.string(),score:B.number(),text:B.string()})).nullish()}),kr=B.object({type:B.literal(`code_interpreter_call`),id:B.string(),code:B.string().nullable(),container_id:B.string(),outputs:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`logs`),logs:B.string()}),B.object({type:B.literal(`image`),url:B.string()})])).nullable()}),Ar=B.object({type:B.literal(`local_shell_call`),id:B.string(),call_id:B.string(),action:B.object({type:B.literal(`exec`),command:B.array(B.string()),timeout_ms:B.number().optional(),user:B.string().optional(),working_directory:B.string().optional(),env:B.record(B.string(),B.string()).optional()})}),jr=B.object({type:B.literal(`image_generation_call`),id:B.string(),result:B.string()}),Mr=20,Nr=B.array(B.object({token:B.string(),logprob:B.number(),top_logprobs:B.array(B.object({token:B.string(),logprob:B.number()}))})),Pr=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=li(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await N({provider:`openai`,providerOptions:l,schema:ui}),{input:g,warnings:_}=await Cr({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Mr:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=Er({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await F({url:o,headers:v(this.config.headers(),e.headers),body:r,failedResponseHandler:Cn,successfulResponseHandler:T(B.object({id:B.string(),created_at:B.number(),error:B.object({code:B.string(),message:B.string()}).nullish(),model:B.string(),output:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`message`),role:B.literal(`assistant`),id:B.string(),content:B.array(B.object({type:B.literal(`output_text`),text:B.string(),logprobs:Nr.nullish(),annotations:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`url_citation`),start_index:B.number(),end_index:B.number(),url:B.string(),title:B.string()}),B.object({type:B.literal(`file_citation`),file_id:B.string(),filename:B.string().nullish(),index:B.number().nullish(),start_index:B.number().nullish(),end_index:B.number().nullish(),quote:B.string().nullish()}),B.object({type:B.literal(`container_file_citation`)})]))}))}),Dr,Or,kr,jr,Ar,B.object({type:B.literal(`function_call`),call_id:B.string(),name:B.string(),arguments:B.string(),id:B.string()}),B.object({type:B.literal(`computer_call`),id:B.string(),status:B.string().optional()}),B.object({type:B.literal(`reasoning`),id:B.string(),encrypted_content:B.string().nullish(),summary:B.array(B.object({type:B.literal(`summary_text`),text:B.string()}))})])),service_tier:B.string().nullish(),incomplete_details:B.object({reason:B.string()}).nullish(),usage:Fr})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??k(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??k(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Tr({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await F({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Cn,successfulResponseHandler:S(Jr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(ri(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):ii(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(Xr(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(Zr(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(ei(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(ti(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(ni(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else $r(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):Yr(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):oi(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):si(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):Qr(g)?(s=Tr({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):ai(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??k(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??k(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):ci(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Fr=B.object({input_tokens:B.number(),input_tokens_details:B.object({cached_tokens:B.number().nullish()}).nullish(),output_tokens:B.number(),output_tokens_details:B.object({reasoning_tokens:B.number().nullish()}).nullish()}),Ir=B.object({type:B.literal(`response.output_text.delta`),item_id:B.string(),delta:B.string(),logprobs:Nr.nullish()}),Lr=B.object({type:B.literal(`error`),code:B.string(),message:B.string(),param:B.string().nullish(),sequence_number:B.number()}),Rr=B.object({type:B.enum([`response.completed`,`response.incomplete`]),response:B.object({incomplete_details:B.object({reason:B.string()}).nullish(),usage:Fr,service_tier:B.string().nullish()})}),zr=B.object({type:B.literal(`response.created`),response:B.object({id:B.string(),created_at:B.number(),model:B.string(),service_tier:B.string().nullish()})}),Br=B.object({type:B.literal(`response.output_item.added`),output_index:B.number(),item:B.discriminatedUnion(`type`,[B.object({type:B.literal(`message`),id:B.string()}),B.object({type:B.literal(`reasoning`),id:B.string(),encrypted_content:B.string().nullish()}),B.object({type:B.literal(`function_call`),id:B.string(),call_id:B.string(),name:B.string(),arguments:B.string()}),B.object({type:B.literal(`web_search_call`),id:B.string(),status:B.string(),action:B.object({type:B.literal(`search`),query:B.string().optional()}).nullish()}),B.object({type:B.literal(`computer_call`),id:B.string(),status:B.string()}),B.object({type:B.literal(`file_search_call`),id:B.string()}),B.object({type:B.literal(`image_generation_call`),id:B.string()}),B.object({type:B.literal(`code_interpreter_call`),id:B.string(),container_id:B.string(),code:B.string().nullable(),outputs:B.array(B.discriminatedUnion(`type`,[B.object({type:B.literal(`logs`),logs:B.string()}),B.object({type:B.literal(`image`),url:B.string()})])).nullable(),status:B.string()})])}),Vr=B.object({type:B.literal(`response.output_item.done`),output_index:B.number(),item:B.discriminatedUnion(`type`,[B.object({type:B.literal(`message`),id:B.string()}),B.object({type:B.literal(`reasoning`),id:B.string(),encrypted_content:B.string().nullish()}),B.object({type:B.literal(`function_call`),id:B.string(),call_id:B.string(),name:B.string(),arguments:B.string(),status:B.literal(`completed`)}),kr,jr,Dr,Or,Ar,B.object({type:B.literal(`computer_call`),id:B.string(),status:B.literal(`completed`)})])}),Hr=B.object({type:B.literal(`response.function_call_arguments.delta`),item_id:B.string(),output_index:B.number(),delta:B.string()}),Ur=B.object({type:B.literal(`response.code_interpreter_call_code.delta`),item_id:B.string(),output_index:B.number(),delta:B.string()}),Wr=B.object({type:B.literal(`response.code_interpreter_call_code.done`),item_id:B.string(),output_index:B.number(),code:B.string()}),Gr=B.object({type:B.literal(`response.output_text.annotation.added`),annotation:B.discriminatedUnion(`type`,[B.object({type:B.literal(`url_citation`),url:B.string(),title:B.string()}),B.object({type:B.literal(`file_citation`),file_id:B.string(),filename:B.string().nullish(),index:B.number().nullish(),start_index:B.number().nullish(),end_index:B.number().nullish(),quote:B.string().nullish()})])}),Kr=B.object({type:B.literal(`response.reasoning_summary_part.added`),item_id:B.string(),summary_index:B.number()}),qr=B.object({type:B.literal(`response.reasoning_summary_text.delta`),item_id:B.string(),summary_index:B.number(),delta:B.string()}),Jr=B.union([Ir,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Lr,B.object({type:B.string()}).loose()]);function Yr(e){return e.type===`response.output_text.delta`}function Xr(e){return e.type===`response.output_item.done`}function Zr(e){return Xr(e)&&e.item.type===`reasoning`}function Qr(e){return e.type===`response.completed`||e.type===`response.incomplete`}function $r(e){return e.type===`response.created`}function ei(e){return e.type===`response.function_call_arguments.delta`}function ti(e){return e.type===`response.code_interpreter_call_code.delta`}function ni(e){return e.type===`response.code_interpreter_call_code.done`}function ri(e){return e.type===`response.output_item.added`}function ii(e){return ri(e)&&e.item.type===`reasoning`}function ai(e){return e.type===`response.output_text.annotation.added`}function oi(e){return e.type===`response.reasoning_summary_part.added`}function si(e){return e.type===`response.reasoning_summary_text.delta`}function ci(e){return e.type===`error`}function li(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var ui=B.object({include:B.array(B.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:B.string().nullish(),logprobs:B.union([B.boolean(),B.number().min(1).max(Mr)]).optional(),maxToolCalls:B.number().nullish(),metadata:B.any().nullish(),parallelToolCalls:B.boolean().nullish(),previousResponseId:B.string().nullish(),promptCacheKey:B.string().nullish(),reasoningEffort:B.string().nullish(),reasoningSummary:B.string().nullish(),safetyIdentifier:B.string().nullish(),serviceTier:B.enum([`auto`,`flex`,`priority`]).nullish(),store:B.boolean().nullish(),strictJsonSchema:B.boolean().nullish(),textVerbosity:B.enum([`low`,`medium`,`high`]).nullish(),user:B.string().nullish()}),di=B.object({instructions:B.string().nullish(),speed:B.number().min(.25).max(4).default(1).nullish()}),fi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await N({provider:`openai`,providerOptions:o,schema:di}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await F({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),body:r,failedResponseHandler:Cn,successfulResponseHandler:x(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},pi=B.object({include:B.array(B.string()).optional(),language:B.string().optional(),prompt:B.string().optional(),temperature:B.number().min(0).max(1).default(0).optional(),timestampGranularities:B.array(B.enum([`word`,`segment`])).default([`segment`]).optional()}),mi={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},hi=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await N({provider:`openai`,providerOptions:n,schema:pi}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([y(e)]);a.append(`model`,this.modelId);let s=re(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await P({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:v(this.config.headers(),e.headers),formData:r,failedResponseHandler:Cn,successfulResponseHandler:T(gi),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in mi?mi[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},gi=B.object({text:B.string(),language:B.string().nullish(),duration:B.number().nullish(),words:B.array(B.object({word:B.string(),start:B.number(),end:B.number()})).nullish(),segments:B.array(B.object({id:B.number(),seek:B.number(),start:B.number(),end:B.number(),text:B.string(),tokens:B.array(B.number()),temperature:B.number(),avg_logprob:B.number(),compression_ratio:B.number(),no_speech_prob:B.number()})).nullish()}),_i=`2.0.42`;function vi(e={}){let t=ae(ne({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>z({Authorization:`Bearer ${te({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${_i}`),i=i=>new kn(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new Hn(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new qn(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new Zn(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new hi(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new fi(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Pr(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=xr,f}vi(),B.object({user:B.string().optional(),reasoningEffort:B.string().optional()});var yi={errorSchema:B.object({error:B.object({message:B.string(),type:B.string().nullish(),param:B.any().nullish(),code:B.union([B.string(),B.number()]).nullish()})}),errorToMessage:e=>e.error.message},bi=B.object({prompt_tokens:B.number().nullish(),completion_tokens:B.number().nullish(),total_tokens:B.number().nullish(),prompt_tokens_details:B.object({cached_tokens:B.number().nullish()}).nullish(),completion_tokens_details:B.object({reasoning_tokens:B.number().nullish(),accepted_prediction_tokens:B.number().nullish(),rejected_prediction_tokens:B.number().nullish()}).nullish()}).nullish();B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({message:B.object({role:B.literal(`assistant`).nullish(),content:B.string().nullish(),reasoning_content:B.string().nullish(),reasoning:B.string().nullish(),tool_calls:B.array(B.object({id:B.string().nullish(),function:B.object({name:B.string(),arguments:B.string()})})).nullish()}),finish_reason:B.string().nullish()})),usage:bi}),B.object({echo:B.boolean().optional(),logitBias:B.record(B.string(),B.number()).optional(),suffix:B.string().optional(),user:B.string().optional()});var xi=B.object({prompt_tokens:B.number(),completion_tokens:B.number(),total_tokens:B.number()});B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({text:B.string(),finish_reason:B.string()})),usage:xi.nullish()}),B.object({dimensions:B.number().optional(),user:B.string().optional()}),B.object({data:B.array(B.object({embedding:B.array(B.number())})),usage:B.object({prompt_tokens:B.number()}).nullish(),providerMetadata:B.record(B.string(),B.record(B.string(),B.any())).optional()});var Si=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await F({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:v(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:w(this.config.errorStructure??yi),successfulResponseHandler:T(Ci),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},Ci=B.object({data:B.array(B.object({b64_json:B.string()}))});function wi(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${b(e.data)}`}}}else throw new _({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function Ti({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ei(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var Di=B.object({type:B.literal(`web`),country:B.string().length(2).optional(),excludedWebsites:B.array(B.string()).max(5).optional(),allowedWebsites:B.array(B.string()).max(5).optional(),safeSearch:B.boolean().optional()}),Oi=B.object({type:B.literal(`x`),excludedXHandles:B.array(B.string()).optional(),includedXHandles:B.array(B.string()).optional(),postFavoriteCount:B.number().int().optional(),postViewCount:B.number().int().optional(),xHandles:B.array(B.string()).optional()}),ki=B.object({type:B.literal(`news`),country:B.string().length(2).optional(),excludedWebsites:B.array(B.string()).max(5).optional(),safeSearch:B.boolean().optional()}),Ai=B.object({type:B.literal(`rss`),links:B.array(B.string().url()).max(1)}),ji=B.discriminatedUnion(`type`,[Di,Oi,ki,Ai]),Mi=B.object({reasoningEffort:B.enum([`low`,`high`]).optional(),searchParameters:B.object({mode:B.enum([`off`,`auto`,`on`]),returnCitations:B.boolean().optional(),fromDate:B.string().optional(),toDate:B.string().optional(),maxSearchResults:B.number().min(1).max(50).optional(),sources:B.array(ji).optional()}).optional()}),Ni=B.object({error:B.object({message:B.string(),type:B.string().nullish(),param:B.any().nullish(),code:B.union([B.string(),B.number()]).nullish()})}),Pi=w({errorSchema:Ni,errorToMessage:e=>e.error.message});function Fi({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new _({functionality:`tool choice type: ${i}`})}}var Ii=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await N({provider:`xai`,providerOptions:u,schema:Mi})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=wi(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=Fi({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await F({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:v(this.config.headers(),e.headers),body:t,failedResponseHandler:Pi,successfulResponseHandler:T(Ri),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:Ei(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...Ti(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await F({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:v(this.config.headers(),e.headers),body:r,failedResponseHandler:Pi,successfulResponseHandler:S(zi),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...Ti(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=Ei(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},Li=B.object({prompt_tokens:B.number(),completion_tokens:B.number(),total_tokens:B.number(),completion_tokens_details:B.object({reasoning_tokens:B.number().nullish()}).nullish()}),Ri=B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({message:B.object({role:B.literal(`assistant`),content:B.string().nullish(),reasoning_content:B.string().nullish(),tool_calls:B.array(B.object({id:B.string(),type:B.literal(`function`),function:B.object({name:B.string(),arguments:B.string()})})).nullish()}),index:B.number(),finish_reason:B.string().nullish()})),object:B.literal(`chat.completion`),usage:Li,citations:B.array(B.string().url()).nullish()}),zi=B.object({id:B.string().nullish(),created:B.number().nullish(),model:B.string().nullish(),choices:B.array(B.object({delta:B.object({role:B.enum([`assistant`]).optional(),content:B.string().nullish(),reasoning_content:B.string().nullish(),tool_calls:B.array(B.object({id:B.string(),type:B.literal(`function`),function:B.object({name:B.string(),arguments:B.string()})})).nullish()}),finish_reason:B.string().nullish(),index:B.number()})),usage:Li.nullish(),citations:B.array(B.string().url()).nullish()}),Bi=`2.0.23`,Vi={errorSchema:Ni,errorToMessage:e=>e.error.message};function Hi(e={}){let t=ae(e.baseURL??`https://api.x.ai/v1`),n=()=>z({Authorization:`Bearer ${te({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Bi}`),r=r=>new Ii(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:k,fetch:e.fetch}),i=r=>new Si(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:Vi}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new m({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}Hi();function Ui(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(h);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new u).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>je({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(vi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(vi({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(zt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(xn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(Hi({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var Wi=class{baseUrl;client;constructor(e){this.client=A(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Ui(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function Gi(e){let[t,n]=q(void 0),[r,i]=q([]),[a,o]=q(void 0),[s,l]=q(e.buildResult),[u,d]=q(e.env),[f,p]=q(e.apiServerUrl),[m,h]=q(void 0);return K(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),K(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;return o(void 0),n(void 0),h(void 0),(async()=>{let t=await Ki(),r=Fe(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let a=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!a&&t.startsWith(`Agent server listening on`)||(a||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{a||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let o=new Wi({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;a=!0;let l=await o.capabilities();h(l),n(o)})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[s,u,f]),Ie(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function Ki(){let e=be();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var qi=Object.getOwnPropertyNames,Ji=(e,t)=>function(){return t||(0,e[qi(e)[0]])((t={exports:{}}).exports,t),t.exports},Z=se(import.meta.url);Y.object({email:Y.string().email(),password:Y.string().min(8)}),Y.object({email:Y.string().email(),code:Y.string()}),Y.object({email:Y.string().email(),password:Y.string().min(8)});var Yi=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},Xi=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Zi(e){}function Qi(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Zi,onError:n=Zi,onRetry:r=Zi,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=$i(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
16
|
-
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new
|
|
17
|
-
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function
|
|
15
|
+
${t}:`]}}function Xi({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Zi(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Qi=N.object({echo:N.boolean().optional(),logitBias:N.record(N.string(),N.number()).optional(),suffix:N.string().optional(),user:N.string().optional(),logprobs:N.union([N.boolean(),N.number()]).optional()}),$i=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await hi({provider:`openai`,providerOptions:f,schema:Qi}),...await hi({provider:this.providerOptionsName,providerOptions:f,schema:Qi})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=Yi({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await _i({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:t,failedResponseHandler:Pi,successfulResponseHandler:Ti(ta),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:Zi(o.finish_reason),request:{body:t},response:{...Xi(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await _i({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:r,failedResponseHandler:Pi,successfulResponseHandler:wi(na),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Xi(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Zi(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},ea=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number()}),ta=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string(),logprobs:N.object({tokens:N.array(N.string()),token_logprobs:N.array(N.number()),top_logprobs:N.array(N.record(N.string(),N.number())).nullish()}).nullish()})),usage:ea.nullish()}),na=N.union([N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string().nullish(),index:N.number(),logprobs:N.object({tokens:N.array(N.string()),token_logprobs:N.array(N.number()),top_logprobs:N.array(N.record(N.string(),N.number())).nullish()}).nullish()})),usage:ea.nullish()}),Ni]),ra=N.object({dimensions:N.number().optional(),user:N.string().optional()}),ia=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await hi({provider:`openai`,providerOptions:r,schema:ra})??{},{responseHeaders:a,value:o,rawValue:s}=await _i({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Br(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Pi,successfulResponseHandler:Ti(aa),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},aa=N.object({data:N.array(N.object({embedding:N.array(N.number())})),usage:N.object({prompt_tokens:N.number()}).nullish()}),oa={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},sa=new Set([`gpt-image-1`]),ca=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return oa[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await _i({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Br(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...sa.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Pi,successfulResponseHandler:Ti(la),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},la=N.object({data:N.array(N.object({b64_json:N.string(),revised_prompt:N.string().optional()}))}),ua=N.object({code:N.string().nullish(),containerId:N.string()}),da=N.object({outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullish()}),fa=N.object({container:N.union([N.string(),N.object({fileIds:N.array(N.string()).optional()})]).optional()}),pa=Si({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:ua,outputSchema:da}),ma=(e={})=>pa(e),ha=N.object({key:N.string(),type:N.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:N.union([N.string(),N.number(),N.boolean()])}),ga=N.object({type:N.enum([`and`,`or`]),filters:N.array(N.union([ha,N.lazy(()=>ga)]))}),_a=N.object({vectorStoreIds:N.array(N.string()),maxNumResults:N.number().optional(),ranking:N.object({ranker:N.string().optional(),scoreThreshold:N.number().optional()}).optional(),filters:N.union([ha,ga]).optional()}),va=N.object({queries:N.array(N.string()),results:N.array(N.object({attributes:N.record(N.string(),N.unknown()),fileId:N.string(),filename:N.string(),score:N.number(),text:N.string()})).nullable()}),ya=Si({id:`openai.file_search`,name:`file_search`,inputSchema:N.object({}),outputSchema:va}),ba=N.object({background:N.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:N.enum([`low`,`high`]).optional(),inputImageMask:N.object({fileId:N.string().optional(),imageUrl:N.string().optional()}).optional(),model:N.string().optional(),moderation:N.enum([`auto`]).optional(),outputCompression:N.number().int().min(0).max(100).optional(),outputFormat:N.enum([`png`,`jpeg`,`webp`]).optional(),quality:N.enum([`auto`,`low`,`medium`,`high`]).optional(),size:N.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),xa=N.object({result:N.string()}),Sa=Si({id:`openai.image_generation`,name:`image_generation`,inputSchema:N.object({}),outputSchema:xa}),Ca=(e={})=>Sa(e),wa=N.object({action:N.object({type:N.literal(`exec`),command:N.array(N.string()),timeoutMs:N.number().optional(),user:N.string().optional(),workingDirectory:N.string().optional(),env:N.record(N.string(),N.string()).optional()})}),Ta=N.object({output:N.string()}),Ea=Si({id:`openai.local_shell`,name:`local_shell`,inputSchema:wa,outputSchema:Ta}),Da=N.object({filters:N.object({allowedDomains:N.array(N.string()).optional()}).optional(),searchContextSize:N.enum([`low`,`medium`,`high`]).optional(),userLocation:N.object({type:N.literal(`approximate`),country:N.string().optional(),city:N.string().optional(),region:N.string().optional(),timezone:N.string().optional()}).optional()}),Oa=xi({id:`openai.web_search`,name:`web_search`,inputSchema:N.object({action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()})}),ka=(e={})=>Oa(e),Aa=N.object({searchContextSize:N.enum([`low`,`medium`,`high`]).optional(),userLocation:N.object({type:N.literal(`approximate`),country:N.string().optional(),city:N.string().optional(),region:N.string().optional(),timezone:N.string().optional()}).optional()}),ja=xi({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:N.object({action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()})}),Ma={codeInterpreter:ma,fileSearch:ya,imageGeneration:Ca,localShell:Ea,webSearchPreview:ja,webSearch:ka};function Na(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Pa({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Na(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${ji(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Na(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${ji(e.data)}`}};else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(i&&n.toolName===`local_shell`){let e=wa.parse(n.input);a.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}a.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await hi({provider:`openai`,providerOptions:n.providerOptions,schema:Fa}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Ta.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var Fa=N.object({itemId:N.string().nullish(),reasoningEncryptedContent:N.string().nullish()});function Ia({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function La({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=_a.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=Aa.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Da.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=fa.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=ba.parse(t.args);i.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${a}`})}}var Ra=N.object({type:N.literal(`web_search_call`),id:N.string(),status:N.string(),action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()}),za=N.object({type:N.literal(`file_search_call`),id:N.string(),queries:N.array(N.string()),results:N.array(N.object({attributes:N.record(N.string(),N.unknown()),file_id:N.string(),filename:N.string(),score:N.number(),text:N.string()})).nullish()}),Ba=N.object({type:N.literal(`code_interpreter_call`),id:N.string(),code:N.string().nullable(),container_id:N.string(),outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullable()}),Va=N.object({type:N.literal(`local_shell_call`),id:N.string(),call_id:N.string(),action:N.object({type:N.literal(`exec`),command:N.array(N.string()),timeout_ms:N.number().optional(),user:N.string().optional(),working_directory:N.string().optional(),env:N.record(N.string(),N.string()).optional()})}),Ha=N.object({type:N.literal(`image_generation_call`),id:N.string(),result:N.string()}),Ua=20,Wa=N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})),Ga=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=xo(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await hi({provider:`openai`,providerOptions:l,schema:So}),{input:g,warnings:_}=await Pa({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Ua:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=La({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await _i({url:o,headers:Br(this.config.headers(),e.headers),body:r,failedResponseHandler:Pi,successfulResponseHandler:Ti(N.object({id:N.string(),created_at:N.number(),error:N.object({code:N.string(),message:N.string()}).nullish(),model:N.string(),output:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),role:N.literal(`assistant`),id:N.string(),content:N.array(N.object({type:N.literal(`output_text`),text:N.string(),logprobs:Wa.nullish(),annotations:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()}),N.object({type:N.literal(`file_citation`),file_id:N.string(),filename:N.string().nullish(),index:N.number().nullish(),start_index:N.number().nullish(),end_index:N.number().nullish(),quote:N.string().nullish()}),N.object({type:N.literal(`container_file_citation`)})]))}))}),Ra,za,Ba,Ha,Va,N.object({type:N.literal(`function_call`),call_id:N.string(),name:N.string(),arguments:N.string(),id:N.string()}),N.object({type:N.literal(`computer_call`),id:N.string(),status:N.string().optional()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish(),summary:N.array(N.object({type:N.literal(`summary_text`),text:N.string()}))})])),service_tier:N.string().nullish(),incomplete_details:N.object({reason:N.string()}).nullish(),usage:Ka})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??Gr(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??Gr(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:Ia({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await _i({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Pi,successfulResponseHandler:wi(ao),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(ho(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):go(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(so(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(co(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(fo(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(po(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(mo(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else uo(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):oo(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):vo(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):yo(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):lo(g)?(s=Ia({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):_o(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??Gr(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??Gr(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):bo(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},Ka=N.object({input_tokens:N.number(),input_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),output_tokens:N.number(),output_tokens_details:N.object({reasoning_tokens:N.number().nullish()}).nullish()}),qa=N.object({type:N.literal(`response.output_text.delta`),item_id:N.string(),delta:N.string(),logprobs:Wa.nullish()}),Ja=N.object({type:N.literal(`error`),code:N.string(),message:N.string(),param:N.string().nullish(),sequence_number:N.number()}),Ya=N.object({type:N.enum([`response.completed`,`response.incomplete`]),response:N.object({incomplete_details:N.object({reason:N.string()}).nullish(),usage:Ka,service_tier:N.string().nullish()})}),Xa=N.object({type:N.literal(`response.created`),response:N.object({id:N.string(),created_at:N.number(),model:N.string(),service_tier:N.string().nullish()})}),Za=N.object({type:N.literal(`response.output_item.added`),output_index:N.number(),item:N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),id:N.string()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish()}),N.object({type:N.literal(`function_call`),id:N.string(),call_id:N.string(),name:N.string(),arguments:N.string()}),N.object({type:N.literal(`web_search_call`),id:N.string(),status:N.string(),action:N.object({type:N.literal(`search`),query:N.string().optional()}).nullish()}),N.object({type:N.literal(`computer_call`),id:N.string(),status:N.string()}),N.object({type:N.literal(`file_search_call`),id:N.string()}),N.object({type:N.literal(`image_generation_call`),id:N.string()}),N.object({type:N.literal(`code_interpreter_call`),id:N.string(),container_id:N.string(),code:N.string().nullable(),outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullable(),status:N.string()})])}),Qa=N.object({type:N.literal(`response.output_item.done`),output_index:N.number(),item:N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),id:N.string()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish()}),N.object({type:N.literal(`function_call`),id:N.string(),call_id:N.string(),name:N.string(),arguments:N.string(),status:N.literal(`completed`)}),Ba,Ha,Ra,za,Va,N.object({type:N.literal(`computer_call`),id:N.string(),status:N.literal(`completed`)})])}),$a=N.object({type:N.literal(`response.function_call_arguments.delta`),item_id:N.string(),output_index:N.number(),delta:N.string()}),eo=N.object({type:N.literal(`response.code_interpreter_call_code.delta`),item_id:N.string(),output_index:N.number(),delta:N.string()}),to=N.object({type:N.literal(`response.code_interpreter_call_code.done`),item_id:N.string(),output_index:N.number(),code:N.string()}),no=N.object({type:N.literal(`response.output_text.annotation.added`),annotation:N.discriminatedUnion(`type`,[N.object({type:N.literal(`url_citation`),url:N.string(),title:N.string()}),N.object({type:N.literal(`file_citation`),file_id:N.string(),filename:N.string().nullish(),index:N.number().nullish(),start_index:N.number().nullish(),end_index:N.number().nullish(),quote:N.string().nullish()})])}),ro=N.object({type:N.literal(`response.reasoning_summary_part.added`),item_id:N.string(),summary_index:N.number()}),io=N.object({type:N.literal(`response.reasoning_summary_text.delta`),item_id:N.string(),summary_index:N.number(),delta:N.string()}),ao=N.union([qa,Ya,Xa,Za,Qa,$a,eo,to,no,ro,io,Ja,N.object({type:N.string()}).loose()]);function oo(e){return e.type===`response.output_text.delta`}function so(e){return e.type===`response.output_item.done`}function co(e){return so(e)&&e.item.type===`reasoning`}function lo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function uo(e){return e.type===`response.created`}function fo(e){return e.type===`response.function_call_arguments.delta`}function po(e){return e.type===`response.code_interpreter_call_code.delta`}function mo(e){return e.type===`response.code_interpreter_call_code.done`}function ho(e){return e.type===`response.output_item.added`}function go(e){return ho(e)&&e.item.type===`reasoning`}function _o(e){return e.type===`response.output_text.annotation.added`}function vo(e){return e.type===`response.reasoning_summary_part.added`}function yo(e){return e.type===`response.reasoning_summary_text.delta`}function bo(e){return e.type===`error`}function xo(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var So=N.object({include:N.array(N.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:N.string().nullish(),logprobs:N.union([N.boolean(),N.number().min(1).max(Ua)]).optional(),maxToolCalls:N.number().nullish(),metadata:N.any().nullish(),parallelToolCalls:N.boolean().nullish(),previousResponseId:N.string().nullish(),promptCacheKey:N.string().nullish(),reasoningEffort:N.string().nullish(),reasoningSummary:N.string().nullish(),safetyIdentifier:N.string().nullish(),serviceTier:N.enum([`auto`,`flex`,`priority`]).nullish(),store:N.boolean().nullish(),strictJsonSchema:N.boolean().nullish(),textVerbosity:N.enum([`low`,`medium`,`high`]).nullish(),user:N.string().nullish()}),Co=N.object({instructions:N.string().nullish(),speed:N.number().min(.25).max(4).default(1).nullish()}),wo=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await hi({provider:`openai`,providerOptions:o,schema:Co}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await _i({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:r,failedResponseHandler:Pi,successfulResponseHandler:Ei(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},To=N.object({include:N.array(N.string()).optional(),language:N.string().optional(),prompt:N.string().optional(),temperature:N.number().min(0).max(1).default(0).optional(),timestampGranularities:N.array(N.enum([`word`,`segment`])).default([`segment`]).optional()}),Eo={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},Do=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await hi({provider:`openai`,providerOptions:n,schema:To}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([ki(e)]);a.append(`model`,this.modelId);let s=Qr(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await vi({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),formData:r,failedResponseHandler:Pi,successfulResponseHandler:Ti(Oo),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Eo?Eo[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Oo=N.object({text:N.string(),language:N.string().nullish(),duration:N.number().nullish(),words:N.array(N.object({word:N.string(),start:N.number(),end:N.number()})).nullish(),segments:N.array(N.object({id:N.number(),seek:N.number(),start:N.number(),end:N.number(),text:N.string(),tokens:N.array(N.number()),temperature:N.number(),avg_logprob:N.number(),compression_ratio:N.number(),no_speech_prob:N.number()})).nullish()}),ko=`2.0.42`;function Ao(e={}){let t=Mi(Zr({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>Wr({Authorization:`Bearer ${Xr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${ko}`),i=i=>new Bi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new $i(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new ia(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new ca(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Do(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new wo(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ga(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Ma,f}Ao();function jo(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Mo(e){return Object.fromEntries([...e.headers])}function No(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Po(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Fo(e,...t){let n=Po(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Io(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Lo=[`fetch failed`,`failed to fetch`];function Ro({error:e,url:t,requestBodyValues:n}){if(Io(e))return e;if(e instanceof TypeError&&Lo.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var zo=`3.0.10`,Bo=/"__proto__"\s*:/,Vo=/"constructor"\s*:/;function Ho(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Bo.test(e)===!1&&Vo.test(e)===!1?t:Uo(t)}function Uo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Wo(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ho(e)}finally{Error.stackTraceLimit=t}}var Go=Symbol.for(`vercel.ai.validator`);function Ko(e){return{[Go]:!0,validate:e}}function qo(e){return typeof e==`object`&&!!e&&Go in e&&e[Go]===!0&&`validate`in e}function Jo(e){return qo(e)?e:Yo(e)}function Yo(e){return Ko(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Xo({value:e,schema:t}){let n=await Zo({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Zo({value:e,schema:t}){let n=Jo(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Qo({text:e,schema:t}){try{let n=Wo(e);return t==null?n:Xo({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function $o({text:e,schema:t}){try{let n=Wo(e);return t==null?{success:!0,value:n,rawValue:n}:await Zo({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}var es=()=>globalThis.fetch,ts=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ns({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ns=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=es()})=>{try{let c=await o(e,{method:`POST`,headers:Fo(t,`ai-sdk/provider-utils/${zo}`,No()),body:n.content,signal:a}),l=Mo(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Io(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Io(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ro({error:t,url:e,requestBodyValues:n.values})}},rs=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=Mo(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Qo({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},os=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await $o({text:i,schema:e}),o=Mo(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:ss,atob:cs}=globalThis;N.object({user:N.string().optional(),reasoningEffort:N.string().optional()});var ls={errorSchema:N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),errorToMessage:e=>e.error.message},us=N.object({prompt_tokens:N.number().nullish(),completion_tokens:N.number().nullish(),total_tokens:N.number().nullish(),prompt_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish(),accepted_prediction_tokens:N.number().nullish(),rejected_prediction_tokens:N.number().nullish()}).nullish()}).nullish();N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`).nullish(),content:N.string().nullish(),reasoning_content:N.string().nullish(),reasoning:N.string().nullish(),tool_calls:N.array(N.object({id:N.string().nullish(),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),finish_reason:N.string().nullish()})),usage:us}),N.object({echo:N.boolean().optional(),logitBias:N.record(N.string(),N.number()).optional(),suffix:N.string().optional(),user:N.string().optional()});var ds=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number()});N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string()})),usage:ds.nullish()}),N.object({dimensions:N.number().optional(),user:N.string().optional()}),N.object({data:N.array(N.object({embedding:N.array(N.number())})),usage:N.object({prompt_tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.any())).optional()});var fs=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await ts({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:jo(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:rs(this.config.errorStructure??ls),successfulResponseHandler:os(ps),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},ps=N.object({data:N.array(N.object({b64_json:N.string()}))});function ms(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function hs(e){return Object.fromEntries([...e.headers])}function gs(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function _s(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function vs(e,...t){let n=_s(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var ys=(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function bs(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var xs=[`fetch failed`,`failed to fetch`];function Ss({error:e,url:t,requestBodyValues:n}){if(bs(e))return e;if(e instanceof TypeError&&xs.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Cs=`3.0.10`;function ws({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Ts=/"__proto__"\s*:/,Es=/"constructor"\s*:/;function Ds(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Ts.test(e)===!1&&Es.test(e)===!1?t:Os(t)}function Os(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function ks(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ds(e)}finally{Error.stackTraceLimit=t}}var As=Symbol.for(`vercel.ai.validator`);function js(e){return{[As]:!0,validate:e}}function Ms(e){return typeof e==`object`&&!!e&&As in e&&e[As]===!0&&`validate`in e}function Ns(e){return Ms(e)?e:Ps(e)}function Ps(e){return js(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Fs({value:e,schema:t}){let n=await Is({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Is({value:e,schema:t}){let n=Ns(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Ls({text:e,schema:t}){try{let n=ks(e);return t==null?n:Fs({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Rs({text:e,schema:t}){try{let n=ks(e);return t==null?{success:!0,value:n,rawValue:n}:await Is({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function zs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Rs({text:e,schema:t}))}}))}async function Bs({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Is({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Vs=()=>globalThis.fetch,Hs=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Us({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Us=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Vs()})=>{try{let c=await o(e,{method:`POST`,headers:vs(t,`ai-sdk/provider-utils/${Cs}`,gs()),body:n.content,signal:a}),l=hs(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw bs(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(bs(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ss({error:t,url:e,requestBodyValues:n.values})}},Ws=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=hs(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Ls({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Gs=e=>async({response:t})=>{let n=hs(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:zs({stream:t.body,schema:e})}},Ks=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Rs({text:i,schema:e}),o=hs(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:qs,atob:Js}=globalThis;function Ys(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return qs(t)}function Xs(e){return e instanceof Uint8Array?Ys(e):e}function Zs(e){return e?.replace(/\/$/,``)}function Qs(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Xs(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function $s({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function ec(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var tc=N.object({type:N.literal(`web`),country:N.string().length(2).optional(),excludedWebsites:N.array(N.string()).max(5).optional(),allowedWebsites:N.array(N.string()).max(5).optional(),safeSearch:N.boolean().optional()}),nc=N.object({type:N.literal(`x`),excludedXHandles:N.array(N.string()).optional(),includedXHandles:N.array(N.string()).optional(),postFavoriteCount:N.number().int().optional(),postViewCount:N.number().int().optional(),xHandles:N.array(N.string()).optional()}),rc=N.object({type:N.literal(`news`),country:N.string().length(2).optional(),excludedWebsites:N.array(N.string()).max(5).optional(),safeSearch:N.boolean().optional()}),ic=N.object({type:N.literal(`rss`),links:N.array(N.string().url()).max(1)}),ac=N.discriminatedUnion(`type`,[tc,nc,rc,ic]),oc=N.object({reasoningEffort:N.enum([`low`,`high`]).optional(),searchParameters:N.object({mode:N.enum([`off`,`auto`,`on`]),returnCitations:N.boolean().optional(),fromDate:N.string().optional(),toDate:N.string().optional(),maxSearchResults:N.number().min(1).max(50).optional(),sources:N.array(ac).optional()}).optional()}),sc=N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),cc=Ws({errorSchema:sc,errorToMessage:e=>e.error.message});function lc({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new S({functionality:`tool choice type: ${i}`})}}var uc=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await Bs({provider:`xai`,providerOptions:u,schema:oc})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=Qs(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=lc({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await Hs({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:ms(this.config.headers(),e.headers),body:t,failedResponseHandler:cc,successfulResponseHandler:Ks(fc),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:ec(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...$s(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await Hs({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:ms(this.config.headers(),e.headers),body:r,failedResponseHandler:cc,successfulResponseHandler:Gs(pc),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...$s(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=ec(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},dc=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish()}).nullish()}),fc=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`),content:N.string().nullish(),reasoning_content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),index:N.number(),finish_reason:N.string().nullish()})),object:N.literal(`chat.completion`),usage:dc,citations:N.array(N.string().url()).nullish()}),pc=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({delta:N.object({role:N.enum([`assistant`]).optional(),content:N.string().nullish(),reasoning_content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),finish_reason:N.string().nullish(),index:N.number()})),usage:dc.nullish(),citations:N.array(N.string().url()).nullish()}),mc=`2.0.23`,hc={errorSchema:sc,errorToMessage:e=>e.error.message};function gc(e={}){let t=Zs(e.baseURL??`https://api.x.ai/v1`),n=()=>vs({Authorization:`Bearer ${ws({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${mc}`),r=r=>new uc(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:ys,fetch:e.fetch}),i=r=>new fs(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:hc}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}gc();function _c(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(y);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let n=e=>ye({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Ao({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Ao({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(gn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(zr({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(gc({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var vc=class{baseUrl;client;constructor(e){this.client=T(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),_c(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function yc(e){let[t,n]=G(void 0),[r,i]=G([]),[a,o]=G(void 0),[s,l]=G(e.buildResult),[u,d]=G(e.env),[f,p]=G(e.apiServerUrl),[m,h]=G(void 0);return U(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),U(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;return o(void 0),n(void 0),h(void 0),(async()=>{let t=await bc(),r=Ce(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{r.kill()}catch{}});let a=!1;r.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!a&&t.startsWith(`Agent server listening on`)||(a||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),r.stderr.on(`data`,e=>{a||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),r.on(`error`,t=>{e.abort(t)}),r.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let o=new vc({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;a=!0;let l=await o.capabilities();h(l),n(o)})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[s,u,f]),we(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function bc(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var xc=Object.getOwnPropertyNames,Sc=(e,t)=>function(){return t||(0,e[xc(e)[0]])((t={exports:{}}).exports,t),t.exports},Y=j(import.meta.url);q.object({email:q.string().email(),password:q.string().min(8)}),q.object({email:q.string().email(),code:q.string()}),q.object({email:q.string().email(),password:q.string().min(8)});var Cc=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},wc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Tc(e){}function Ec(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Tc,onError:n=Tc,onRetry:r=Tc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Dc(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
16
|
+
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new wc(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new wc(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
17
|
+
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Dc(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
18
18
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
19
|
-
`&&r++}}return[t,n]}var
|
|
20
|
-
Error message: ${
|
|
21
|
-
Error message: ${oa(t)}`,cause:t}),this[ba]=!0,this.value=e}static isInstance(e){return aa.hasMarker(e,va)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};ba=ya;var Sa=xa;(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new da({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();var Ca=/"__proto__"\s*:/,wa=/"constructor"\s*:/;function Ta(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Ca.test(e)===!1&&wa.test(e)===!1?t:Ea(t)}function Ea(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Da(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ta(e)}finally{Error.stackTraceLimit=t}}var Oa=Symbol.for(`vercel.ai.validator`);function ka(e){return{[Oa]:!0,validate:e}}function Aa(e){return typeof e==`object`&&!!e&&Oa in e&&e[Oa]===!0&&`validate`in e}function ja(e){return Aa(e)?e:Ma(e)}function Ma(e){return ka(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Sa({value:t,cause:n.issues})}})}async function Na({value:e,schema:t}){let n=ja(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Sa.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:Sa.wrap({value:e,cause:t}),rawValue:e}}}async function Pa({text:e,schema:t}){try{let n=Da(e);return t==null?{success:!0,value:n,rawValue:n}:await Na({value:n,schema:t})}catch(t){return{success:!1,error:ga.isInstance(t)?t:new ga({text:e,cause:t}),rawValue:void 0}}}var{btoa:Fa,atob:Ia}=globalThis;function La(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}const Q=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch{throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},Ra=Y.object({per_page:Y.number().int().positive().max(100).default(10).optional(),page:Y.number().int().nonnegative().default(0).optional()}),za=e=>Y.object({has_more:Y.boolean(),items:Y.array(e)}),Ba=Y.object({limit:Y.number().int().positive().max(100).default(10).optional(),cursor:Y.string().optional()}),Va=e=>Y.object({next_cursor:Y.string().nullable(),items:Y.array(e)}),Ha=Y.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),Ua=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Wa=(e,t)=>{let n=new ea;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Ga(n.readable,t)},Ga=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await Pa({text:e.data});if(!r.success){n.error(r.error);return}let i=t.safeParse({event:e.event,data:r.value});if(!i.success){n.error(i.error);return}n.enqueue(i.data)}}));return La(n)};Y.union([Y.object({agent_id:Y.uuid(),deployment_id:Y.uuid()}),Y.object({agent_id:Y.uuid(),deployment_number:Y.number().int().positive()})]),Y.object({agent_id:Y.uuid(),deployment_id:Y.uuid()});const Ka=Y.object({path:Y.string(),id:Y.uuid()}),qa=Ka.or(Y.object({path:Y.string(),data:Y.string().max(1024*1024*5)})),Ja=Y.enum([`production`,`preview`]);Y.object({agent_id:Y.uuid(),output_files:Y.array(qa).optional(),source_files:Y.array(qa).optional(),files:Y.array(qa).optional(),target:Ja,entrypoint:Y.string().optional(),message:Y.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e);const Ya=Y.object({id:Y.uuid(),number:Y.number().int().positive(),created_at:Y.iso.datetime(),updated_at:Y.iso.datetime(),created_by:Y.uuid().nullable(),created_from:Y.enum([`cli`]),agent_id:Y.uuid(),source_files:Y.array(Ka),output_files:Y.array(Ka),status:Y.enum([`success`,`failed`,`deploying`,`pending`]),target:Ja,error_message:Y.string().nullable(),user_message:Y.string().nullable(),platform:Y.enum([`lambda`]),platform_memory_mb:Y.number().int().positive(),platform_region:Y.string().nullable()});Y.object({id:Y.uuid(),created_at:Y.string().datetime(),updated_at:Y.string().datetime(),agent_id:Y.uuid(),deployment_id:Y.uuid(),level:Y.enum([`log`,`info`,`warning`,`error`]),message:Y.string()}),Ra.extend({agent_id:Y.uuid(),order:Y.enum([`asc`,`desc`]).default(`asc`).optional()}),za(Ya);var Xa=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t;t=`deployment_id`in e?e.deployment_id:e.deployment_number.toString();let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${t}`);return await Q(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await Q(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await Q(t,200)}};Y.object({agent_id:Y.uuid(),target:Ja.array().optional()}),Y.object({id:Y.uuid(),created_at:Y.date(),updated_at:Y.date(),created_by:Y.uuid(),updated_by:Y.uuid(),key:Y.string(),value:Y.string().nullable(),secret:Y.boolean(),target:Ja.array()});const Za=Y.object({key:Y.string(),value:Y.string(),secret:Y.boolean(),target:Ja.array().optional(),upsert:Y.boolean().optional()});Za.extend({agent_id:Y.uuid()}),Y.object({agent_id:Y.uuid(),id:Y.uuid()}),Y.object({agent_id:Y.uuid(),id:Y.uuid(),key:Y.string().optional(),value:Y.string().optional(),secret:Y.boolean().optional(),target:Ja.array().default([`preview`,`production`]).optional()});var Qa=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await Q(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await Q(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await Q(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await Q(t,200),t.json()}};const $a=Y.object({id:Y.string(),agent_id:Y.uuid(),agent_deployment_id:Y.uuid(),received_at:Y.date(),request_method:Y.string(),request_handler_location:Y.string().nullable(),duration_ms:Y.number().nullable(),error:Y.string().nullable(),response_status:Y.number().nullable()});$a.extend({request_headers:Y.record(Y.string(),Y.string()),request_headers_redacted:Y.boolean(),request_body:Y.string().nullable(),request_body_redacted:Y.boolean(),response_headers:Y.record(Y.string(),Y.string()).nullable(),response_headers_redacted:Y.boolean(),response_body:Y.string().nullable(),response_body_redacted:Y.boolean()}),Ba.extend({agent_id:Y.string(),agent_deployment_id:Y.number().optional()}),Va($a);var eo=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await Q(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await Q(n,200),n.json()}};Ba.extend({agent_id:Y.uuid(),agent_deployment_id:Y.uuid().optional()}),Y.object({agent_id:Y.uuid(),run_id:Y.uuid()});var to=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await Q(t,200),t.json()}};const no=Y.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),ro=Y.enum([`tool_call`,`queued_message`]),io=Y.object({id:Y.uuid(),number:Y.number().int().positive(),chat_id:Y.uuid(),chat_run_id:Y.uuid(),agent_id:Y.uuid(),agent_deployment_id:Y.uuid(),started_at:Y.string().datetime(),status:no,error:Y.string().nullable(),continuation_reason:ro.nullable(),response_status:Y.number().nullable(),response_message_id:Y.uuid().nullable(),time_to_first_token_micros:Y.number().nullable()});io.extend({heartbeat_at:Y.date(),completed_at:Y.date().nullable(),interrupted_at:Y.date().nullable(),first_message_id:Y.uuid().nullable(),last_message_id:Y.uuid().nullable(),response_headers:Y.record(Y.string(),Y.string()).nullable(),response_headers_redacted:Y.boolean(),response_body:Y.string().nullable(),response_body_redacted:Y.boolean(),usage_model:Y.string().nullable(),usage_total_input_tokens:Y.number().nullable(),usage_total_output_tokens:Y.number().nullable(),usage_total_tokens:Y.number().nullable(),usage_total_cached_input_tokens:Y.number().nullable(),usage_cost_usd:Y.number().nullable()}),Ba.extend({chat_id:Y.uuid(),run_id:Y.uuid().optional()}),Va(io);var ao=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await Q(t,200),t.json()}};Ba.extend({agent_id:Y.uuid(),agent_deployment_id:Y.uuid().optional(),chat_id:Y.uuid().optional(),run_id:Y.uuid().optional(),status:no.optional()}),Va(io);var oo=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await Q(t,200),t.json()}};const so=Y.object({type:Y.literal(`eq`),key:Y.string(),value:Y.string()}),co=Y.object({type:Y.literal(`and`),get filters(){return Y.array(Y.union([so,co]))}});Y.object({start_time:Y.iso.datetime().pipe(Y.coerce.date()),end_time:Y.iso.datetime().pipe(Y.coerce.date()),filters:Y.string().transform(e=>JSON.parse(e)).pipe(co),limit:Y.string().pipe(Y.coerce.number().min(1).max(1e4)).optional()});var lo=class{constructor(e){this.client=e}async spans(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),t.set(`filters`,JSON.stringify(e.filters)),e.limit!==void 0&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/traces/spans?${t.toString()}`);return await Q(n,200),await n.json()}};J.object({start_time:J.iso.datetime().pipe(J.coerce.date()),end_time:J.iso.datetime().pipe(J.coerce.date()),message_pattern:J.string().optional(),filters:J.string().transform(e=>JSON.parse(e)).pipe(co).optional(),limit:J.string().pipe(J.coerce.number().min(1).max(1e4)).optional()});const uo=J.object({timestamp:J.iso.datetime().pipe(J.coerce.date()),message:J.string(),level:J.enum([`info`,`error`,`warn`])}),fo=J.object({logs:J.array(uo)});var po=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern),e.filters&&t.set(`filters`,JSON.stringify(e.filters));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await Q(n,200);let r=await n.json();return fo.parse(r)}};const mo=Y.enum([`private`,`public`]);Y.object({organization_id:Y.uuid(),name:Y.string().regex(Ua),description:Y.string().optional(),visibility:mo.default(`private`).optional(),source_files:Y.array(qa).optional(),output_files:Y.array(qa).optional(),entrypoint:Y.string().optional(),env:Y.array(Za).optional(),request_id:Y.uuid().optional()});const ho=Y.object({id:Y.uuid(),organization_id:Y.uuid(),created_at:Y.iso.datetime(),updated_at:Y.iso.datetime(),created_by:Y.uuid(),name:Y.string().regex(Ua),description:Y.string().nullable(),avatar_url:Y.string().nullable(),visibility:mo,active_deployment_id:Y.uuid().nullable(),pinned:Y.boolean().default(!1),request_url:Y.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)});Y.object({id:Y.uuid(),name:Y.string().regex(Ua).optional(),description:Y.string().optional(),visibility:mo.optional(),active_deployment_id:Y.uuid().optional(),avatar_file_id:Y.uuid().nullable().optional()}),Ra.extend({organization_id:Y.uuid().optional(),pinned:Y.boolean().optional()}),za(ho),Y.object({agent_id:Y.uuid(),input:Y.string(),caret:Y.number().optional(),selection:Y.tuple([Y.number(),Y.number()]).optional(),chat_id:Y.uuid().optional(),agent_deployment_id:Y.uuid().optional()});const go=Y.object({text:Y.string(),caret:Y.number().optional(),selection:Y.tuple([Y.number(),Y.number()]).optional()});Y.object({agent_id:Y.uuid(),agent_deployment_id:Y.uuid().optional(),selected:Y.record(Y.string(),Y.string()).optional()}),Y.object({agent_id:Y.uuid(),start_time:Y.iso.datetime().pipe(Y.coerce.date()),end_time:Y.iso.datetime().pipe(Y.coerce.date())}),Y.object({seconds:Y.string()});var _o=class{constructor(e){this.client=e,this.deployments=new Xa(e),this.env=new Qa(e),this.webhook=new eo(e),this.runs=new to(e),this.steps=new oo(e),this.logs=new po(e),this.traces=new lo(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await Q(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await Q(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await Q(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),typeof e.pinned==`boolean`&&t.set(`pinned`,e.pinned.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await Q(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await Q(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await Q(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return La(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Wa(t,go)}async uiOptions(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.selected&&t.set(`selected`,JSON.stringify(e.selected));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/ui-options?${t.toString()}`);return await Q(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await Q(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await Q(t,204)}async getRuntimeUsage(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/usage/runtime?${t.toString()}`);return await Q(n,200),n.json()}},vo=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await Q(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await Q(t,200),new File([await t.blob()],``)}};const yo=Y.enum([`owner`,`admin`,`billing_admin`,`member`]),bo=Y.object({user_id:Y.uuid(),organization_id:Y.uuid(),role:yo,created_at:Y.date(),updated_at:Y.date()}),xo=Y.object({id:Y.uuid(),created_at:Y.date(),updated_at:Y.date(),display_name:Y.string().nullable(),email:Y.email(),avatar_url:Y.url().nullable(),username:Y.string()}),So=bo.extend({user:xo});Ra.extend({organization_id:Y.uuid()}),za(So),Y.object({organization_id:Y.uuid(),user_id:Y.uuid()}),Y.object({role:Y.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:Y.uuid(),user_id:Y.uuid()});var Co=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await Q(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await Q(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await Q(t,200),t.json()}},wo=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await Q(t,200),t.json()}};Y.object({id:Y.uuid(),name:Y.string(),created_at:Y.date(),updated_at:Y.date(),membership:bo.nullable(),members_url:Y.url(),invites_url:Y.url(),avatar_url:Y.url().nullable()}),Y.object({name:Y.string().regex(Ua)}),Y.object({name:Y.string().max(100).optional(),avatar_file_id:Y.string().nullable().optional(),avatar_url:Y.string().url().nullable().optional()});var To=class{constructor(e){this.client=e,this.members=new Co(e),this.agents=new wo(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await Q(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await Q(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await Q(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await Q(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await Q(t,204)}};J.object({id:J.uuid(),created_at:J.date(),updated_at:J.date(),email:J.string().email(),email_verified:J.boolean(),display_name:J.string(),username:J.string(),organization_id:J.uuid(),avatar_url:J.string().url().nullable()}),J.object({display_name:J.string().max(100).optional(),username:J.string().regex(Ua).optional(),avatar_file_id:J.string().nullable().optional()});const Eo=J.object({provider:J.enum([`github`,`google`]),provider_account_id:J.string()});J.object({github:J.array(Eo),google:J.array(Eo)});var Do=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await Q(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await Q(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await Q(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await Q(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await Q(e,204)}};const Oo=Y.enum([`ai-sdk`]),ko=Y.array(Y.custom()),Ao=Y.enum([`user`,`assistant`,`system`]),jo=Y.object({id:Y.uuid(),created_at:Y.string().datetime(),chat_id:Y.uuid(),metadata:Ha}).extend({format:Y.literal(`ai-sdk`),parts:ko,role:Ao}),Mo=Y.discriminatedUnion(`format`,[jo]);Ba.extend({chat_id:Y.uuid(),format:Oo.default(`ai-sdk`).optional()}),Va(Mo),Y.object({chat_id:Y.uuid(),message_id:Y.uuid()});const No=Y.object({id:Y.uuid().optional(),role:Ao,parts:ko,metadata:Ha.optional(),format:Y.literal(`ai-sdk`).optional()});Y.object({message_id:Y.uuid(),metadata:Ha.optional(),role:Ao.optional(),parts:ko.optional(),format:Y.literal(`ai-sdk`).optional(),behavior:Y.enum([`interrupt`,`enqueue`,`none`]).optional()});const Po=Y.enum([`enqueue`,`interrupt`,`append`]);Y.object({chat_id:Y.uuid(),behavior:Po.optional(),messages:Y.array(No).min(1)}),Y.object({messages:Y.array(Mo)});var Fo=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;t.set(`chat_id`,e.chat_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor),e.format&&t.set(`format`,e.format);let n=await this.client.request(`GET`,`/api/messages?${t.toString()}`);return await Q(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await Q(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await Q(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await Q(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await Q(t,201),t.json()}};Ba.extend({chat_id:Y.uuid()});const Io=Y.object({id:Y.uuid(),started_at:Y.date(),agent_id:Y.uuid(),agent_deployment_id:Y.uuid().nullable(),chat_id:Y.uuid(),step_count:Y.number().int().positive(),status:no.nullable(),error:Y.string().nullable()});Va(Io);var Lo=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs?${t.toString()}`);return await Q(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs/${e.run_id}`);return await Q(t,200),t.json()}};const Ro=Y.enum([`streaming`,`idle`,`error`,`interrupted`]),zo=Y.enum([`private`,`organization`,`public`]),Bo=Y.object({id:Y.uuid(),created_at:Y.iso.datetime(),updated_at:Y.iso.datetime(),created_by:Y.uuid().nullable(),organization_id:Y.uuid(),title:Y.string().nullable(),visibility:zo,metadata:Ha,archived:Y.boolean(),status:Ro,error:Y.string().nullable(),agent_deployment_id:Y.uuid().nullable(),agent:ho});Y.enum([`websocket`,`sse`]);const Vo=Y.object({organization_id:Y.uuid(),title:Y.string().optional(),visibility:zo.default(`private`).optional(),metadata:Ha.optional(),agent_id:Y.uuid(),agent_deployment_id:Y.uuid().optional(),messages:Y.array(No).optional()}),Ho=Vo.extend({stream:Y.literal(!0)}),Uo=Vo.extend({stream:Y.literal(!1).optional()});Y.union([Ho,Uo]),Y.union([Ba.extend({organization_id:Y.uuid()}),Ba.extend({agent_id:Y.uuid()})]);const Wo=Bo.extend({messages:Y.array(Mo)});Va(Bo);const Go=Y.discriminatedUnion(`event`,[Y.strictObject({event:Y.literal(`chat.updated`),data:Bo}),Y.strictObject({event:Y.literal(`message.created`),data:Mo}),Y.strictObject({event:Y.literal(`message.updated`),data:Mo}),Y.strictObject({event:Y.literal(`message.deleted`),data:Y.object({id:Y.uuid()})}),Y.strictObject({event:Y.literal(`message.chunk.added`),data:Y.object({id:Y.uuid(),chunk:Y.custom()})})]),Ko=Y.strictObject({event:Y.literal(`chat.created`),data:Wo});var qo=class{constructor(e){this.client=e,this.runs=new Lo(e),this.steps=new ao(e)}async create(e){let t={};e.stream&&(t.Accept=`text/event-stream`);let n=await this.client.request(`POST`,`/api/chats`,JSON.stringify(e),{headers:t});if(await Q(n,201),e.stream){let e=n.headers.get(`Content-Type`);if(e!==`text/event-stream`)throw Error(`Expected text/event-stream, got ${e}`);if(!n.body)throw Error(`The stream endpoint did not return a body!`);let t=Wa(n,Y.discriminatedUnion(`event`,[Go,Ko])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await Q(t,200),t.json()}async list(e){let t=new URLSearchParams;`organization_id`in e&&e.organization_id?t.set(`organization_id`,e.organization_id):`agent_id`in e&&e.agent_id&&t.set(`agent_id`,e.agent_id),e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats?${t.toString()}`);return await Q(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await Q(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await Q(t,200)}async stream(e,t={transport:`websocket`}){if(t?.transport===`websocket`)return this.streamWS(e,t?.signal);let n=await this.client.request(`GET`,`/api/chats/${e}/stream`,void 0,{abortSignal:t?.signal,headers:{Accept:`text/event-stream`}});return await Q(n,200),Wa(n,Go)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new ea,i=r.writable.getWriter(),a,o=new TextDecoder,s=!1,c=()=>{if(!s){s=!0,a?a.finally(()=>{i.close().catch(()=>{})}):i.close().catch(()=>{});try{n.close()}catch{}}};return t&&(t.aborted?c():t.addEventListener(`abort`,c,{once:!0})),n.addEventListener(`error`,()=>{c()}),n.addEventListener(`close`,()=>{c()}),n.addEventListener(`message`,e=>{if(s)return;let t;t=typeof e.data==`string`?e.data:o.decode(e.data),a=a?a.then(()=>{if(!s)return i.write(t).catch(()=>{})}):i.write(t).catch(()=>{})}),Ga(r.readable,Go)}};Y.object({id:Y.uuid(),organization_id:Y.uuid(),role:yo,invited_by:Y.uuid(),expires_at:Y.date(),created_at:Y.date(),updated_at:Y.date(),reusable:Y.boolean(),accepted_at:Y.date().nullable(),email:Y.string().email().nullable()}),Y.object({organization_id:Y.uuid(),role:yo,email:Y.string().email().optional(),reusable:Y.boolean().optional()}),Y.object({organization_id:Y.uuid()}),Y.object({organization_id:Y.uuid(),invite_id:Y.uuid()}),Y.object({code:Y.string()}).extend({invite_id:Y.uuid()});var Jo=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await Q(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await Q(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await Q(t,204)}async accept(e){let t=await this.client.request(`POST`,`/api/invites/${e.invite_id}/accept`,JSON.stringify({code:e.code}));return await Q(t,201),t.json()}},Yo=class{constructor(e){this.chats=new qo(this),this.runs=new Lo(this),this.agents=new _o(this),this.files=new vo(this),this.organizations=new To(this),this.invites=new Jo(this),this.users=new Do(this),this.messages=new Fo(this),this.baseURL=new URL(e?.baseURL??(globalThis.window===void 0?`https://blink.so`:window.location.origin)),this.fetch=e?.fetch,this.authToken=e?.authToken,this.auth=new Yi(this,this.baseURL)}request(e,t,n,r){let i=new URL(t,this.baseURL),a=new Headers;if(this.authToken&&a.set(`Authorization`,`Bearer ${this.authToken}`),typeof n==`string`&&a.set(`Content-Type`,`application/json`),r?.headers)for(let[e,t]of Object.entries(r.headers))a.set(e,t);let o;if(r?.abortSignal&&r?.timeout)throw Error(`Cannot specify both abortSignal and timeout`);return r?.abortSignal&&(o=r.abortSignal),r?.timeout&&(o=AbortSignal.timeout(r.timeout)),(this.fetch??fetch)(i.toString(),{method:e,headers:a,body:n,signal:o})}websocket(e){let t=new URL(e,this.baseURL);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,new WebSocket(t.toString())}},Xo=Ji({"../../node_modules/@blink-sdk/compute-protocol/dist/schema-CZdQiIXB.cjs":(e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>function(){return t||(0,e[i(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=Z(`zod`);u=l(u);let d=(e,t)=>{let n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},f=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},p=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1)),m=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),h=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({}),g={[m.REQUEST]:u.z.string(),[m.PROXY_INIT]:u.z.object({method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}),[m.PROXY_BODY]:u.z.instanceof(Uint8Array),[m.PROXY_WEBSOCKET_MESSAGE]:u.z.object({type:u.z.enum([`text`,`binary`]),data:u.z.instanceof(Uint8Array)}),[m.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number().optional(),reason:u.z.string().optional()})},_={[h.RESPONSE]:u.z.string(),[h.NOTIFICATION]:u.z.string(),[h.PROXY_INIT]:u.z.object({status_code:u.z.number(),status_message:u.z.string(),headers:u.z.record(u.z.string(),u.z.string())}),[h.PROXY_DATA]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_MESSAGE]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number(),reason:u.z.string()})},v={[m.PROXY_INIT]:{method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}},y={process_execute:u.z.object({command:u.z.string(),args:u.z.array(u.z.string()),env:u.z.record(u.z.string(),u.z.string()).optional(),cwd:u.z.string().optional()}),process_send_input:u.z.object({pid:u.z.number(),data:u.z.string()}),process_wait:u.z.object({pid:u.z.number(),output_idle_timeout_ms:u.z.number().optional(),timeout_ms:u.z.number().optional()}),process_list:u.z.object({include_dead:u.z.boolean().optional()}),process_read_plain_output:u.z.object({pid:u.z.number(),start_line:u.z.number().optional(),end_line:u.z.number().optional()}),process_kill:u.z.object({pid:u.z.number(),signal:u.z.string().optional()}),set_env:u.z.object({env:u.z.record(u.z.string(),u.z.string())}),read_file:u.z.object({path:u.z.string(),line_start:u.z.number().optional(),line_end:u.z.number().optional()}),write_file:u.z.object({path:u.z.string(),content:u.z.string(),base64:u.z.boolean().optional(),mode:u.z.number().optional()}),read_directory:u.z.object({path:u.z.string()}),watch_directory:u.z.object({path:u.z.string()}),deploy_static_files:u.z.object({path:u.z.string()})},b=u.z.object({pid:u.z.number(),command:u.z.string(),args:u.z.array(u.z.string()),title:u.z.string().optional(),cwd:u.z.string(),env:u.z.record(u.z.string(),u.z.string()),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional(),duration_ms:u.z.number().optional(),output_total_lines:u.z.number()}),x=b.extend({ansi_output:u.z.string(),plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number()})}),S={process_execute:u.z.object({pid:u.z.number()}),process_send_input:u.z.object({}),process_wait:x,process_list:u.z.object({processes:u.z.array(b)}),process_read_plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number(),duration_ms:u.z.number(),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional()}),process_kill:u.z.object({}),set_env:u.z.object({}),read_file:u.z.object({total_lines:u.z.number(),lines_read:u.z.number(),start_line:u.z.number(),content:u.z.string(),mime_type:u.z.string()}),write_file:u.z.object({}),read_directory:u.z.object({entries:u.z.array(u.z.object({name:u.z.string(),type:u.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:u.z.object({}),deploy_static_files:u.z.object({deployment_id:u.z.string()})},C=u.z.object({type:u.z.enum([`create`,`update`,`delete`]),path:u.z.string()}),w=u.z.object({type:u.z.enum([`context`,`added`,`deleted`]),content:u.z.string(),oldLineNumber:u.z.number().optional(),newLineNumber:u.z.number().optional()}),T=u.z.object({oldStart:u.z.number(),oldLines:u.z.number(),newStart:u.z.number(),newLines:u.z.number(),lines:u.z.array(w)}),E=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:u.z.string().optional(),insertions:u.z.number(),deletions:u.z.number(),chunks:u.z.array(T)}),D=u.z.object({totalFiles:u.z.number(),totalInsertions:u.z.number(),totalDeletions:u.z.number(),netChange:u.z.number(),startHash:u.z.string().optional(),currentHash:u.z.string().optional(),timespan:u.z.number(),files:u.z.array(E)}),O=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:u.z.boolean()}),k=u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),email:u.z.string(),date:u.z.date(),timestamp:u.z.date(),filesChanged:u.z.number(),insertions:u.z.number(),deletions:u.z.number(),commitDiff:u.z.array(E).optional()}),A=u.z.object({files:u.z.array(O),branch:u.z.string(),ahead:u.z.number(),behind:u.z.number(),timestamp:u.z.date(),sessionDiff:D.optional(),workingDirectoryDiff:D.optional(),newCommits:u.z.array(k),currentCommit:u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),date:u.z.date()}).optional(),diffSkipped:u.z.boolean().optional(),payloadTruncated:u.z.boolean().optional(),estimatedSizeKB:u.z.number().optional()}),j=u.z.object({debounceDelay:u.z.number().optional(),gitStatusInterval:u.z.number().optional(),ignoreDotfiles:u.z.boolean().optional(),ignored:u.z.array(u.z.string()).optional(),watchGit:u.z.boolean().optional(),includeDiffs:u.z.boolean().optional(),maxDiffFiles:u.z.number().optional(),maxPayloadSizeKB:u.z.number().optional(),truncateLargeDiffs:u.z.boolean().optional()}),ee={process_status:u.z.object({status:b}),process_output:u.z.object({pid:u.z.number(),output:u.z.string()}),file_change:u.z.object({changes:u.z.array(C)}),git_status:A};Object.defineProperty(e,`ClientMessageSchema`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`ClientMessageType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`DiffChunkSchema`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`DiffLineSchema`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`DiffSummarySchema`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`FileChangeEventSchema`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`FileDiffSchema`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`GitCommitEventSchema`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`GitFileStatusSchema`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`GitStatusEventSchema`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`NotificationSchema`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(e,`ProcessStatusSchema`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`ProcessWaitSchema`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`ProxySchema`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`RequestSchema`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`ResponseSchema`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`ServerMessageSchema`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`ServerMessageType`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`WatchOptionsSchema`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`__commonJS`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`__toESM`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`createMessagePayload`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`createWebSocketMessagePayload`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`parseWebSocketMessagePayload`,{enumerable:!0,get:function(){return p}})})}),Zo=Ji({"../../node_modules/ws/lib/constants.js":((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})}),Qo=Ji({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=Zo(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=Z(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})}),$o=Ji({"../../node_modules/ws/lib/limiter.js":((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})}),es=Ji({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=Z(`zlib`),r=Qo(),i=$o(),{kStatusCode:a}=Zo(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})}),ts=Ji({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=Z(`buffer`),{hasBlob:r}=Zo(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Z(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),ns=Ji({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=Z(`stream`),r=es(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Zo(),{concat:c,toArrayBuffer:l,unmask:u}=Qo(),{isValidStatusCode:d,isValidUTF8:f}=ts(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})}),rs=Ji({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=Z(`stream`),{randomFillSync:r}=Z(`crypto`),i=es(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Zo(),{isBlob:c,isValidStatusCode:l}=ts(),{mask:u,toBuffer:d}=Qo(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})}),os=Ji({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Zo(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})}),ss=Ji({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=ts();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})}),cs=Ji({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=Z(`events`),r=Z(`https`),i=Z(`http`),a=Z(`net`),o=Z(`tls`),{randomBytes:s,createHash:c}=Z(`crypto`),{Duplex:l,Readable:u}=Z(`stream`),{URL:d}=Z(`url`),f=es(),p=ns(),m=rs(),{isBlob:h}=ts(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Zo(),{EventTarget:{addEventListener:w,removeEventListener:T}}=os(),{format:E,parse:D}=ss(),{toBuffer:O}=Qo(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var M=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,I),i.on(`drain`,L),i.on(`error`,R),i.on(`message`,z),i.on(`ping`,ae),i.on(`pong`,oe),a.onerror=ce,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,V),t.on(`data`,H),t.on(`end`,le),t.on(`error`,ue),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){P(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),B(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){F(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){F(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){F(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){P(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(M,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(M.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(M,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(M.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(M,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(M.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(M,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(M.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(M.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(M.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),M.prototype.addEventListener=w,M.prototype.removeEventListener=T,t.exports=M;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?N:re),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{P(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,ne(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){P(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);ne(e,t);return}te(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||P(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==M.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){P(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){P(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){P(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){P(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{P(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){P(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{P(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function ne(e,t){e._readyState=M.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function re(e){return e.path=e.socketPath,a.connect(e)}function N(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function P(e,t,n){e._readyState=M.CLOSING;let r=Error(n);Error.captureStackTrace(r,P),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function F(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function I(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,H),process.nextTick(se,n._socket),e===1005?n.close():n.close(e,t))}function L(){let e=this[S];e.isPaused||e._socket.resume()}function R(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,H),process.nextTick(se,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ie(){this[S].emitClose()}function z(e,t){this[S].emit(`message`,e,t)}function ae(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function oe(e){this[S].emit(`pong`,e)}function se(e){e.resume()}function ce(e){let t=this[S];t.readyState!==M.CLOSED&&(t.readyState===M.OPEN&&(t._readyState=M.CLOSING,B(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function B(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function V(){let e=this[S];this.removeListener(`close`,V),this.removeListener(`data`,H),this.removeListener(`end`,le),e._readyState=M.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ie),e._receiver.on(`finish`,ie))}function H(e){this[S]._receiver.write(e)||this.pause()}function le(){let e=this[S];e._readyState=M.CLOSING,e._receiver.end(),this.end()}function ue(){let e=this[S];this.removeListener(`error`,ue),this.on(`error`,C),e&&(e._readyState=M.CLOSING,this.destroy())}})}),ls=Ji({"../../node_modules/ws/lib/stream.js":((e,t)=>{cs();let{Duplex:n}=Z(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})}),us=Ji({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=ts();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})}),ds=Ji({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=Z(`events`),r=Z(`http`),{Duplex:i}=Z(`stream`),{createHash:a}=Z(`crypto`),o=ss(),s=es(),c=us(),l=cs(),{GUID:u,kWebSocket:d}=Zo(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
19
|
+
`&&r++}}return[t,n]}var Oc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Ec({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},kc=`vercel.ai.error`,Ac=Symbol.for(kc),jc,Mc=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[jc]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,kc)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};jc=Ac;var Nc=Mc;function Pc(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Fc=`AI_InvalidArgumentError`,Ic=`vercel.ai.error.${Fc}`,Lc=Symbol.for(Ic),Rc,zc=class extends Nc{constructor({message:e,cause:t,argument:n}){super({name:Fc,message:e,cause:t}),this[Rc]=!0,this.argument=n}static isInstance(e){return Nc.hasMarker(e,Ic)}};Rc=Lc;var Bc=`AI_JSONParseError`,Vc=`vercel.ai.error.${Bc}`,Hc=Symbol.for(Vc),Uc,Wc=class extends Nc{constructor({text:e,cause:t}){super({name:Bc,message:`JSON parsing failed: Text: ${e}.
|
|
20
|
+
Error message: ${Pc(t)}`,cause:t}),this[Uc]=!0,this.text=e}static isInstance(e){return Nc.hasMarker(e,Vc)}};Uc=Hc;var Gc=`AI_TypeValidationError`,Kc=`vercel.ai.error.${Gc}`,qc=Symbol.for(Kc),Jc,Yc=class e extends Nc{constructor({value:e,cause:t}){super({name:Gc,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
21
|
+
Error message: ${Pc(t)}`,cause:t}),this[Jc]=!0,this.value=e}static isInstance(e){return Nc.hasMarker(e,Kc)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Jc=qc;var Xc=Yc;(({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new zc({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();var Zc=/"__proto__"\s*:/,Qc=/"constructor"\s*:/;function $c(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Zc.test(e)===!1&&Qc.test(e)===!1?t:el(t)}function el(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function tl(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return $c(e)}finally{Error.stackTraceLimit=t}}var nl=Symbol.for(`vercel.ai.validator`);function rl(e){return{[nl]:!0,validate:e}}function il(e){return typeof e==`object`&&!!e&&nl in e&&e[nl]===!0&&`validate`in e}function al(e){return il(e)?e:ol(e)}function ol(e){return rl(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Xc({value:t,cause:n.issues})}})}async function sl({value:e,schema:t}){let n=al(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Xc.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:Xc.wrap({value:e,cause:t}),rawValue:e}}}async function cl({text:e,schema:t}){try{let n=tl(e);return t==null?{success:!0,value:n,rawValue:n}:await sl({value:n,schema:t})}catch(t){return{success:!1,error:Wc.isInstance(t)?t:new Wc({text:e,cause:t}),rawValue:void 0}}}var{btoa:ll,atob:ul}=globalThis;function dl(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}const X=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch{throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},fl=q.object({per_page:q.number().int().positive().max(100).default(10).optional(),page:q.number().int().nonnegative().default(0).optional()}),pl=e=>q.object({has_more:q.boolean(),items:q.array(e)}),ml=q.object({limit:q.number().int().positive().max(100).default(10).optional(),cursor:q.string().optional()}),hl=e=>q.object({next_cursor:q.string().nullable(),items:q.array(e)}),gl=q.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),_l=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,vl=(e,t)=>{let n=new Oc;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),yl(n.readable,t)},yl=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await cl({text:e.data});if(!r.success){n.error(r.error);return}let i=t.safeParse({event:e.event,data:r.value});if(!i.success){n.error(i.error);return}n.enqueue(i.data)}}));return dl(n)};q.union([q.object({agent_id:q.uuid(),deployment_id:q.uuid()}),q.object({agent_id:q.uuid(),deployment_number:q.number().int().positive()})]),q.object({agent_id:q.uuid(),deployment_id:q.uuid()});const bl=q.object({path:q.string(),id:q.uuid()}),xl=bl.or(q.object({path:q.string(),data:q.string().max(1024*1024*5)})),Sl=q.enum([`production`,`preview`]);q.object({agent_id:q.uuid(),output_files:q.array(xl).optional(),source_files:q.array(xl).optional(),files:q.array(xl).optional(),target:Sl,entrypoint:q.string().optional(),message:q.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e);const Cl=q.object({id:q.uuid(),number:q.number().int().positive(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid().nullable(),created_from:q.enum([`cli`]),agent_id:q.uuid(),source_files:q.array(bl),output_files:q.array(bl),status:q.enum([`success`,`failed`,`deploying`,`pending`]),target:Sl,error_message:q.string().nullable(),user_message:q.string().nullable(),platform:q.enum([`lambda`]),platform_memory_mb:q.number().int().positive(),platform_region:q.string().nullable()});q.object({id:q.uuid(),created_at:q.string().datetime(),updated_at:q.string().datetime(),agent_id:q.uuid(),deployment_id:q.uuid(),level:q.enum([`log`,`info`,`warning`,`error`]),message:q.string()}),fl.extend({agent_id:q.uuid(),order:q.enum([`asc`,`desc`]).default(`asc`).optional()}),pl(Cl);var wl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t;t=`deployment_id`in e?e.deployment_id:e.deployment_number.toString();let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${t}`);return await X(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await X(t,200)}};q.object({agent_id:q.uuid(),target:Sl.array().optional()}),q.object({id:q.uuid(),created_at:q.date(),updated_at:q.date(),created_by:q.uuid(),updated_by:q.uuid(),key:q.string(),value:q.string().nullable(),secret:q.boolean(),target:Sl.array()});const Tl=q.object({key:q.string(),value:q.string(),secret:q.boolean(),target:Sl.array().optional(),upsert:q.boolean().optional()});Tl.extend({agent_id:q.uuid()}),q.object({agent_id:q.uuid(),id:q.uuid()}),q.object({agent_id:q.uuid(),id:q.uuid(),key:q.string().optional(),value:q.string().optional(),secret:q.boolean().optional(),target:Sl.array().default([`preview`,`production`]).optional()});var El=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await X(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await X(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await X(t,200),t.json()}};const Dl=q.object({id:q.string(),agent_id:q.uuid(),agent_deployment_id:q.uuid(),received_at:q.date(),request_method:q.string(),request_handler_location:q.string().nullable(),duration_ms:q.number().nullable(),error:q.string().nullable(),response_status:q.number().nullable()});Dl.extend({request_headers:q.record(q.string(),q.string()),request_headers_redacted:q.boolean(),request_body:q.string().nullable(),request_body_redacted:q.boolean(),response_headers:q.record(q.string(),q.string()).nullable(),response_headers_redacted:q.boolean(),response_body:q.string().nullable(),response_body_redacted:q.boolean()}),ml.extend({agent_id:q.string(),agent_deployment_id:q.number().optional()}),hl(Dl);var Ol=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await X(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await X(n,200),n.json()}};ml.extend({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional()}),q.object({agent_id:q.uuid(),run_id:q.uuid()});var kl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await X(t,200),t.json()}};const Al=q.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),jl=q.enum([`tool_call`,`queued_message`]),Ml=q.object({id:q.uuid(),number:q.number().int().positive(),chat_id:q.uuid(),chat_run_id:q.uuid(),agent_id:q.uuid(),agent_deployment_id:q.uuid(),started_at:q.string().datetime(),status:Al,error:q.string().nullable(),continuation_reason:jl.nullable(),response_status:q.number().nullable(),response_message_id:q.uuid().nullable(),time_to_first_token_micros:q.number().nullable()});Ml.extend({heartbeat_at:q.date(),completed_at:q.date().nullable(),interrupted_at:q.date().nullable(),first_message_id:q.uuid().nullable(),last_message_id:q.uuid().nullable(),response_headers:q.record(q.string(),q.string()).nullable(),response_headers_redacted:q.boolean(),response_body:q.string().nullable(),response_body_redacted:q.boolean(),usage_model:q.string().nullable(),usage_total_input_tokens:q.number().nullable(),usage_total_output_tokens:q.number().nullable(),usage_total_tokens:q.number().nullable(),usage_total_cached_input_tokens:q.number().nullable(),usage_cost_usd:q.number().nullable()}),ml.extend({chat_id:q.uuid(),run_id:q.uuid().optional()}),hl(Ml);var Nl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await X(t,200),t.json()}};ml.extend({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),chat_id:q.uuid().optional(),run_id:q.uuid().optional(),status:Al.optional()}),hl(Ml);var Pl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await X(t,200),t.json()}};const Fl=q.object({type:q.literal(`eq`),key:q.string(),value:q.string()}),Il=q.object({type:q.literal(`and`),get filters(){return q.array(q.union([Fl,Il]))}});q.object({start_time:q.iso.datetime().pipe(q.coerce.date()),end_time:q.iso.datetime().pipe(q.coerce.date()),filters:q.string().transform(e=>JSON.parse(e)).pipe(Il),limit:q.string().pipe(q.coerce.number().min(1).max(1e4)).optional()});var Ll=class{constructor(e){this.client=e}async spans(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),t.set(`filters`,JSON.stringify(e.filters)),e.limit!==void 0&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/traces/spans?${t.toString()}`);return await X(n,200),await n.json()}};K.object({start_time:K.iso.datetime().pipe(K.coerce.date()),end_time:K.iso.datetime().pipe(K.coerce.date()),message_pattern:K.string().optional(),filters:K.string().transform(e=>JSON.parse(e)).pipe(Il).optional(),limit:K.string().pipe(K.coerce.number().min(1).max(1e4)).optional()});const Rl=K.object({timestamp:K.iso.datetime().pipe(K.coerce.date()),message:K.string(),level:K.enum([`info`,`error`,`warn`])}),zl=K.object({logs:K.array(Rl)});var Bl=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern),e.filters&&t.set(`filters`,JSON.stringify(e.filters));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await X(n,200);let r=await n.json();return zl.parse(r)}};const Vl=q.enum([`private`,`public`]);q.object({organization_id:q.uuid(),name:q.string().regex(_l),description:q.string().optional(),visibility:Vl.default(`private`).optional(),source_files:q.array(xl).optional(),output_files:q.array(xl).optional(),entrypoint:q.string().optional(),env:q.array(Tl).optional(),request_id:q.uuid().optional()});const Hl=q.object({id:q.uuid(),organization_id:q.uuid(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid(),name:q.string().regex(_l),description:q.string().nullable(),avatar_url:q.string().nullable(),visibility:Vl,active_deployment_id:q.uuid().nullable(),pinned:q.boolean().default(!1),request_url:q.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)});q.object({id:q.uuid(),name:q.string().regex(_l).optional(),description:q.string().optional(),visibility:Vl.optional(),active_deployment_id:q.uuid().optional(),avatar_file_id:q.uuid().nullable().optional()}),fl.extend({organization_id:q.uuid().optional(),pinned:q.boolean().optional()}),pl(Hl),q.object({agent_id:q.uuid(),input:q.string(),caret:q.number().optional(),selection:q.tuple([q.number(),q.number()]).optional(),chat_id:q.uuid().optional(),agent_deployment_id:q.uuid().optional()});const Ul=q.object({text:q.string(),caret:q.number().optional(),selection:q.tuple([q.number(),q.number()]).optional()});q.object({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),selected:q.record(q.string(),q.string()).optional()}),q.object({agent_id:q.uuid(),start_time:q.iso.datetime().pipe(q.coerce.date()),end_time:q.iso.datetime().pipe(q.coerce.date())}),q.object({seconds:q.string()});var Wl=class{constructor(e){this.client=e,this.deployments=new wl(e),this.env=new El(e),this.webhook=new Ol(e),this.runs=new kl(e),this.steps=new Pl(e),this.logs=new Bl(e),this.traces=new Ll(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await X(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await X(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),typeof e.pinned==`boolean`&&t.set(`pinned`,e.pinned.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await X(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await X(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return dl(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return vl(t,Ul)}async uiOptions(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.selected&&t.set(`selected`,JSON.stringify(e.selected));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/ui-options?${t.toString()}`);return await X(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await X(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await X(t,204)}async getRuntimeUsage(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/usage/runtime?${t.toString()}`);return await X(n,200),n.json()}},Gl=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await X(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await X(t,200),new File([await t.blob()],``)}};const Kl=q.enum([`owner`,`admin`,`billing_admin`,`member`]),ql=q.object({user_id:q.uuid(),organization_id:q.uuid(),role:Kl,created_at:q.date(),updated_at:q.date()}),Jl=q.object({id:q.uuid(),created_at:q.date(),updated_at:q.date(),display_name:q.string().nullable(),email:q.email(),avatar_url:q.url().nullable(),username:q.string()}),Yl=ql.extend({user:Jl});fl.extend({organization_id:q.uuid()}),pl(Yl),q.object({organization_id:q.uuid(),user_id:q.uuid()}),q.object({role:q.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:q.uuid(),user_id:q.uuid()});var Xl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await X(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await X(t,200),t.json()}},Zl=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await X(t,200),t.json()}};q.object({id:q.uuid(),name:q.string(),created_at:q.date(),updated_at:q.date(),membership:ql.nullable(),members_url:q.url(),invites_url:q.url(),avatar_url:q.url().nullable()}),q.object({name:q.string().regex(_l)}),q.object({name:q.string().max(100).optional(),avatar_file_id:q.string().nullable().optional(),avatar_url:q.string().url().nullable().optional()});var Ql=class{constructor(e){this.client=e,this.members=new Xl(e),this.agents=new Zl(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await X(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await X(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await X(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await X(t,204)}};K.object({id:K.uuid(),created_at:K.date(),updated_at:K.date(),email:K.string().email(),email_verified:K.boolean(),display_name:K.string(),username:K.string(),organization_id:K.uuid(),avatar_url:K.string().url().nullable()}),K.object({display_name:K.string().max(100).optional(),username:K.string().regex(_l).optional(),avatar_file_id:K.string().nullable().optional()});const $l=K.object({provider:K.enum([`github`,`google`]),provider_account_id:K.string()});K.object({github:K.array($l),google:K.array($l)});var eu=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await X(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await X(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await X(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await X(e,204)}};const tu=q.enum([`ai-sdk`]),nu=q.array(q.custom()),ru=q.enum([`user`,`assistant`,`system`]),iu=q.object({id:q.uuid(),created_at:q.string().datetime(),chat_id:q.uuid(),metadata:gl}).extend({format:q.literal(`ai-sdk`),parts:nu,role:ru}),au=q.discriminatedUnion(`format`,[iu]);ml.extend({chat_id:q.uuid(),format:tu.default(`ai-sdk`).optional()}),hl(au),q.object({chat_id:q.uuid(),message_id:q.uuid()});const ou=q.object({id:q.uuid().optional(),role:ru,parts:nu,metadata:gl.optional(),format:q.literal(`ai-sdk`).optional()});q.object({message_id:q.uuid(),metadata:gl.optional(),role:ru.optional(),parts:nu.optional(),format:q.literal(`ai-sdk`).optional(),behavior:q.enum([`interrupt`,`enqueue`,`none`]).optional()});const su=q.enum([`enqueue`,`interrupt`,`append`]);q.object({chat_id:q.uuid(),behavior:su.optional(),messages:q.array(ou).min(1)}),q.object({messages:q.array(au)});var cu=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;t.set(`chat_id`,e.chat_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor),e.format&&t.set(`format`,e.format);let n=await this.client.request(`GET`,`/api/messages?${t.toString()}`);return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await X(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await X(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await X(t,201),t.json()}};ml.extend({chat_id:q.uuid()});const lu=q.object({id:q.uuid(),started_at:q.date(),agent_id:q.uuid(),agent_deployment_id:q.uuid().nullable(),chat_id:q.uuid(),step_count:q.number().int().positive(),status:Al.nullable(),error:q.string().nullable()});hl(lu);var uu=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs?${t.toString()}`);return await X(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs/${e.run_id}`);return await X(t,200),t.json()}};const du=q.enum([`streaming`,`idle`,`error`,`interrupted`]),fu=q.enum([`private`,`organization`,`public`]),pu=q.object({id:q.uuid(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid().nullable(),organization_id:q.uuid(),title:q.string().nullable(),visibility:fu,metadata:gl,archived:q.boolean(),status:du,error:q.string().nullable(),agent_deployment_id:q.uuid().nullable(),agent:Hl});q.enum([`websocket`,`sse`]);const mu=q.object({organization_id:q.uuid(),title:q.string().optional(),visibility:fu.default(`private`).optional(),metadata:gl.optional(),agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),messages:q.array(ou).optional()}),hu=mu.extend({stream:q.literal(!0)}),gu=mu.extend({stream:q.literal(!1).optional()});q.union([hu,gu]),q.union([ml.extend({organization_id:q.uuid()}),ml.extend({agent_id:q.uuid()})]);const _u=pu.extend({messages:q.array(au)});hl(pu);const vu=q.discriminatedUnion(`event`,[q.strictObject({event:q.literal(`chat.updated`),data:pu}),q.strictObject({event:q.literal(`message.created`),data:au}),q.strictObject({event:q.literal(`message.updated`),data:au}),q.strictObject({event:q.literal(`message.deleted`),data:q.object({id:q.uuid()})}),q.strictObject({event:q.literal(`message.chunk.added`),data:q.object({id:q.uuid(),chunk:q.custom()})})]),yu=q.strictObject({event:q.literal(`chat.created`),data:_u});var bu=class{constructor(e){this.client=e,this.runs=new uu(e),this.steps=new Nl(e)}async create(e){let t={};e.stream&&(t.Accept=`text/event-stream`);let n=await this.client.request(`POST`,`/api/chats`,JSON.stringify(e),{headers:t});if(await X(n,201),e.stream){let e=n.headers.get(`Content-Type`);if(e!==`text/event-stream`)throw Error(`Expected text/event-stream, got ${e}`);if(!n.body)throw Error(`The stream endpoint did not return a body!`);let t=vl(n,q.discriminatedUnion(`event`,[vu,yu])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await X(t,200),t.json()}async list(e){let t=new URLSearchParams;`organization_id`in e&&e.organization_id?t.set(`organization_id`,e.organization_id):`agent_id`in e&&e.agent_id&&t.set(`agent_id`,e.agent_id),e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats?${t.toString()}`);return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await X(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await X(t,200)}async stream(e,t={transport:`websocket`}){if(t?.transport===`websocket`)return this.streamWS(e,t?.signal);let n=await this.client.request(`GET`,`/api/chats/${e}/stream`,void 0,{abortSignal:t?.signal,headers:{Accept:`text/event-stream`}});return await X(n,200),vl(n,vu)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new Oc,i=r.writable.getWriter(),a,o=new TextDecoder,s=!1,c=()=>{if(!s){s=!0,a?a.finally(()=>{i.close().catch(()=>{})}):i.close().catch(()=>{});try{n.close()}catch{}}};return t&&(t.aborted?c():t.addEventListener(`abort`,c,{once:!0})),n.addEventListener(`error`,()=>{c()}),n.addEventListener(`close`,()=>{c()}),n.addEventListener(`message`,e=>{if(s)return;let t;t=typeof e.data==`string`?e.data:o.decode(e.data),a=a?a.then(()=>{if(!s)return i.write(t).catch(()=>{})}):i.write(t).catch(()=>{})}),yl(r.readable,vu)}};q.object({id:q.uuid(),organization_id:q.uuid(),role:Kl,invited_by:q.uuid(),expires_at:q.date(),created_at:q.date(),updated_at:q.date(),reusable:q.boolean(),accepted_at:q.date().nullable(),email:q.string().email().nullable()}),q.object({organization_id:q.uuid(),role:Kl,email:q.string().email().optional(),reusable:q.boolean().optional()}),q.object({organization_id:q.uuid()}),q.object({organization_id:q.uuid(),invite_id:q.uuid()}),q.object({code:q.string()}).extend({invite_id:q.uuid()});var xu=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await X(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await X(t,204)}async accept(e){let t=await this.client.request(`POST`,`/api/invites/${e.invite_id}/accept`,JSON.stringify({code:e.code}));return await X(t,201),t.json()}},Su=class{constructor(e){this.chats=new bu(this),this.runs=new uu(this),this.agents=new Wl(this),this.files=new Gl(this),this.organizations=new Ql(this),this.invites=new xu(this),this.users=new eu(this),this.messages=new cu(this),this.baseURL=new URL(e?.baseURL??(globalThis.window===void 0?`https://blink.so`:window.location.origin)),this.fetch=e?.fetch,this.authToken=e?.authToken,this.auth=new Cc(this,this.baseURL)}request(e,t,n,r){let i=new URL(t,this.baseURL),a=new Headers;if(this.authToken&&a.set(`Authorization`,`Bearer ${this.authToken}`),typeof n==`string`&&a.set(`Content-Type`,`application/json`),r?.headers)for(let[e,t]of Object.entries(r.headers))a.set(e,t);let o;if(r?.abortSignal&&r?.timeout)throw Error(`Cannot specify both abortSignal and timeout`);return r?.abortSignal&&(o=r.abortSignal),r?.timeout&&(o=AbortSignal.timeout(r.timeout)),(this.fetch??fetch)(i.toString(),{method:e,headers:a,body:n,signal:o})}websocket(e){let t=new URL(e,this.baseURL);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,new WebSocket(t.toString())}},Cu=Sc({"../../node_modules/@blink-sdk/compute-protocol/dist/schema-CZdQiIXB.cjs":(e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>function(){return t||(0,e[i(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=Y(`zod`);u=l(u);let d=(e,t)=>{let n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},f=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},p=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1)),m=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),h=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({}),g={[m.REQUEST]:u.z.string(),[m.PROXY_INIT]:u.z.object({method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}),[m.PROXY_BODY]:u.z.instanceof(Uint8Array),[m.PROXY_WEBSOCKET_MESSAGE]:u.z.object({type:u.z.enum([`text`,`binary`]),data:u.z.instanceof(Uint8Array)}),[m.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number().optional(),reason:u.z.string().optional()})},_={[h.RESPONSE]:u.z.string(),[h.NOTIFICATION]:u.z.string(),[h.PROXY_INIT]:u.z.object({status_code:u.z.number(),status_message:u.z.string(),headers:u.z.record(u.z.string(),u.z.string())}),[h.PROXY_DATA]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_MESSAGE]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number(),reason:u.z.string()})},v={[m.PROXY_INIT]:{method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}},y={process_execute:u.z.object({command:u.z.string(),args:u.z.array(u.z.string()),env:u.z.record(u.z.string(),u.z.string()).optional(),cwd:u.z.string().optional()}),process_send_input:u.z.object({pid:u.z.number(),data:u.z.string()}),process_wait:u.z.object({pid:u.z.number(),output_idle_timeout_ms:u.z.number().optional(),timeout_ms:u.z.number().optional()}),process_list:u.z.object({include_dead:u.z.boolean().optional()}),process_read_plain_output:u.z.object({pid:u.z.number(),start_line:u.z.number().optional(),end_line:u.z.number().optional()}),process_kill:u.z.object({pid:u.z.number(),signal:u.z.string().optional()}),set_env:u.z.object({env:u.z.record(u.z.string(),u.z.string())}),read_file:u.z.object({path:u.z.string(),line_start:u.z.number().optional(),line_end:u.z.number().optional()}),write_file:u.z.object({path:u.z.string(),content:u.z.string(),base64:u.z.boolean().optional(),mode:u.z.number().optional()}),read_directory:u.z.object({path:u.z.string()}),watch_directory:u.z.object({path:u.z.string()}),deploy_static_files:u.z.object({path:u.z.string()})},b=u.z.object({pid:u.z.number(),command:u.z.string(),args:u.z.array(u.z.string()),title:u.z.string().optional(),cwd:u.z.string(),env:u.z.record(u.z.string(),u.z.string()),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional(),duration_ms:u.z.number().optional(),output_total_lines:u.z.number()}),x=b.extend({ansi_output:u.z.string(),plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number()})}),S={process_execute:u.z.object({pid:u.z.number()}),process_send_input:u.z.object({}),process_wait:x,process_list:u.z.object({processes:u.z.array(b)}),process_read_plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number(),duration_ms:u.z.number(),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional()}),process_kill:u.z.object({}),set_env:u.z.object({}),read_file:u.z.object({total_lines:u.z.number(),lines_read:u.z.number(),start_line:u.z.number(),content:u.z.string(),mime_type:u.z.string()}),write_file:u.z.object({}),read_directory:u.z.object({entries:u.z.array(u.z.object({name:u.z.string(),type:u.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:u.z.object({}),deploy_static_files:u.z.object({deployment_id:u.z.string()})},C=u.z.object({type:u.z.enum([`create`,`update`,`delete`]),path:u.z.string()}),w=u.z.object({type:u.z.enum([`context`,`added`,`deleted`]),content:u.z.string(),oldLineNumber:u.z.number().optional(),newLineNumber:u.z.number().optional()}),T=u.z.object({oldStart:u.z.number(),oldLines:u.z.number(),newStart:u.z.number(),newLines:u.z.number(),lines:u.z.array(w)}),E=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:u.z.string().optional(),insertions:u.z.number(),deletions:u.z.number(),chunks:u.z.array(T)}),D=u.z.object({totalFiles:u.z.number(),totalInsertions:u.z.number(),totalDeletions:u.z.number(),netChange:u.z.number(),startHash:u.z.string().optional(),currentHash:u.z.string().optional(),timespan:u.z.number(),files:u.z.array(E)}),O=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:u.z.boolean()}),k=u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),email:u.z.string(),date:u.z.date(),timestamp:u.z.date(),filesChanged:u.z.number(),insertions:u.z.number(),deletions:u.z.number(),commitDiff:u.z.array(E).optional()}),A=u.z.object({files:u.z.array(O),branch:u.z.string(),ahead:u.z.number(),behind:u.z.number(),timestamp:u.z.date(),sessionDiff:D.optional(),workingDirectoryDiff:D.optional(),newCommits:u.z.array(k),currentCommit:u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),date:u.z.date()}).optional(),diffSkipped:u.z.boolean().optional(),payloadTruncated:u.z.boolean().optional(),estimatedSizeKB:u.z.number().optional()}),j=u.z.object({debounceDelay:u.z.number().optional(),gitStatusInterval:u.z.number().optional(),ignoreDotfiles:u.z.boolean().optional(),ignored:u.z.array(u.z.string()).optional(),watchGit:u.z.boolean().optional(),includeDiffs:u.z.boolean().optional(),maxDiffFiles:u.z.number().optional(),maxPayloadSizeKB:u.z.number().optional(),truncateLargeDiffs:u.z.boolean().optional()}),M={process_status:u.z.object({status:b}),process_output:u.z.object({pid:u.z.number(),output:u.z.string()}),file_change:u.z.object({changes:u.z.array(C)}),git_status:A};Object.defineProperty(e,`ClientMessageSchema`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`ClientMessageType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`DiffChunkSchema`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`DiffLineSchema`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`DiffSummarySchema`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`FileChangeEventSchema`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`FileDiffSchema`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`GitCommitEventSchema`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`GitFileStatusSchema`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`GitStatusEventSchema`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`NotificationSchema`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`ProcessStatusSchema`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`ProcessWaitSchema`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`ProxySchema`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`RequestSchema`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`ResponseSchema`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`ServerMessageSchema`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`ServerMessageType`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`WatchOptionsSchema`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`__commonJS`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`__toESM`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`createMessagePayload`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`createWebSocketMessagePayload`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`parseWebSocketMessagePayload`,{enumerable:!0,get:function(){return p}})})}),wu=Sc({"../../node_modules/ws/lib/constants.js":((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})}),Tu=Sc({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=wu(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=Y(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})}),Eu=Sc({"../../node_modules/ws/lib/limiter.js":((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})}),Du=Sc({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=Y(`zlib`),r=Tu(),i=Eu(),{kStatusCode:a}=wu(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})}),Ou=Sc({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=Y(`buffer`),{hasBlob:r}=wu(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Y(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),ku=Sc({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=Y(`stream`),r=Du(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=wu(),{concat:c,toArrayBuffer:l,unmask:u}=Tu(),{isValidStatusCode:d,isValidUTF8:f}=Ou(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})}),Au=Sc({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=Y(`stream`),{randomFillSync:r}=Y(`crypto`),i=Du(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=wu(),{isBlob:c,isValidStatusCode:l}=Ou(),{mask:u,toBuffer:d}=Tu(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})}),ju=Sc({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=wu(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})}),Mu=Sc({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Ou();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})}),Nu=Sc({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=Y(`events`),r=Y(`https`),i=Y(`http`),a=Y(`net`),o=Y(`tls`),{randomBytes:s,createHash:c}=Y(`crypto`),{Duplex:l,Readable:u}=Y(`stream`),{URL:d}=Y(`url`),f=Du(),p=ku(),m=Au(),{isBlob:h}=Ou(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=wu(),{EventTarget:{addEventListener:w,removeEventListener:T}}=ju(),{format:E,parse:D}=Mu(),{toBuffer:O}=Tu(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ee(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,L),i.on(`drain`,re),i.on(`error`,R),i.on(`message`,z),i.on(`ping`,ae),i.on(`pong`,oe),a.onerror=ce,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,B),t.on(`data`,ue),t.on(`end`,de),t.on(`error`,fe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),le(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){I(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){I(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){I(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function ee(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;te(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?ne:P),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{F(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,te(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);te(e,t);return}ee(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||F(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function te(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function ne(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(te,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function I(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function L(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,ue),process.nextTick(se,n._socket),e===1005?n.close():n.close(e,t))}function re(){let e=this[S];e.isPaused||e._socket.resume()}function R(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,ue),process.nextTick(se,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ie(){this[S].emitClose()}function z(e,t){this[S].emit(`message`,e,t)}function ae(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function oe(e){this[S].emit(`pong`,e)}function se(e){e.resume()}function ce(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,le(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function le(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function B(){let e=this[S];this.removeListener(`close`,B),this.removeListener(`data`,ue),this.removeListener(`end`,de),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ie),e._receiver.on(`finish`,ie))}function ue(e){this[S]._receiver.write(e)||this.pause()}function de(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function fe(){let e=this[S];this.removeListener(`error`,fe),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})}),Pu=Sc({"../../node_modules/ws/lib/stream.js":((e,t)=>{Nu();let{Duplex:n}=Y(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})}),Fu=Sc({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Ou();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})}),Iu=Sc({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=Y(`events`),r=Y(`http`),{Duplex:i}=Y(`stream`),{createHash:a}=Y(`crypto`),o=Mu(),s=Du(),c=Fu(),l=Nu(),{GUID:u,kWebSocket:d}=wu(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
22
22
|
`).join(`\r
|
|
23
23
|
`)),i.removeListener(`error`,h),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(m,this)})),l(p,r)}};function p(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function m(e){e._state=2,e.emit(`close`)}function h(){this.destroy()}function g(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
24
24
|
`)+`\r
|
|
25
25
|
\r
|
|
26
|
-
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})}),fs=Ji({"../../node_modules/ws/index.js":((e,t)=>{let n=cs();n.createWebSocketStream=ls(),n.Server=ds(),n.Receiver=ns(),n.Sender=rs(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),ps=Ji({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Xo(),o=Z(`node:fs/promises`);o=a.__toESM(o);let s=Z(`module`);s=a.__toESM(s);let c=Z(`fs/promises`);c=a.__toESM(c);let l=Z(`child_process`);l=a.__toESM(l);let u=fs();u=a.__toESM(u);let d=Z(`node:fs`);d=a.__toESM(d);var f=class{constructor(){this.listeners=[]}get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let p=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),m=function(e){return e[e.NEW=1]=`NEW`,e}({});var h=(t=class{static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},t.MAX_POOL_SIZE=100,t.COMMON_SIZES=[64,256,1024,4096,16384],t.pools=new Map,(()=>{for(let e of t.COMMON_SIZES)t.pools.set(e,[])})(),t),g=(n=class e{static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=h.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=h.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){h.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},n.HEADER_SIZE=4,n.MAX_FRAME_SIZE=1024*1024-n.HEADER_SIZE,n),_=class{constructor(e,t,n){this._disposed=!1,this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new f,this._onData.event}get onClose(){return this._onClose||=new f,this._onClose.event}get onError(){return this._onError||=new f,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=g.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:p.DATA,flags:t?m.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:p.DATA,flags:t&&i?m.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=g.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?m.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?m.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:p.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:p.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case p.DATA:this._onData?.emit(e.payload);break;case p.CLOSE:this._onClose?.emit(),this._dispose();break;case p.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},v=(r=class{static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new _(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},r.MAX_POOL_SIZE=200,r.pool=[],r),y=class{constructor(e){this._onNextStreamIDChange=new f,this.onNextStreamIDChange=this._onNextStreamIDChange.event,this._onStream=new f,this.onStream=this._onStream.event,this.streams=[],this.streamCount=0,this.nextStreamId=1,this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=v.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=g.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&g.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=g.encodeTyped(e,p.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&g.releaseBuffer(i)}}handleMessage(e){this.handleFrame(g.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=v.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===p.CLOSE||e.type===p.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,v.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),v.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}},b=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},x=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},S=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new b;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new x;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new b;return n}},C=class extends S{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},w=class extends C{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},T=class extends S{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new b;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function E(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new T(t):new w(t)}catch(t){if(t instanceof TypeError)return new T(e.getReader());throw t}}var D=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},O=class extends D{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new b;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof b)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new b}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},k=class extends D{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new b;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function A(e,t){let n=E(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new O(n,r)}function j(e,t){return new k(e,t)}let ee={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},M={};for(let[e,t]of Object.entries(ee))M[t]=Number.parseInt(e);function te(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?ne(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return re(e);case`ascii`:return N(e);case`latin1`:case`iso-8859-1`:return P(e);case`windows-1252`:return F(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function ne(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function re(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function N(e){return String.fromCharCode(...e.map(e=>e&127))}function P(e){return String.fromCharCode(...e)}function F(e){let t=``;for(let n of e)n>=128&&n<=159&&ee[n]?t+=ee[n]:t+=String.fromCharCode(n);return t}function I(e){return new DataView(e.buffer,e.byteOffset)}let L={len:1,get(e,t){return I(e).getUint8(t)},put(e,t,n){return I(e).setUint8(t,n),t+1}},R={len:2,get(e,t){return I(e).getUint16(t,!0)},put(e,t,n){return I(e).setUint16(t,n,!0),t+2}},ie={len:2,get(e,t){return I(e).getUint16(t)},put(e,t,n){return I(e).setUint16(t,n),t+2}},z={len:4,get(e,t){return I(e).getUint32(t,!0)},put(e,t,n){return I(e).setUint32(t,n,!0),t+4}},ae={len:4,get(e,t){return I(e).getUint32(t)},put(e,t,n){return I(e).setUint32(t,n),t+4}},oe={len:4,get(e,t){return I(e).getInt32(t)},put(e,t,n){return I(e).setInt32(t,n),t+4}},se={len:8,get(e,t){return I(e).getBigUint64(t,!0)},put(e,t,n){return I(e).setBigUint64(t,n,!0),t+8}};var ce=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return te(n,this.encoding)}},B=(0,s.createRequire)(`/`);try{B(`worker_threads`).Worker}catch{}var V=Uint8Array,H=Uint16Array,le=Int32Array,ue=new V([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),de=new V([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),fe=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pe=function(e,t){for(var n=new H(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new le(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},me=pe(ue,2),he=me.b,ge=me.r;he[28]=258,ge[258]=28;var _e=pe(de,0),ve=_e.b;_e.r;for(var ye=new H(32768),U=0;U<32768;++U){var be=(U&43690)>>1|(U&21845)<<1;be=(be&52428)>>2|(be&13107)<<2,be=(be&61680)>>4|(be&3855)<<4,ye[U]=((be&65280)>>8|(be&255)<<8)>>1}for(var xe=(function(e,t,n){for(var r=e.length,i=0,a=new H(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new H(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new H(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[ye[d]>>c]=l}else for(s=new H(r),i=0;i<r;++i)e[i]&&(s[i]=ye[o[e[i]-1]++]>>15-e[i]);return s}),Se=new V(288),U=0;U<144;++U)Se[U]=8;for(var U=144;U<256;++U)Se[U]=9;for(var U=256;U<280;++U)Se[U]=7;for(var U=280;U<288;++U)Se[U]=8;for(var Ce=new V(32),U=0;U<32;++U)Ce[U]=5;var we=xe(Se,9,1),Te=xe(Ce,5,1),Ee=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},De=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Oe=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},ke=function(e){return(e+7)/8|0},Ae=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new V(e.subarray(t,n))},je=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],W=function(e,t,n){var r=Error(t||je[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,W),!n)throw r;return r},Me=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new V(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new V(i*3));var l=function(e){var t=n.length;if(e>t){var r=new V(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=De(e,d,1);var v=De(e,d+1,3);if(d+=3,v)if(v==1)p=we,m=Te,h=9,g=5;else if(v==2){var y=De(e,d,31)+257,b=De(e,d+10,15)+4,x=y+De(e,d+5,31)+1;d+=14;for(var S=new V(x),C=new V(19),w=0;w<b;++w)C[fe[w]]=De(e,d+w*3,7);d+=b*3;for(var T=Ee(C),E=(1<<T)-1,D=xe(C,T,1),w=0;w<x;){var O=D[De(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+De(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+De(e,d,7),d+=3):k==18&&(j=11+De(e,d,127),d+=7);j--;)S[w++]=A}}var ee=S.subarray(0,y),M=S.subarray(y);h=Ee(ee),g=Ee(M),p=xe(ee,h,1),m=xe(M,g,1)}else W(1);else{var k=ke(d)+4,te=e[k-4]|e[k-3]<<8,ne=k+te;if(ne>i){c&&W(0);break}s&&l(f+te),n.set(e.subarray(k,ne),f),t.b=f+=te,t.p=d=ne*8,t.f=u;continue}if(d>_){c&&W(0);break}}s&&l(f+131072);for(var re=(1<<h)-1,N=(1<<g)-1,P=d;;P=d){var A=p[Oe(e,d)&re],F=A>>4;if(d+=A&15,d>_){c&&W(0);break}if(A||W(2),F<256)n[f++]=F;else if(F==256){P=d,p=null;break}else{var I=F-254;if(F>264){var w=F-257,L=ue[w];I=De(e,d,(1<<L)-1)+he[w],d+=L}var R=m[Oe(e,d)&N],ie=R>>4;R||W(3),d+=R&15;var M=ve[ie];if(ie>3){var L=de[ie];M+=Oe(e,d)&(1<<L)-1,d+=L}if(d>_){c&&W(0);break}s&&l(f+131072);var z=f+I;if(f<M){var ae=a-M,oe=Math.min(M,z);for(ae+f<0&&W(3);f<oe;++f)n[f]=r[ae+f]}for(;f<z;++f)n[f]=n[f-M]}}t.l=p,t.p=P,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Ae(n,0,f):n.subarray(0,f)},Ne=new V(0),Pe=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&W(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Fe=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},G=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&W(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&W(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function K(e,t){return Me(e,{i:2},t&&t.out,t&&t.dictionary)}function Ie(e,t){var n=Pe(e);return n+8>e.length&&W(6,`invalid gzip data`),Me(e.subarray(n,-8),{i:2},t&&t.out||new V(Fe(e)),t&&t.dictionary)}function Le(e,t){return Me(e.subarray(G(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function q(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Ie(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?K(e,t):Le(e,t)}var J=typeof TextDecoder<`u`&&new TextDecoder;try{J.decode(Ne,{stream:!0})}catch{}var Y=a.__commonJS({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),Re=a.__commonJS({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Y(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),ze=a.__commonJS({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=Re()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Be=a.__commonJS({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),Ve=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Z(`os`),r=Z(`tty`),i=Be(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){let t=c(e,e&&e.isTTY);return s(t)}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})}),X=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Z(`tty`),r=Z(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=Ve();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
26
|
+
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})}),Lu=Sc({"../../node_modules/ws/index.js":((e,t)=>{let n=Nu();n.createWebSocketStream=Pu(),n.Server=Iu(),n.Receiver=ku(),n.Sender=Au(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),Ru=Sc({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Cu(),o=Y(`node:fs/promises`);o=a.__toESM(o);let s=Y(`module`);s=a.__toESM(s);let c=Y(`fs/promises`);c=a.__toESM(c);let l=Y(`child_process`);l=a.__toESM(l);let u=Lu();u=a.__toESM(u);let d=Y(`node:fs`);d=a.__toESM(d);var f=class{constructor(){this.listeners=[]}get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let p=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),m=function(e){return e[e.NEW=1]=`NEW`,e}({});var h=(t=class{static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},t.MAX_POOL_SIZE=100,t.COMMON_SIZES=[64,256,1024,4096,16384],t.pools=new Map,(()=>{for(let e of t.COMMON_SIZES)t.pools.set(e,[])})(),t),g=(n=class e{static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=h.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=h.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){h.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},n.HEADER_SIZE=4,n.MAX_FRAME_SIZE=1024*1024-n.HEADER_SIZE,n),_=class{constructor(e,t,n){this._disposed=!1,this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new f,this._onData.event}get onClose(){return this._onClose||=new f,this._onClose.event}get onError(){return this._onError||=new f,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=g.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:p.DATA,flags:t?m.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:p.DATA,flags:t&&i?m.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=g.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?m.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?m.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:p.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:p.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case p.DATA:this._onData?.emit(e.payload);break;case p.CLOSE:this._onClose?.emit(),this._dispose();break;case p.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},v=(r=class{static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new _(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},r.MAX_POOL_SIZE=200,r.pool=[],r),y=class{constructor(e){this._onNextStreamIDChange=new f,this.onNextStreamIDChange=this._onNextStreamIDChange.event,this._onStream=new f,this.onStream=this._onStream.event,this.streams=[],this.streamCount=0,this.nextStreamId=1,this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=v.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=g.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&g.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=g.encodeTyped(e,p.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&g.releaseBuffer(i)}}handleMessage(e){this.handleFrame(g.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=v.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===p.CLOSE||e.type===p.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,v.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),v.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}},b=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},x=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},S=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new b;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new x;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new b;return n}},C=class extends S{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},w=class extends C{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},T=class extends S{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new b;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function E(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new T(t):new w(t)}catch(t){if(t instanceof TypeError)return new T(e.getReader());throw t}}var D=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},O=class extends D{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new b;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof b)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new b}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},k=class extends D{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new b;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function A(e,t){let n=E(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new O(n,r)}function j(e,t){return new k(e,t)}let M={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},N={};for(let[e,t]of Object.entries(M))N[t]=Number.parseInt(e);function ee(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?te(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return P(e);case`ascii`:return ne(e);case`latin1`:case`iso-8859-1`:return F(e);case`windows-1252`:return I(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function te(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function P(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function ne(e){return String.fromCharCode(...e.map(e=>e&127))}function F(e){return String.fromCharCode(...e)}function I(e){let t=``;for(let n of e)n>=128&&n<=159&&M[n]?t+=M[n]:t+=String.fromCharCode(n);return t}function L(e){return new DataView(e.buffer,e.byteOffset)}let re={len:1,get(e,t){return L(e).getUint8(t)},put(e,t,n){return L(e).setUint8(t,n),t+1}},R={len:2,get(e,t){return L(e).getUint16(t,!0)},put(e,t,n){return L(e).setUint16(t,n,!0),t+2}},ie={len:2,get(e,t){return L(e).getUint16(t)},put(e,t,n){return L(e).setUint16(t,n),t+2}},z={len:4,get(e,t){return L(e).getUint32(t,!0)},put(e,t,n){return L(e).setUint32(t,n,!0),t+4}},ae={len:4,get(e,t){return L(e).getUint32(t)},put(e,t,n){return L(e).setUint32(t,n),t+4}},oe={len:4,get(e,t){return L(e).getInt32(t)},put(e,t,n){return L(e).setInt32(t,n),t+4}},se={len:8,get(e,t){return L(e).getBigUint64(t,!0)},put(e,t,n){return L(e).setBigUint64(t,n,!0),t+8}};var ce=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return ee(n,this.encoding)}},le=(0,s.createRequire)(`/`);try{le(`worker_threads`).Worker}catch{}var B=Uint8Array,ue=Uint16Array,de=Int32Array,fe=new B([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),pe=new B([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),me=new B([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),he=function(e,t){for(var n=new ue(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new de(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},ge=he(fe,2),_e=ge.b,ve=ge.r;_e[28]=258,ve[258]=28;var ye=he(pe,0),be=ye.b;ye.r;for(var xe=new ue(32768),V=0;V<32768;++V){var Se=(V&43690)>>1|(V&21845)<<1;Se=(Se&52428)>>2|(Se&13107)<<2,Se=(Se&61680)>>4|(Se&3855)<<4,xe[V]=((Se&65280)>>8|(Se&255)<<8)>>1}for(var Ce=(function(e,t,n){for(var r=e.length,i=0,a=new ue(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new ue(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new ue(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[xe[d]>>c]=l}else for(s=new ue(r),i=0;i<r;++i)e[i]&&(s[i]=xe[o[e[i]-1]++]>>15-e[i]);return s}),H=new B(288),V=0;V<144;++V)H[V]=8;for(var V=144;V<256;++V)H[V]=9;for(var V=256;V<280;++V)H[V]=7;for(var V=280;V<288;++V)H[V]=8;for(var U=new B(32),V=0;V<32;++V)U[V]=5;var we=Ce(H,9,1),W=Ce(U,5,1),G=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},K=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},q=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Te=function(e){return(e+7)/8|0},Ee=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new B(e.subarray(t,n))},De=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Oe=function(e,t,n){var r=Error(t||De[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Oe),!n)throw r;return r},J=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new B(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new B(i*3));var l=function(e){var t=n.length;if(e>t){var r=new B(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=K(e,d,1);var v=K(e,d+1,3);if(d+=3,v)if(v==1)p=we,m=W,h=9,g=5;else if(v==2){var y=K(e,d,31)+257,b=K(e,d+10,15)+4,x=y+K(e,d+5,31)+1;d+=14;for(var S=new B(x),C=new B(19),w=0;w<b;++w)C[me[w]]=K(e,d+w*3,7);d+=b*3;for(var T=G(C),E=(1<<T)-1,D=Ce(C,T,1),w=0;w<x;){var O=D[K(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+K(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+K(e,d,7),d+=3):k==18&&(j=11+K(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=G(M),g=G(N),p=Ce(M,h,1),m=Ce(N,g,1)}else Oe(1);else{var k=Te(d)+4,ee=e[k-4]|e[k-3]<<8,te=k+ee;if(te>i){c&&Oe(0);break}s&&l(f+ee),n.set(e.subarray(k,te),f),t.b=f+=ee,t.p=d=te*8,t.f=u;continue}if(d>_){c&&Oe(0);break}}s&&l(f+131072);for(var P=(1<<h)-1,ne=(1<<g)-1,F=d;;F=d){var A=p[q(e,d)&P],I=A>>4;if(d+=A&15,d>_){c&&Oe(0);break}if(A||Oe(2),I<256)n[f++]=I;else if(I==256){F=d,p=null;break}else{var L=I-254;if(I>264){var w=I-257,re=fe[w];L=K(e,d,(1<<re)-1)+_e[w],d+=re}var R=m[q(e,d)&ne],ie=R>>4;R||Oe(3),d+=R&15;var N=be[ie];if(ie>3){var re=pe[ie];N+=q(e,d)&(1<<re)-1,d+=re}if(d>_){c&&Oe(0);break}s&&l(f+131072);var z=f+L;if(f<N){var ae=a-N,oe=Math.min(N,z);for(ae+f<0&&Oe(3);f<oe;++f)n[f]=r[ae+f]}for(;f<z;++f)n[f]=n[f-N]}}t.l=p,t.p=F,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Ee(n,0,f):n.subarray(0,f)},ke=new B(0),Ae=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&Oe(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},je=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Me=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Oe(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Oe(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Ne(e,t){return J(e,{i:2},t&&t.out,t&&t.dictionary)}function Pe(e,t){var n=Ae(e);return n+8>e.length&&Oe(6,`invalid gzip data`),J(e.subarray(n,-8),{i:2},t&&t.out||new B(je(e)),t&&t.dictionary)}function Fe(e,t){return J(e.subarray(Me(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Ie(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Pe(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Ne(e,t):Fe(e,t)}var Le=typeof TextDecoder<`u`&&new TextDecoder;try{Le.decode(ke,{stream:!0})}catch{}var Re=a.__commonJS({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),ze=a.__commonJS({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Re(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),Be=a.__commonJS({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=ze()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ve=a.__commonJS({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),He=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Y(`os`),r=Y(`tty`),i=Ve(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){let t=c(e,e&&e.isTTY);return s(t)}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})}),Ue=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Y(`tty`),r=Y(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=He();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
27
27
|
`).join(`
|
|
28
28
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
29
|
-
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=
|
|
30
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),He=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=ze():t.exports=X()})});let Ue={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},We={get(e){return R.get(e,6),{signature:z.get(e,0),compressedSize:z.get(e,8),uncompressedSize:z.get(e,12)}},len:16},Ge={get(e){let t=R.get(e,6);return{signature:z.get(e,0),minVersion:R.get(e,4),dataDescriptor:!!(t&8),compressedMethod:R.get(e,8),compressedSize:z.get(e,18),uncompressedSize:z.get(e,22),filenameLength:R.get(e,26),extraFieldLength:R.get(e,28),filename:null}},len:30},Ke={get(e){return{signature:z.get(e,0),nrOfThisDisk:R.get(e,4),nrOfThisDiskWithTheStart:R.get(e,6),nrOfEntriesOnThisDisk:R.get(e,8),nrOfEntriesOfSize:R.get(e,10),sizeOfCd:z.get(e,12),offsetOfStartOfCd:z.get(e,16),zipFileCommentLength:R.get(e,20)}},len:22},qe={get(e){let t=R.get(e,8);return{signature:z.get(e,0),minVersion:R.get(e,6),dataDescriptor:!!(t&8),compressedMethod:R.get(e,10),compressedSize:z.get(e,20),uncompressedSize:z.get(e,24),filenameLength:R.get(e,28),extraFieldLength:R.get(e,30),fileCommentLength:R.get(e,32),relativeOffsetOfLocalHeader:z.get(e,42),filename:null}},len:46};var Je=a.__toESM(He(),1);function Ye(e){let t=new Uint8Array(z.len);return z.put(t,0,e),t}let Xe=(0,Je.default)(`tokenizer:inflate`),Ze=256*1024,Qe=Ye(Ue.DataDescriptor),$e=Ye(Ue.EndOfCentralDirectory);var et=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Ze)}async isZip(){return await this.peekSignature()===Ue.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(z)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===$e[0]&&n[r+1]===$e[1]&&n[r+2]===$e[2]&&n[r+3]===$e[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Xe(`Cannot reading central-directory without random-read support`);return}Xe(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Xe(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Ke,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(qe);if(t.signature!==Ue.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new ce(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Xe(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=Ze;Xe(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===Ze;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=tt(this.syncBuffer.subarray(0,n),Qe);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}Xe(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,nt(e),r.handler)}else r.handler?(Xe(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Xe(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Xe(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(We)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-We.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);Xe(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=q(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(z);if(e===Ue.LocalFileHeader){let e=await this.tokenizer.readToken(Ge);return e.filename=await this.tokenizer.readToken(new ce(e.filenameLength,`utf-8`)),e}if(e===Ue.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function tt(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function nt(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function rt(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function it(e){return[...e].map(e=>e.charCodeAt(0))}function at(e,t=0){let n=Number.parseInt(new ce(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}let ot={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},st=4100;async function ct(e,t){return new dt(t).fromBuffer(e)}function lt(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function ut(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}var dt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(st),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return{ext:`gz`,mime:`application/gzip`};if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await e.ignore(6);let t=await e.readToken(ot);return e.position+t>e.fileInfo.size?{ext:`mp3`,mime:`audio/mpeg`}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t;return await new et(e).unzip(e=>{switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e).trim();t=lt(n)},stop:!0};case`[Content_Types].xml`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e),r=n.indexOf(`.main+xml"`);if(r===-1){let e=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;n.includes(`ContentType="${e}"`)&&(t=lt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=lt(i)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}}),t??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),ut(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:ut(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:ut(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:ut(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:ut(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:ut(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(L),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await e.readBuffer(i),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:rt(i),len:rt(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new ce(r.len))).replaceAll(/\00.*$/g,``);await e.ignore(r.len),--t}}let i=await n();switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190]))return{ext:`class`,mime:`application/java-vm`};if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new ce(4,`latin1`).get(this.buffer,2);if(e.match(`^d*`)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new ce(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
31
|
-
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(oe),type:await e.readToken(new ce(4,`latin1`))}}do{let n=await t();if(n.length<0)return;switch(n.type){case`IDAT`:return{ext:`png`,mime:`image/png`};case`acTL`:return{ext:`apng`,mime:`image/apng`};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:`png`,mime:`image/png`}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new ce(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(se))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(ut(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(r-=await e.readBuffer(t),ut(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(ut(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}await e.ignore(r)}return{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new ce(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&at(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:`xml`,mime:`application/xml`}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:void 0;if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}},this.detectImprecise=async e=>{if(this.buffer=new Uint8Array(st),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}},this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let r=await n.detect(e);if(r)return r;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(j(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await A(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=st}=t,r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await a.read(new Uint8Array(n));if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof b))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}check(e,t){return ut(this.buffer,e,t)}checkString(e,t){return this.check(it(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?ie:R);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?ie:R);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?ie:R).get(this.buffer,2),n=(e?ae:z).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(n>=8){let t=(e?ie:R).get(this.buffer,8),n=(e?ie:R).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:`tif`,mime:`image/tiff`}}if(t===43)return{ext:`tif`,mime:`image/tiff`}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},ft=a.__commonJS({"../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js":((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.SerializeAddon=r():n.SerializeAddon=r()})(e,(()=>(()=>{var e={930:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ColorContrastCache=void 0;let r=n(485);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},997:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;let a=n(930),o=n(160),s=n(345),c=n(859),l=n(97),u=o.css.toColor(`#ffffff`),d=o.css.toColor(`#000000`),f=o.css.toColor(`#ffffff`),p=o.css.toColor(`#000000`),m={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[o.css.toColor(`#2e3436`),o.css.toColor(`#cc0000`),o.css.toColor(`#4e9a06`),o.css.toColor(`#c4a000`),o.css.toColor(`#3465a4`),o.css.toColor(`#75507b`),o.css.toColor(`#06989a`),o.css.toColor(`#d3d7cf`),o.css.toColor(`#555753`),o.css.toColor(`#ef2929`),o.css.toColor(`#8ae234`),o.css.toColor(`#fce94f`),o.css.toColor(`#729fcf`),o.css.toColor(`#ad7fa8`),o.css.toColor(`#34e2e2`),o.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:o.channels.toCss(r,i,a),rgba:o.channels.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:o.channels.toCss(n,n,n),rgba:o.channels.toRgba(n,n,n)})}return e})());let h=t.ThemeService=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this.register(new s.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:d,cursor:f,cursorAccent:p,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:o.color.blend(d,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:o.color.blend(d,m),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let n=this._colors;if(n.foreground=g(e.foreground,u),n.background=g(e.background,d),n.cursor=g(e.cursor,f),n.cursorAccent=g(e.cursorAccent,p),n.selectionBackgroundTransparent=g(e.selectionBackground,m),n.selectionBackgroundOpaque=o.color.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=g(e.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=o.color.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=e.selectionForeground?g(e.selectionForeground,o.NULL_COLOR):void 0,n.selectionForeground===o.NULL_COLOR&&(n.selectionForeground=void 0),o.color.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=o.color.opacity(n.selectionBackgroundTransparent,.3)),o.color.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=o.color.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.ansi=t.DEFAULT_ANSI_COLORS.slice(),n.ansi[0]=g(e.black,t.DEFAULT_ANSI_COLORS[0]),n.ansi[1]=g(e.red,t.DEFAULT_ANSI_COLORS[1]),n.ansi[2]=g(e.green,t.DEFAULT_ANSI_COLORS[2]),n.ansi[3]=g(e.yellow,t.DEFAULT_ANSI_COLORS[3]),n.ansi[4]=g(e.blue,t.DEFAULT_ANSI_COLORS[4]),n.ansi[5]=g(e.magenta,t.DEFAULT_ANSI_COLORS[5]),n.ansi[6]=g(e.cyan,t.DEFAULT_ANSI_COLORS[6]),n.ansi[7]=g(e.white,t.DEFAULT_ANSI_COLORS[7]),n.ansi[8]=g(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),n.ansi[9]=g(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),n.ansi[10]=g(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),n.ansi[11]=g(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),n.ansi[12]=g(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),n.ansi[13]=g(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),n.ansi[14]=g(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),n.ansi[15]=g(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let r=Math.min(n.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<r;i++)n.ansi[i+16]=g(e.extendedAnsi[i],t.DEFAULT_ANSI_COLORS[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e!==void 0)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function g(e,t){if(e!==void 0)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=h=r([i(0,l.IOptionsService)],h)},160:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:`#00000000`,rgba:0},function(e){e.toCss=function(e,t,n,r){return r===void 0?`#${d(e)}${d(t)}${d(n)}`:`#${d(e)}${d(t)}${d(n)}${d(r)}`},e.toRgba=function(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return(255&e.rgba)==255},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),s=Math.min(255,s+Math.ceil(.1*(255-s))),c=Math.min(255,c+Math.ceil(.1*(255-c))),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)<r){if(a<i){let a=t(e,n,r),o=f(i,l.relativeLuminance(a>>8));if(o<r){let t=s(e,n,r);return o>f(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(c<r){let a=t(e,n,r);return c>f(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={})),t.toPaddedHex=d,t.contrastRatio=f},345:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},859:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},485:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},726:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},97:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(726);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,`__esModule`,{value:!0}),e.HTMLSerializeHandler=e.SerializeAddon=void 0;let t=n(997);function i(e,t,n){return Math.max(t,Math.min(e,n))}class a{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);o?(this._nextCell(o,i,t,e),i=o):console.warn(`Can't get cell at row=${t}, col=${e}`)}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}}function o(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function s(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function c(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}class l extends a{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!s(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(r.isWrapped){n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),c=o.getWidth()>1,l=!1;(o.getChars()&&c?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&s(i,o)&&(l=!0),c&&(a.getChars()||a.getWidth()===0)&&s(i,o)&&s(a,o)&&(l=!0)),l||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`[${t.length-this._nullCellCount}C`,n+=`[${this._nullCellCount}X`,n+=`[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}else n=`\r
|
|
32
|
-
`,this._lastCursorRow=e+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,255&t):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(8&t?90+(7&t):30+(7&t)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,255&t):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(8&t?100+(7&t):40+(7&t)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!s(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX;(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((r=e-this._lastCursorRow)>0?n+=`[${r}B`:r<0&&(n+=`[${-r}A`),(e=>{e>0?n+=`[${e}C`:e<0&&(n+=`[${-e}D`)})(t-this._lastCursorCol))}var r;let i=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(i,this._cursorStyle);return a.length>0&&(n+=`[${a.join(`;`)}m`),n}}e.SerializeAddon=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,a=n===void 0?r:i(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-a,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new l(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new u(n,e,t);if(!t.onlySelection){let a=n.length,o=t.scrollback,s=o===void 0?a:i(o+e.rows,0,a);return r.serialize({start:{x:0,y:a-s},end:{x:e.cols,y:a-1}})}let a=this._terminal?.getSelectionPosition();return a===void 0?``:r.serialize({start:{x:a.start.x,y:a.start.y},end:{x:a.end.x,y:a.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),!1===n.wraparoundMode&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);return e?.excludeAltBuffer||this._terminal.buffer.active.type!==`alternate`||(t+=`[?1049h[H${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}};class u extends a{constructor(e,n,r){super(e),this._terminal=n,this._options=r,this._currentRow=``,this._htmlContent=``,n._core._themeService?this._ansiColors=n._core._themeService.colors.ansi:this._ansiColors=t.DEFAULT_ANSI_COLORS}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:((t-=e.length)>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;this._options.includeGlobalBackground&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();return(t?e.isFgRGB():e.isBgRGB())?`#`+[n>>16&255,n>>8&255,255&n].map((e=>this._padStart(e.toString(16),2,`0`))).join(``):(t?e.isFgPalette():e.isBgPalette())?this._ansiColors[n].css:void 0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),this._currentRow+=i?` `:e.getChars()}_serializeString(){return this._htmlContent}}e.HTMLSerializeHandler=u})(),r})()))})}),pt=a.__commonJS({"../../node_modules/@xterm/headless/lib-headless/xterm-headless.js":(e=>{(()=>{var t={349:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CircularList=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new r.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new r.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new r.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=a},439:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.clone=void 0,t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},969:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreTerminal=void 0;let r=n(844),i=n(585),a=n(348),o=n(866),s=n(744),c=n(302),l=n(83),u=n(460),d=n(753),f=n(480),p=n(994),m=n(282),h=n(435),g=n(981),_=n(660),v=!1;class y extends r.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new r.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new a.InstantiationService,this.optionsService=this.register(new c.OptionsService(e)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(s.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(f.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(p.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new h.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new g.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=i.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,s.MINIMUM_COLS),t=Math.max(t,s.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,n){this._bufferService.scrollLines(e,t,n)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,r.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},460:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},435:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;let a=n(584),o=n(116),s=n(15),c=n(844),l=n(482),u=n(437),d=n(460),f=n(643),p=n(511),m=n(734),h=n(585),g=n(480),_=n(242),v=n(351),y=n(941),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,f,m,h=new s.EscapeSequenceParser){for(let s in super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=f,this._unicodeService=m,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._workCell=new p.CellData,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new _.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new _.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new _.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new _.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new _.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new _.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new _.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new _.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new _.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new _.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new _.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new _.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset())),o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:s},(()=>this.selectCharset(`(`+s))),this._parser.registerEscHandler({intermediates:`)`,final:s},(()=>this.selectCharset(`)`+s))),this._parser.registerEscHandler({intermediates:`*`,final:s},(()=>this.selectCharset(`*`+s))),this._parser.registerEscHandler({intermediates:`+`,final:s},(()=>this.selectCharset(`+`+s))),this._parser.registerEscHandler({intermediates:`-`,final:s},(()=>this.selectCharset(`-`+s))),this._parser.registerEscHandler({intermediates:`.`,final:s},(()=>this.selectCharset(`.`+s))),this._parser.registerEscHandler({intermediates:`/`,final:s},(()=>this.selectCharset(`/`+s)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new v.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=h.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=h.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data`+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`),typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(e.length,x))),o||this._dirtyRowTracker.clearRange(),e.length>x)for(let t=a;t<e.length;t+=x){let a=t+x<e.length?t+x:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}this._activeBuffer.x===r&&this._activeBuffer.y===i||this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(c,this._bufferService.rows-1),Math.min(s,this._bufferService.rows-1))}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,p=this._curAttrData,m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let h=this._parser.precedingJoinState;for(let _=t;_<n;++_){if(r=e[_],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,h);i=g.UnicodeService.extractWidth(t);let n=g.UnicodeService.extractShouldJoin(t),v=n?g.UnicodeService.extractWidth(h):0;if(h=t,o&&this._onA11yChar.fire((0,l.stringFromCodePoint)(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-v>s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t<s;)e.setCellFromCodepoint(t++,0,1,p)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=m.getWidth(this._activeBuffer.x-1)?1:2;m.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-v;--e>=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(d&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,f.NULL_CELL_CODE,f.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=h,this._activeBuffer.x<s&&n-t>0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new v.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(u.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=g.UnicodeService.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:i}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=e=>e?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:c===132?1:0:0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=m.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle=`block`;break;case 3:case 4:this._optionsService.options.cursorStyle=`underline`;break;case 5:case 6:this._optionsService.options.cursorStyle=`bar`}let n=t%2==1;return this._optionsService.options.cursorBlink=n,!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n))if(r===`?`)t.push({type:0,index:n});else{let e=(0,y.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.split(`;`);return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,y.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);D(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(b[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new p.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=this._bufferService.buffer,r=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,h.IBufferService)],E)},844:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},114:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},226:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(114);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),n=Math.max(t,n),i=e.timeRemaining(),1.5*n>i)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},282:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.updateWindowsModeWrappedState=void 0;let r=n(643);t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)}},734:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},92:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(349),i=n(226),a=n(734),o=n(437),s=n(634),c=n(511),l=n(643),u=n(863),d=n(116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let n=e+this._optionsService.rawOptions.scrollback;return n>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o.BufferLine(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(n.length>0){let r=(0,s.reflowLargerCreateNewLayout)(this.lines,n);(0,s.reflowLargerApplyNewLayout)(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=[],i=0;for(let a=this.lines.length-1;a>=0;a--){let c=this.lines.get(a);if(!c||!c.isWrapped&&c.getTrimmedLength()<=e)continue;let l=[c];for(;c.isWrapped&&a>0;)c=this.lines.get(--a),l.unshift(c);let u=this.ybase+this.y;if(u>=a&&u<a+l.length)continue;let d=l[l.length-1].getTrimmedLength(),f=(0,s.reflowSmallerGetNewLineLengths)(l,this._cols,e),p=f.length-l.length,m=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+p):Math.max(0,this.lines.length-this.lines.maxLength+p),h=[];for(let e=0;e<p;e++){let e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);h.push(e)}h.length>0&&(r.push({start:a+l.length+i,newLines:h}),i+=h.length),l.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=l.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(l[g]===void 0)break;if(l[g].copyCellsFrom(l[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(l,e,this._cols)}}for(let t=0;t<l.length;t++)f[t]<e&&l[t].setCell(f[t],n);let b=p-m;for(;b-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+i)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,a=n-1,o=0,s=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+i);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+i-1);l>=0;l--)if(s&&s.start>a+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:a+1,amount:s.newLines.length}),c+=s.newLines.length,s=r[++o]}else this.lines.set(l,t[a--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+i-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){let t=new u.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},437:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(734),i=n(511),a=n(643),o=n(482);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[3*e+0],n=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:n?(0,o.stringFromCodePoint)(n):``,t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new i.CellData;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new i.CellData;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)!==0||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let n=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){for(let t in this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];for(let t in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let e=new c(0);for(let t in e._data=new Uint32Array(this._data),e.length=this.length,this._combined)e._combined[t]=this._combined[t];for(let t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[3*t+0],n=2097151&e,s=2097152&e?this._combined[t]:n?(0,o.stringFromCodePoint)(n):a.WHITESPACE_CELL_CHAR;if(i+=s,r)for(let e=0;e<s.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}}t.BufferLine=c},634:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,`__esModule`,{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(i>=s&&i<c){s+=u.length-1;continue}let d=0,f=n(u,d,t),p=1,m=0;for(;p<u.length;){let e=n(u,p,t),i=e-m,o=r-f,s=Math.min(i,o);u[d].copyCellsFrom(u[p],m,f,s,!1),f+=s,f===r&&(d++,f=0),m+=s,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(r-1)===2&&(u[d].copyCellsFrom(u[d-1],r-1,f++,1,!1),u[d-1].setCell(r-1,a))}u[d].replaceCells(f,r,a);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}},t.reflowLargerApplyNewLayout=function(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,r){let i=[],a=e.map(((r,i)=>n(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;c<a;){if(a-c<r){i.push(a-c);break}o+=r;let l=n(e,s,t);o>l&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},295:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferSet=void 0;let r=n(460),i=n(844),a=n(92);class o extends i.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new r.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new a.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new a.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CellData=void 0;let r=n(482),i=n(643),a=n(734);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},863:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Marker=void 0;let r=n(460),i=n(844);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},116:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},584:(e,t)=>{var n,r,i;Object.defineProperty(t,`__esModule`,{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
29
|
+
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=ze()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
30
|
+
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),We=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=Be():t.exports=Ue()})});let Ge={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ke={get(e){return R.get(e,6),{signature:z.get(e,0),compressedSize:z.get(e,8),uncompressedSize:z.get(e,12)}},len:16},qe={get(e){let t=R.get(e,6);return{signature:z.get(e,0),minVersion:R.get(e,4),dataDescriptor:!!(t&8),compressedMethod:R.get(e,8),compressedSize:z.get(e,18),uncompressedSize:z.get(e,22),filenameLength:R.get(e,26),extraFieldLength:R.get(e,28),filename:null}},len:30},Je={get(e){return{signature:z.get(e,0),nrOfThisDisk:R.get(e,4),nrOfThisDiskWithTheStart:R.get(e,6),nrOfEntriesOnThisDisk:R.get(e,8),nrOfEntriesOfSize:R.get(e,10),sizeOfCd:z.get(e,12),offsetOfStartOfCd:z.get(e,16),zipFileCommentLength:R.get(e,20)}},len:22},Ye={get(e){let t=R.get(e,8);return{signature:z.get(e,0),minVersion:R.get(e,6),dataDescriptor:!!(t&8),compressedMethod:R.get(e,10),compressedSize:z.get(e,20),uncompressedSize:z.get(e,24),filenameLength:R.get(e,28),extraFieldLength:R.get(e,30),fileCommentLength:R.get(e,32),relativeOffsetOfLocalHeader:z.get(e,42),filename:null}},len:46};var Xe=a.__toESM(We(),1);function Ze(e){let t=new Uint8Array(z.len);return z.put(t,0,e),t}let Qe=(0,Xe.default)(`tokenizer:inflate`),$e=256*1024,et=Ze(Ge.DataDescriptor),tt=Ze(Ge.EndOfCentralDirectory);var nt=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array($e)}async isZip(){return await this.peekSignature()===Ge.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(z)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===tt[0]&&n[r+1]===tt[1]&&n[r+2]===tt[2]&&n[r+3]===tt[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Qe(`Cannot reading central-directory without random-read support`);return}Qe(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Qe(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Je,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Ye);if(t.signature!==Ge.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new ce(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Qe(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=$e;Qe(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===$e;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=rt(this.syncBuffer.subarray(0,n),et);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}Qe(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,it(e),r.handler)}else r.handler?(Qe(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Qe(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Qe(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ke)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ke.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);Qe(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=Ie(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(z);if(e===Ge.LocalFileHeader){let e=await this.tokenizer.readToken(qe);return e.filename=await this.tokenizer.readToken(new ce(e.filenameLength,`utf-8`)),e}if(e===Ge.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function rt(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function it(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function at(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function ot(e){return[...e].map(e=>e.charCodeAt(0))}function st(e,t=0){let n=Number.parseInt(new ce(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}let ct={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},lt=4100;async function ut(e,t){return new pt(t).fromBuffer(e)}function dt(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function ft(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}var pt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(lt),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return{ext:`gz`,mime:`application/gzip`};if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await e.ignore(6);let t=await e.readToken(ct);return e.position+t>e.fileInfo.size?{ext:`mp3`,mime:`audio/mpeg`}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t;return await new nt(e).unzip(e=>{switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e).trim();t=dt(n)},stop:!0};case`[Content_Types].xml`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e),r=n.indexOf(`.main+xml"`);if(r===-1){let e=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;n.includes(`ContentType="${e}"`)&&(t=dt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=dt(i)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}}),t??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),ft(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:ft(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:ft(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:ft(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:ft(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:ft(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(re),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await e.readBuffer(i),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:at(i),len:at(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new ce(r.len))).replaceAll(/\00.*$/g,``);await e.ignore(r.len),--t}}let i=await n();switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190]))return{ext:`class`,mime:`application/java-vm`};if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new ce(4,`latin1`).get(this.buffer,2);if(e.match(`^d*`)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new ce(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
31
|
+
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(oe),type:await e.readToken(new ce(4,`latin1`))}}do{let n=await t();if(n.length<0)return;switch(n.type){case`IDAT`:return{ext:`png`,mime:`image/png`};case`acTL`:return{ext:`apng`,mime:`image/apng`};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:`png`,mime:`image/png`}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new ce(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(se))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(ft(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(r-=await e.readBuffer(t),ft(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(ft(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}await e.ignore(r)}return{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new ce(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&st(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:`xml`,mime:`application/xml`}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:void 0;if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}},this.detectImprecise=async e=>{if(this.buffer=new Uint8Array(lt),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}},this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let r=await n.detect(e);if(r)return r;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(j(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await A(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=lt}=t,r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await a.read(new Uint8Array(n));if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof b))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}check(e,t){return ft(this.buffer,e,t)}checkString(e,t){return this.check(ot(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?ie:R);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?ie:R);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?ie:R).get(this.buffer,2),n=(e?ae:z).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(n>=8){let t=(e?ie:R).get(this.buffer,8),n=(e?ie:R).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:`tif`,mime:`image/tiff`}}if(t===43)return{ext:`tif`,mime:`image/tiff`}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},mt=a.__commonJS({"../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js":((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.SerializeAddon=r():n.SerializeAddon=r()})(e,(()=>(()=>{var e={930:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ColorContrastCache=void 0;let r=n(485);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},997:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;let a=n(930),o=n(160),s=n(345),c=n(859),l=n(97),u=o.css.toColor(`#ffffff`),d=o.css.toColor(`#000000`),f=o.css.toColor(`#ffffff`),p=o.css.toColor(`#000000`),m={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[o.css.toColor(`#2e3436`),o.css.toColor(`#cc0000`),o.css.toColor(`#4e9a06`),o.css.toColor(`#c4a000`),o.css.toColor(`#3465a4`),o.css.toColor(`#75507b`),o.css.toColor(`#06989a`),o.css.toColor(`#d3d7cf`),o.css.toColor(`#555753`),o.css.toColor(`#ef2929`),o.css.toColor(`#8ae234`),o.css.toColor(`#fce94f`),o.css.toColor(`#729fcf`),o.css.toColor(`#ad7fa8`),o.css.toColor(`#34e2e2`),o.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:o.channels.toCss(r,i,a),rgba:o.channels.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:o.channels.toCss(n,n,n),rgba:o.channels.toRgba(n,n,n)})}return e})());let h=t.ThemeService=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this.register(new s.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:d,cursor:f,cursorAccent:p,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:o.color.blend(d,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:o.color.blend(d,m),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let n=this._colors;if(n.foreground=g(e.foreground,u),n.background=g(e.background,d),n.cursor=g(e.cursor,f),n.cursorAccent=g(e.cursorAccent,p),n.selectionBackgroundTransparent=g(e.selectionBackground,m),n.selectionBackgroundOpaque=o.color.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=g(e.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=o.color.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=e.selectionForeground?g(e.selectionForeground,o.NULL_COLOR):void 0,n.selectionForeground===o.NULL_COLOR&&(n.selectionForeground=void 0),o.color.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=o.color.opacity(n.selectionBackgroundTransparent,.3)),o.color.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=o.color.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.ansi=t.DEFAULT_ANSI_COLORS.slice(),n.ansi[0]=g(e.black,t.DEFAULT_ANSI_COLORS[0]),n.ansi[1]=g(e.red,t.DEFAULT_ANSI_COLORS[1]),n.ansi[2]=g(e.green,t.DEFAULT_ANSI_COLORS[2]),n.ansi[3]=g(e.yellow,t.DEFAULT_ANSI_COLORS[3]),n.ansi[4]=g(e.blue,t.DEFAULT_ANSI_COLORS[4]),n.ansi[5]=g(e.magenta,t.DEFAULT_ANSI_COLORS[5]),n.ansi[6]=g(e.cyan,t.DEFAULT_ANSI_COLORS[6]),n.ansi[7]=g(e.white,t.DEFAULT_ANSI_COLORS[7]),n.ansi[8]=g(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),n.ansi[9]=g(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),n.ansi[10]=g(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),n.ansi[11]=g(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),n.ansi[12]=g(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),n.ansi[13]=g(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),n.ansi[14]=g(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),n.ansi[15]=g(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let r=Math.min(n.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<r;i++)n.ansi[i+16]=g(e.extendedAnsi[i],t.DEFAULT_ANSI_COLORS[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e!==void 0)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function g(e,t){if(e!==void 0)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=h=r([i(0,l.IOptionsService)],h)},160:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:`#00000000`,rgba:0},function(e){e.toCss=function(e,t,n,r){return r===void 0?`#${d(e)}${d(t)}${d(n)}`:`#${d(e)}${d(t)}${d(n)}${d(r)}`},e.toRgba=function(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return(255&e.rgba)==255},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),s=Math.min(255,s+Math.ceil(.1*(255-s))),c=Math.min(255,c+Math.ceil(.1*(255-c))),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)<r){if(a<i){let a=t(e,n,r),o=f(i,l.relativeLuminance(a>>8));if(o<r){let t=s(e,n,r);return o>f(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(c<r){let a=t(e,n,r);return c>f(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={})),t.toPaddedHex=d,t.contrastRatio=f},345:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},859:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},485:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},726:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},97:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(726);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,`__esModule`,{value:!0}),e.HTMLSerializeHandler=e.SerializeAddon=void 0;let t=n(997);function i(e,t,n){return Math.max(t,Math.min(e,n))}class a{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);o?(this._nextCell(o,i,t,e),i=o):console.warn(`Can't get cell at row=${t}, col=${e}`)}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}}function o(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function s(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function c(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}class l extends a{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!s(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(r.isWrapped){n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),c=o.getWidth()>1,l=!1;(o.getChars()&&c?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&s(i,o)&&(l=!0),c&&(a.getChars()||a.getWidth()===0)&&s(i,o)&&s(a,o)&&(l=!0)),l||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`[${t.length-this._nullCellCount}C`,n+=`[${this._nullCellCount}X`,n+=`[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}else n=`\r
|
|
32
|
+
`,this._lastCursorRow=e+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,255&t):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(8&t?90+(7&t):30+(7&t)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,255&t):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(8&t?100+(7&t):40+(7&t)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!s(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX;(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((r=e-this._lastCursorRow)>0?n+=`[${r}B`:r<0&&(n+=`[${-r}A`),(e=>{e>0?n+=`[${e}C`:e<0&&(n+=`[${-e}D`)})(t-this._lastCursorCol))}var r;let i=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(i,this._cursorStyle);return a.length>0&&(n+=`[${a.join(`;`)}m`),n}}e.SerializeAddon=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,a=n===void 0?r:i(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-a,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new l(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new u(n,e,t);if(!t.onlySelection){let a=n.length,o=t.scrollback,s=o===void 0?a:i(o+e.rows,0,a);return r.serialize({start:{x:0,y:a-s},end:{x:e.cols,y:a-1}})}let a=this._terminal?.getSelectionPosition();return a===void 0?``:r.serialize({start:{x:a.start.x,y:a.start.y},end:{x:a.end.x,y:a.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),!1===n.wraparoundMode&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);return e?.excludeAltBuffer||this._terminal.buffer.active.type!==`alternate`||(t+=`[?1049h[H${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}};class u extends a{constructor(e,n,r){super(e),this._terminal=n,this._options=r,this._currentRow=``,this._htmlContent=``,n._core._themeService?this._ansiColors=n._core._themeService.colors.ansi:this._ansiColors=t.DEFAULT_ANSI_COLORS}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:((t-=e.length)>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;this._options.includeGlobalBackground&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();return(t?e.isFgRGB():e.isBgRGB())?`#`+[n>>16&255,n>>8&255,255&n].map((e=>this._padStart(e.toString(16),2,`0`))).join(``):(t?e.isFgPalette():e.isBgPalette())?this._ansiColors[n].css:void 0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),this._currentRow+=i?` `:e.getChars()}_serializeString(){return this._htmlContent}}e.HTMLSerializeHandler=u})(),r})()))})}),ht=a.__commonJS({"../../node_modules/@xterm/headless/lib-headless/xterm-headless.js":(e=>{(()=>{var t={349:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CircularList=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new r.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new r.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new r.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=a},439:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.clone=void 0,t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},969:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreTerminal=void 0;let r=n(844),i=n(585),a=n(348),o=n(866),s=n(744),c=n(302),l=n(83),u=n(460),d=n(753),f=n(480),p=n(994),m=n(282),h=n(435),g=n(981),_=n(660),v=!1;class y extends r.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new r.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new a.InstantiationService,this.optionsService=this.register(new c.OptionsService(e)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(s.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(f.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(p.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new h.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new g.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=i.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,s.MINIMUM_COLS),t=Math.max(t,s.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,n){this._bufferService.scrollLines(e,t,n)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,r.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},460:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},435:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;let a=n(584),o=n(116),s=n(15),c=n(844),l=n(482),u=n(437),d=n(460),f=n(643),p=n(511),m=n(734),h=n(585),g=n(480),_=n(242),v=n(351),y=n(941),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,f,m,h=new s.EscapeSequenceParser){for(let s in super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=f,this._unicodeService=m,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._workCell=new p.CellData,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new _.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new _.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new _.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new _.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new _.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new _.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new _.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new _.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new _.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new _.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new _.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new _.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset())),o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:s},(()=>this.selectCharset(`(`+s))),this._parser.registerEscHandler({intermediates:`)`,final:s},(()=>this.selectCharset(`)`+s))),this._parser.registerEscHandler({intermediates:`*`,final:s},(()=>this.selectCharset(`*`+s))),this._parser.registerEscHandler({intermediates:`+`,final:s},(()=>this.selectCharset(`+`+s))),this._parser.registerEscHandler({intermediates:`-`,final:s},(()=>this.selectCharset(`-`+s))),this._parser.registerEscHandler({intermediates:`.`,final:s},(()=>this.selectCharset(`.`+s))),this._parser.registerEscHandler({intermediates:`/`,final:s},(()=>this.selectCharset(`/`+s)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new v.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=h.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=h.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data`+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`),typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(e.length,x))),o||this._dirtyRowTracker.clearRange(),e.length>x)for(let t=a;t<e.length;t+=x){let a=t+x<e.length?t+x:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}this._activeBuffer.x===r&&this._activeBuffer.y===i||this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(c,this._bufferService.rows-1),Math.min(s,this._bufferService.rows-1))}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,p=this._curAttrData,m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let h=this._parser.precedingJoinState;for(let _=t;_<n;++_){if(r=e[_],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,h);i=g.UnicodeService.extractWidth(t);let n=g.UnicodeService.extractShouldJoin(t),v=n?g.UnicodeService.extractWidth(h):0;if(h=t,o&&this._onA11yChar.fire((0,l.stringFromCodePoint)(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-v>s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t<s;)e.setCellFromCodepoint(t++,0,1,p)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=m.getWidth(this._activeBuffer.x-1)?1:2;m.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-v;--e>=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(d&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,f.NULL_CELL_CODE,f.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=h,this._activeBuffer.x<s&&n-t>0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new v.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(u.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=g.UnicodeService.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:i}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=e=>e?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:c===132?1:0:0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=m.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle=`block`;break;case 3:case 4:this._optionsService.options.cursorStyle=`underline`;break;case 5:case 6:this._optionsService.options.cursorStyle=`bar`}let n=t%2==1;return this._optionsService.options.cursorBlink=n,!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n))if(r===`?`)t.push({type:0,index:n});else{let e=(0,y.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.split(`;`);return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,y.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);D(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(b[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new p.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=this._bufferService.buffer,r=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,h.IBufferService)],E)},844:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},114:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},226:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(114);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),n=Math.max(t,n),i=e.timeRemaining(),1.5*n>i)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},282:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.updateWindowsModeWrappedState=void 0;let r=n(643);t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)}},734:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},92:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(349),i=n(226),a=n(734),o=n(437),s=n(634),c=n(511),l=n(643),u=n(863),d=n(116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let n=e+this._optionsService.rawOptions.scrollback;return n>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o.BufferLine(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(n.length>0){let r=(0,s.reflowLargerCreateNewLayout)(this.lines,n);(0,s.reflowLargerApplyNewLayout)(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=[],i=0;for(let a=this.lines.length-1;a>=0;a--){let c=this.lines.get(a);if(!c||!c.isWrapped&&c.getTrimmedLength()<=e)continue;let l=[c];for(;c.isWrapped&&a>0;)c=this.lines.get(--a),l.unshift(c);let u=this.ybase+this.y;if(u>=a&&u<a+l.length)continue;let d=l[l.length-1].getTrimmedLength(),f=(0,s.reflowSmallerGetNewLineLengths)(l,this._cols,e),p=f.length-l.length,m=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+p):Math.max(0,this.lines.length-this.lines.maxLength+p),h=[];for(let e=0;e<p;e++){let e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);h.push(e)}h.length>0&&(r.push({start:a+l.length+i,newLines:h}),i+=h.length),l.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=l.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(l[g]===void 0)break;if(l[g].copyCellsFrom(l[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(l,e,this._cols)}}for(let t=0;t<l.length;t++)f[t]<e&&l[t].setCell(f[t],n);let b=p-m;for(;b-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+i)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,a=n-1,o=0,s=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+i);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+i-1);l>=0;l--)if(s&&s.start>a+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:a+1,amount:s.newLines.length}),c+=s.newLines.length,s=r[++o]}else this.lines.set(l,t[a--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+i-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){let t=new u.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},437:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(734),i=n(511),a=n(643),o=n(482);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[3*e+0],n=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:n?(0,o.stringFromCodePoint)(n):``,t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new i.CellData;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new i.CellData;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)!==0||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let n=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){for(let t in this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];for(let t in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let e=new c(0);for(let t in e._data=new Uint32Array(this._data),e.length=this.length,this._combined)e._combined[t]=this._combined[t];for(let t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[3*t+0],n=2097151&e,s=2097152&e?this._combined[t]:n?(0,o.stringFromCodePoint)(n):a.WHITESPACE_CELL_CHAR;if(i+=s,r)for(let e=0;e<s.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}}t.BufferLine=c},634:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,`__esModule`,{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(i>=s&&i<c){s+=u.length-1;continue}let d=0,f=n(u,d,t),p=1,m=0;for(;p<u.length;){let e=n(u,p,t),i=e-m,o=r-f,s=Math.min(i,o);u[d].copyCellsFrom(u[p],m,f,s,!1),f+=s,f===r&&(d++,f=0),m+=s,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(r-1)===2&&(u[d].copyCellsFrom(u[d-1],r-1,f++,1,!1),u[d-1].setCell(r-1,a))}u[d].replaceCells(f,r,a);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}},t.reflowLargerApplyNewLayout=function(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,r){let i=[],a=e.map(((r,i)=>n(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;c<a;){if(a-c<r){i.push(a-c);break}o+=r;let l=n(e,s,t);o>l&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},295:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferSet=void 0;let r=n(460),i=n(844),a=n(92);class o extends i.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new r.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new a.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new a.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CellData=void 0;let r=n(482),i=n(643),a=n(734);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},863:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Marker=void 0;let r=n(460),i=n(844);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},116:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},584:(e,t)=>{var n,r,i;Object.defineProperty(t,`__esModule`,{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
33
33
|
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``}(n||(t.C0=n={})),function(e){e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``}(r||(t.C1=r={})),function(e){e.ST=`${n.ESC}\\`}(i||(t.C1_ESCAPED=i={}))},482:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=1024*(this._interim-55296)+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=1024*(i-55296)+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r,i,a,o,s=0,c=0,l=0;if(this.interim[0]){let r=!1,i=this.interim[0];i&=(224&i)==192?31:(240&i)==224?15:7;let a,o=0;for(;(a=63&this.interim[++o])&&o<4;)i<<=6,i|=a;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(a=e[l++],(192&a)!=128){l--,r=!0;break}this.interim[o++]=a,i<<=6,i|=63&a}r||(c===2?i<128?l--:t[s++]=i:c===3?i<2048||i>=55296&&i<=57343||i===65279||(t[s++]=i):i<65536||i>1114111||(t[s++]=i)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;!(!(d<u)||128&(r=e[d])||128&(i=e[d+1])||128&(a=e[d+2])||128&(o=e[d+3]));)t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=o,d+=4;if(r=e[d++],r<128)t[s++]=r;else if((224&r)==192){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(c=(31&r)<<6|63&i,c<128){d--;continue}t[s++]=c}else if((240&r)==224){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(c=(15&r)<<12|(63&i)<<6|63&a,c<2048||c>=55296&&c<=57343||c===65279)continue;t[s++]=c}else if((248&r)==240){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,this.interim[2]=a,s;if(o=e[d++],(192&o)!=128){d--;continue}if(c=(7&r)<<18|(63&i)<<12|(63&a)<<6|63&o,c<65536||c>1114111)continue;t[s++]=c}}return s}}},225:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeV6=void 0;let r=n(480),i=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],a=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],o;t.UnicodeV6=class{constructor(){if(this.version=`6`,!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;e<i.length;++e)o.fill(0,i[e][0],i[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?o[e]:function(e,t){let n,r=0,i=t.length-1;if(e<t[0][0]||e>t[i][1])return!1;for(;i>=r;)if(n=r+i>>1,e>t[n][1])r=n+1;else{if(!(e<t[n][0]))return!0;i=n-1}return!1}(e,a)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),i=n===0&&t!==0;if(i){let e=r.UnicodeService.extractWidth(t);e===0?i=!1:e>n&&(n=e)}return r.UnicodeService.createPropertyValue(0,n,i)}}},981:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WriteBuffer=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new r.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let n;for(this._isSyncWriting=!0;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e=>Date.now()-n>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-n>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=a},941:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.toRgbString=t.parseColor=void 0;let n=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,r=/^[\da-f]+$/;function i(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=n.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),r.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}},t.toRgbString=function(e,t=16){let[n,r,a]=e;return`rgb:${i(n,t)}/${i(r,t)}/${i(a,t)}`}},770:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},351:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DcsHandler=t.DcsParser=void 0;let r=n(482),i=n(742),a=n(770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,`HOOK`,t)}put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._ident,`PUT`,(0,r.utf32ToString)(e,t,n))}unhook(e,t=!0){if(this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].unhook(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._ident,`UNHOOK`,e);this._active=o,this._ident=0}};let s=new i.Params;s.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data=``,this._params=s,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():s,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,n),this._data.length>a.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=s,this._data=``,this._hitLimit=!1,e)));return this._params=s,this._data=``,this._hitLimit=!1,t}}},15:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;let r=n(844),i=n(742),a=n(242),o=n(351);class s{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}}t.TransitionTable=s,t.VT500_TRANSITION_TABLE=function(){let e=new s(4095),t=Array.apply(null,Array(256)).map(((e,t)=>t)),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();class c extends r.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new i.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,r.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new a.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},(()=>!0))}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r,i=0,a=0,o=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,a=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](this._params),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 4:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 6:if(i=e[this._parseStack.chunkPos],r=this._dcsParser.unhook(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=e[this._parseStack.chunkPos],r=this._oscParser.end(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let n=o;n<t;++n){switch(i=e[n],a=this._transitions.table[this.currentState<<8|(i<160?i:160)],a>>4){case 2:for(let r=n+1;;++r){if(r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let o=this._csiHandlers[this._collect<<8|i],s=o?o.length-1:-1;for(;s>=0&&(r=o[s](this._params),!0!==r);s--)if(r instanceof Promise)return this._preserveStack(3,o,s,a,n),r;s<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++n<t&&(i=e[n])>47&&i<60);n--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let c=this._escHandlers[this._collect<<8|i],l=c?c.length-1:-1;for(;l>=0&&(r=c[l](),!0!==r);l--)if(r instanceof Promise)return this._preserveStack(4,c,l,a,n),r;l<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let r=n+1;;++r)if(r>=t||(i=e[r])===24||i===26||i===27||i>127&&i<160){this._dcsParser.put(e,n,r),n=r-1;break}break;case 14:if(r=this._dcsParser.unhook(i!==24&&i!==26),r)return this._preserveStack(6,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let r=n+1;;r++)if(r>=t||(i=e[r])<32||i>127&&i<160){this._oscParser.put(e,n,r),n=r-1;break}break;case 6:if(r=this._oscParser.end(i!==24&&i!==26),r)return this._preserveStack(5,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&a}}}t.EscapeSequenceParser=c},242:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OscHandler=t.OscParser=void 0;let r=n(770),i=n(482),a=[];t.OscParser=class{constructor(){this._state=0,this._active=a,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=a}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=a,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||a,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,`START`)}_put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._id,`PUT`,(0,i.utf32ToString)(e,t,n))}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].end(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._id,`END`,e);this._active=a,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,i.utf32ToString)(e,t,n),this._data.length>r.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data=``,this._hitLimit=!1,e)));return this._data=``,this._hitLimit=!1,t}}},742:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Params=void 0;let n=2147483647;class r{static fromArray(e){let t=new r;if(!e.length)return t;for(let n=Array.isArray(e[0])?1:0;n<e.length;++n){let r=e[n];if(Array.isArray(r))for(let e=0;e<r.length;++e)t.addSubParam(r[e]);else t.addParam(r)}return t}constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let e=new r(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>n?n:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>n?n:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=255&this._subParamsIdx[e];return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[t-1];r[t-1]=~i?Math.min(10*i+e,n):e}}t.Params=r},741:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}}},771:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferApiView=void 0;let r=n(785),i=n(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new r.BufferLineApiView(t)}getNullCell(){return new i.CellData}}},785:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLineApiView=void 0;let r=n(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new r.CellData)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}}},285:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferNamespaceApi=void 0;let r=n(771),i=n(460),a=n(844);class o extends a.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new i.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new r.BufferApiView(this._core.buffers.normal,`normal`),this._alternate=new r.BufferApiView(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},975:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,n)=>t(e,n.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},90:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;let a=n(460),o=n(844),s=n(295),c=n(585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let l=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new a.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new a.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new s.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r=this._cachedBlankLine;r&&r.length===this.cols&&r.getFg(0)===e.fg&&r.getBg(0)===e.bg||(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t,n){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let i=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),i!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))}};t.BufferService=l=r([i(0,c.IOptionsService)],l)},994:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},753:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreMouseService=void 0;let a=n(585),o=n(460),s=n(844),c={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button!==4&&e.action===1&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function l(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=3&e.button,4&e.button&&(n|=64),8&e.button&&(n|=128),e.action===32?n|=32:e.action!==0||t||(n|=3)),n}let u=String.fromCharCode,d={DEFAULT:e=>{let t=[l(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`[M${u(t[0])}${u(t[1])}${u(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.x};${e.y}${t}`}},f=t.CoreMouseService=class extends s.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(c))this.addProtocol(e,c[e]);for(let e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=f=r([i(0,a.IBufferService),i(1,a.ICoreService)],f)},83:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreService=void 0;let a=n(439),o=n(460),s=n(844),c=n(585),l=Object.freeze({insertMode:!1}),u=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),d=t.CoreService=class extends s.Disposable{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}reset(){this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=r([i(0,c.IBufferService),i(1,c.ILogService),i(2,c.IOptionsService)],d)},348:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;let r=n(585),i=n(343);class a{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=a,t.InstantiationService=class{constructor(){this._services=new a,this._services.set(r.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=(0,i.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);r.push(n)}let a=n.length>0?n[0].index:t.length;if(t.length!==a)throw Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}}},866:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;let a=n(844),o=n(585),s={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF},c,l=t.LogService=class extends a.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange(`logLevel`,(()=>this._updateLogLevel()))),c=this}_updateLogLevel(){this._logLevel=s[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:`xterm.js: `)+t,...n)}trace(e,...t){this._logLevel<=o.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=o.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=o.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=o.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=o.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};t.LogService=l=r([i(0,o.IOptionsService)],l),t.setTraceLogger=function(e){c=e},t.traceCall=function(e,t,n){if(typeof n.value!=`function`)throw Error(`not supported`);let r=n.value;n.value=function(...e){if(c.logLevel!==o.LogLevelEnum.TRACE)return r.apply(this,e);c.trace(`GlyphRenderer#${r.name}(${e.map((e=>JSON.stringify(e))).join(`, `)})`);let t=r.apply(this,e);return c.trace(`GlyphRenderer#${r.name} return`,t),t}}},302:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;let r=n(460),i=n(844);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`courier-new, courier, monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:n(114).isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRulerWidth:0};let a=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`];class o extends i.Disposable{constructor(e){super(),this._onOptionChange=this.register(new r.EventEmitter),this.onOptionChange=this._onOptionChange.event;let n={...t.DEFAULT_OPTIONS};for(let t in e)if(t in n)try{let r=e[t];n[t]=this._sanitizeAndValidateOption(t,r)}catch(e){console.error(e)}this.rawOptions=n,this.options={...n},this._setupOptions(),this.register((0,i.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((n=>{n===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((n=>{e.indexOf(n)!==-1&&t()}))}_setupOptions(){let e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},n=(e,n)=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);n=this._sanitizeAndValidateOption(e,n),this.rawOptions[e]!==n&&(this.rawOptions[e]=n,this._onOptionChange.fire(e))};for(let t in this.rawOptions){let r={get:e.bind(this,t),set:n.bind(this,t)};Object.defineProperty(this.options,t,r)}}_sanitizeAndValidateOption(e,n){switch(e){case`cursorStyle`:if(n||=t.DEFAULT_OPTIONS[e],!function(e){return e===`block`||e===`underline`||e===`bar`}(n))throw Error(`"${n}" is not a valid value for ${e}`);break;case`wordSeparator`:n||=t.DEFAULT_OPTIONS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof n==`number`&&1<=n&&n<=1e3)break;n=a.includes(n)?n:t.DEFAULT_OPTIONS[e];break;case`cursorWidth`:n=Math.floor(n);case`lineHeight`:case`tabStopWidth`:if(n<1)throw Error(`${e} cannot be less than 1, value: ${n}`);break;case`minimumContrastRatio`:n=Math.max(1,Math.min(21,Math.round(10*n)/10));break;case`scrollback`:if((n=Math.min(n,4294967295))<0)throw Error(`${e} cannot be less than 0, value: ${n}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(n<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${n}`);break;case`rows`:case`cols`:if(!n&&n!==0)throw Error(`${e} must be numeric, value: ${n}`);break;case`windowsPty`:n??={}}return n}}t.OptionsService=o},660:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.OscLinkService=void 0;let a=n(585),o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(r,n))),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose((()=>this._removeMarkerFromLink(o,a))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every((e=>e.line!==t))){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(n,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=r([i(0,a.IBufferService)],o)},343:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},585:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(343);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)},480:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeService=void 0;let r=n(460),i=n(225);class a{static extractShouldJoin(e){return(1&e)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(16777215&e)<<3|(3&t)<<1|(n?1:0)}constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new r.EventEmitter,this.onChange=this._onChange.event;let e=new i.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,n=0,r=e.length;for(let i=0;i<r;++i){let o=e.charCodeAt(i);if(55296<=o&&o<=56319){if(++i>=r)return t+this.wcwidth(o);let n=e.charCodeAt(i);56320<=n&&n<=57343?o=1024*(o-55296)+n-56320+65536:t+=this.wcwidth(n)}let s=this.charProperties(o,n),c=a.extractWidth(s);a.extractShouldJoin(s)&&(c-=a.extractWidth(n)),t+=c,n=s}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=a},781:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Terminal=void 0;let r=n(437),i=n(969),a=n(460);class o extends i.CoreTerminal{constructor(e={}){super(e),this._onBell=this.register(new a.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new a.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new a.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new a.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new a.EventEmitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this.register(this._inputHandler.onRequestBell((()=>this.bell()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register((0,a.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,a.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(e){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}bell(){this._onBell.fire()}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){e===this.cols&&t===this.rows||super.resize(e,t)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(r.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}t.Terminal=o}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e].call(a.exports,a,a.exports,r),a.exports}var i={};(()=>{var e=i;Object.defineProperty(e,`__esModule`,{value:!0}),e.Terminal=void 0;let t=r(285),n=r(975),a=r(90),o=r(781),s=r(741),c=r(844),l=[`cols`,`rows`];class u extends c.Disposable{constructor(e){super(),this._core=this.register(new o.Terminal(e)),this._addonManager=this.register(new s.AddonManager),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){Object.defineProperty(this._publicOptions,e,{get:()=>this._core.options[e],set:t=>{this._checkReadonlyOptions(e),this._core.options[e]=t}});let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(l.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get parser(){return this._checkProposedApi(),this._parser||=new n.ParserApi(this._core),this._parser}get unicode(){return this._checkProposedApi(),new a.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||=this.register(new t.BufferNamespaceApi(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}registerMarker(e=0){return this._checkProposedApi(),this._verifyIntegers(e),this._core.addMarker(e)}addMarker(e){return this.registerMarker(e)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
34
|
-
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),mt=a.__toESM(ft(),1),ht=a.__toESM(pt(),1),gt=(i=class e{constructor(e){this.processes=new Map,this.spawnListeners=[],this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}execute(t,n,r){let i=_t(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new ht.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new mt.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}},i.COLUMNS=80,i.ROWS=24,i.SCROLLBACK=128e3,i);let _t=(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new f,i=new f,a=(0,l.spawn)(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),a.on(`error`,e=>{throw e}),{pid:a.pid??-1,process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var vt=a.__commonJS({"../../node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),yt=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=vt();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),bt=a.__commonJS({"../../node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t,n){return b(e).writeDoubleLE(t,n)}function w(e,t,n){return b(e).writeFloatLE(t,n)}function T(e,t,n){return b(e).writeUInt32LE(t,n)}function E(e,t,n){return b(e).writeInt32LE(t,n)}function D(e,t){return b(e).readDoubleLE(t)}function O(e,t){return b(e).readFloatLE(t)}function k(e,t){return b(e).readUInt32LE(t)}function A(e,t){return b(e).readInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function ee(e,t,n){return b(e).writeFloatBE(t,n)}function M(e,t,n){return b(e).writeUInt32BE(t,n)}function te(e,t,n){return b(e).writeInt32BE(t,n)}function ne(e,t){return b(e).readDoubleBE(t)}function re(e,t){return b(e).readFloatBE(t)}function N(e,t){return b(e).readUInt32BE(t)}function P(e,t){return b(e).readInt32BE(t)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,writeDoubleLE:C,writeFloatLE:w,writeUInt32LE:T,writeInt32LE:E,readDoubleLE:D,readFloatLE:O,readUInt32LE:k,readInt32LE:A,writeDoubleBE:j,writeFloatBE:ee,writeUInt32BE:M,writeInt32BE:te,readDoubleBE:ne,readFloatBE:re,readUInt32BE:N,readInt32BE:P}})}),xt=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=bt();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),St=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=bt();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),Ct=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=xt(),r=St();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),wt=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Z(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=yt(),o=Ct(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,ee=512<<18,M=1024<<18;c^(C|j);let te=c^T;c^(C|ee),c^D,c^E;let ne=c^A;c^w;let re=c^M,N=16|C,P=c^N,F=m|O,I=14|F;te&536870847;let L=A|h;L&P;let R=33587215;u|16399;let ie=m|143;u|143,u|16398,h|1,ee|8388623,E|D,E|C;let z=270794767;T|C,C|j,O|134217742;let ae=Symbol.asyncIterator||Symbol(`asyncIterator`);var oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Pe,this.map=r||n,this.afterWrite=ue.bind(this),this.afterUpdateNextTick=pe.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|ee)&te}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&z)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&z)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===ee){e._duplexState|=C,e._final(H.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&L)===0&&(e._duplexState|=N,e._destroy(le.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|N)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=ne,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Pe,this.map=r||n,this.pipeTo=null,this.afterRead=de.bind(this),this.afterUpdateNextTick=fe.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new B(this.stream,e,t),t&&this.stream.on(`error`,Fe),Oe(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Fe),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,V.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ie)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ie)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&I)===F&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&L)===0&&(e._duplexState|=N,e._destroy(le.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|N)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},ce=class{constructor(e){this.data=null,this.afterTransform=ge.bind(e),this.afterFinal=null}},B=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function V(){this.stream._duplexState|=512,this.updateCallback()}function H(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&I)===F&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function le(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function ue(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&me(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function de(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function fe(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function pe(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=ne,this.update())}function me(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function he(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=P,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ge(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function _e(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var ve=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,G.bind(this))),this.on(`newListener`,_e)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},ye=class e extends ve{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new se(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||Ee;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(W(t))return t;if(t[ae])return this._fromAsyncIterator(t[ae](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[ae](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ae](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},U=class extends ve{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new oe(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=M}uncork(){this._duplexState&=re,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(K(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},be=class extends ye{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new oe(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=M}uncork(){this._duplexState&=re,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},xe=class extends be{constructor(e){super(e),this._transformState=new ce(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(Ce.bind(this))}},Se=class extends xe{};function Ce(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function we(...e){return new Promise((t,n)=>Te(...e,e=>{if(e)return n(e);t()}))}function Te(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],Oe(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=Oe(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function Ee(e){return e}function De(e){return!!e._readableState||!!e._writableState}function Oe(e){return typeof e._duplexState==`number`&&De(e)}function ke(e){return!!e._readableState&&e._readableState.ended}function Ae(e){return!!e._writableState&&e._writableState.ended}function je(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function W(e){return Oe(e)&&e.readable}function Me(e){return(e._duplexState&1)!=1||(e._duplexState&L)!==0}function Ne(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Pe(e){return Ne(e)?e.byteLength:1024}function Fe(){}function G(){this.destroy(Error(`Stream aborted.`))}function K(e){return e._writev!==U.prototype._writev&&e._writev!==be.prototype._writev}t.exports={pipeline:Te,pipelinePromise:we,isStream:De,isStreamx:Oe,isEnded:ke,isFinished:Ae,isDisturbed:Me,getStreamError:je,Stream:ve,Writable:U,Readable:ye,Duplex:be,Transform:xe,PassThrough:Se}})}),Tt=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=bt(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
34
|
+
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),gt=a.__toESM(mt(),1),_t=a.__toESM(ht(),1),vt=(i=class e{constructor(e){this.processes=new Map,this.spawnListeners=[],this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}execute(t,n,r){let i=yt(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new _t.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new gt.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}},i.COLUMNS=80,i.ROWS=24,i.SCROLLBACK=128e3,i);let yt=(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new f,i=new f,a=(0,l.spawn)(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),a.on(`error`,e=>{throw e}),{pid:a.pid??-1,process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var bt=a.__commonJS({"../../node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),xt=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=bt();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),St=a.__commonJS({"../../node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t,n){return b(e).writeDoubleLE(t,n)}function w(e,t,n){return b(e).writeFloatLE(t,n)}function T(e,t,n){return b(e).writeUInt32LE(t,n)}function E(e,t,n){return b(e).writeInt32LE(t,n)}function D(e,t){return b(e).readDoubleLE(t)}function O(e,t){return b(e).readFloatLE(t)}function k(e,t){return b(e).readUInt32LE(t)}function A(e,t){return b(e).readInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function M(e,t,n){return b(e).writeFloatBE(t,n)}function N(e,t,n){return b(e).writeUInt32BE(t,n)}function ee(e,t,n){return b(e).writeInt32BE(t,n)}function te(e,t){return b(e).readDoubleBE(t)}function P(e,t){return b(e).readFloatBE(t)}function ne(e,t){return b(e).readUInt32BE(t)}function F(e,t){return b(e).readInt32BE(t)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,writeDoubleLE:C,writeFloatLE:w,writeUInt32LE:T,writeInt32LE:E,readDoubleLE:D,readFloatLE:O,readUInt32LE:k,readInt32LE:A,writeDoubleBE:j,writeFloatBE:M,writeUInt32BE:N,writeInt32BE:ee,readDoubleBE:te,readFloatBE:P,readUInt32BE:ne,readInt32BE:F}})}),Ct=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=St();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),wt=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=St();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),Tt=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=Ct(),r=wt();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),Et=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Y(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=xt(),o=Tt(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,M=512<<18,N=1024<<18;c^(C|j);let ee=c^T;c^(C|M),c^D,c^E;let te=c^A;c^w;let P=c^N,ne=16|C,F=c^ne,I=m|O,L=14|I;ee&536870847;let re=A|h;re&F;let R=33587215;u|16399;let ie=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let z=270794767;T|C,C|j,O|134217742;let ae=Symbol.asyncIterator||Symbol(`asyncIterator`);var oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ae,this.map=r||n,this.afterWrite=fe.bind(this),this.afterUpdateNextTick=he.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|M)&ee}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&z)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&z)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===M){e._duplexState|=C,e._final(ue.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&re)===0&&(e._duplexState|=ne,e._destroy(de.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|ne)&l,e._open(_e.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=te,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ae,this.map=r||n,this.pipeTo=null,this.afterRead=pe.bind(this),this.afterUpdateNextTick=me.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new le(this.stream,e,t),t&&this.stream.on(`error`,je),q(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,je),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,B.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ie)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ie)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&L)===I&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&re)===0&&(e._duplexState|=ne,e._destroy(de.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|ne)&l,e._open(_e.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},ce=class{constructor(e){this.data=null,this.afterTransform=ve.bind(e),this.afterFinal=null}},le=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function B(){this.stream._duplexState|=512,this.updateCallback()}function ue(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&L)===I&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function de(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function fe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&ge(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function pe(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function me(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function he(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=te,this.update())}function ge(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function _e(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=F,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ve(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function ye(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var be=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Me.bind(this))),this.on(`newListener`,ye)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},xe=class e extends be{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new se(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||G;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Oe(t))return t;if(t[ae])return this._fromAsyncIterator(t[ae](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[ae](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ae](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},V=class extends be{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new oe(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=N}uncork(){this._duplexState&=P,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ne(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Se=class extends xe{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new oe(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=N}uncork(){this._duplexState&=P,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Ce=class extends Se{constructor(e){super(e),this._transformState=new ce(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(U.bind(this))}},H=class extends Ce{};function U(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function we(...e){return new Promise((t,n)=>W(...e,e=>{if(e)return n(e);t()}))}function W(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],q(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=q(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function G(e){return e}function K(e){return!!e._readableState||!!e._writableState}function q(e){return typeof e._duplexState==`number`&&K(e)}function Te(e){return!!e._readableState&&e._readableState.ended}function Ee(e){return!!e._writableState&&e._writableState.ended}function De(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function Oe(e){return q(e)&&e.readable}function J(e){return(e._duplexState&1)!=1||(e._duplexState&re)!==0}function ke(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ae(e){return ke(e)?e.byteLength:1024}function je(){}function Me(){this.destroy(Error(`Stream aborted.`))}function Ne(e){return e._writev!==V.prototype._writev&&e._writev!==Se.prototype._writev}t.exports={pipeline:W,pipelinePromise:we,isStream:K,isStreamx:q,isEnded:Te,isFinished:Ee,isDisturbed:J,getStreamError:De,Stream:be,Writable:V,Readable:xe,Duplex:Se,Transform:Ce,PassThrough:H}})}),Dt=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=St(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
35
35
|
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
|
|
36
36
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
37
|
-
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Et=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=wt(),a=yt(),o=bt(),s=Tt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),Dt=a.__commonJS({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=Z(`fs`).constants||n}catch{t.exports=n}})}),Ot=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=wt(),a=bt(),o=Dt(),s=Tt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),kt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Et(),e.pack=Ot()})}),At=a.__toESM(kt(),1);let jt=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=At.pack(),i=async(e,t=``)=>{let n=await o.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,s=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(a.isSymbolicLink?.()){let e=await o.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await o.stat(n);await new Promise((t,i)=>{let a=(0,d.createReadStream)(n),o=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>o.write(e)),a.on(`end`,()=>{o.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,s=0,c=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})},Mt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Nt=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Pt=class{constructor(e){this.decoder=new TextDecoder,this.encoder=new TextEncoder,this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new y({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new gt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=g.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case a.ClientMessageType.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case a.ClientMessageType.PROXY_INIT:{let t=a.ClientMessageSchema[a.ClientMessageType.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new u.WebSocket(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_MESSAGE,a.createWebSocketMessagePayload(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case a.ClientMessageType.PROXY_WEBSOCKET_MESSAGE:{let e=a.parseWebSocketMessagePayload(n,this.decoder);r.send(e);break}case a.ClientMessageType.PROXY_WEBSOCKET_CLOSE:{let e=a.ClientMessageSchema[a.ClientMessageType.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case a.ClientMessageType.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},o;o=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let s={};o.headers.forEach((e,t)=>{s[t]=e});let c={headers:s,status_code:o.status,status_message:o.statusText};e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify(c)));let l=o.headers.get(`content-length`),u=l?parseInt(l):0,d=g.getMaxPayloadSize()-1;if(u>=d){if(!o.body){e.close();return}let t=o.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(d,r.length-t),i=r.subarray(t,t+n);e.writeTyped(a.ServerMessageType.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else o.body&&await o.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(a.ServerMessageType.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=a.RequestSchema[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Nt(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await jt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await c.readFile(t.payload.path),r=await ct(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
37
|
+
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Ot=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Et(),a=xt(),o=St(),s=Dt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),kt=a.__commonJS({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=Y(`fs`).constants||n}catch{t.exports=n}})}),At=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Et(),a=St(),o=kt(),s=Dt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),jt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Ot(),e.pack=At()})}),Mt=a.__toESM(jt(),1);let Nt=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=Mt.pack(),i=async(e,t=``)=>{let n=await o.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,s=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(a.isSymbolicLink?.()){let e=await o.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await o.stat(n);await new Promise((t,i)=>{let a=(0,d.createReadStream)(n),o=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>o.write(e)),a.on(`end`,()=>{o.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,s=0,c=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})},Pt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Ft=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var It=class{constructor(e){this.decoder=new TextDecoder,this.encoder=new TextEncoder,this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new y({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new vt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=g.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case a.ClientMessageType.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case a.ClientMessageType.PROXY_INIT:{let t=a.ClientMessageSchema[a.ClientMessageType.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new u.WebSocket(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_MESSAGE,a.createWebSocketMessagePayload(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case a.ClientMessageType.PROXY_WEBSOCKET_MESSAGE:{let e=a.parseWebSocketMessagePayload(n,this.decoder);r.send(e);break}case a.ClientMessageType.PROXY_WEBSOCKET_CLOSE:{let e=a.ClientMessageSchema[a.ClientMessageType.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case a.ClientMessageType.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},o;o=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let s={};o.headers.forEach((e,t)=>{s[t]=e});let c={headers:s,status_code:o.status,status_message:o.statusText};e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify(c)));let l=o.headers.get(`content-length`),u=l?parseInt(l):0,d=g.getMaxPayloadSize()-1;if(u>=d){if(!o.body){e.close();return}let t=o.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(d,r.length-t),i=r.subarray(t,t+n);e.writeTyped(a.ServerMessageType.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else o.body&&await o.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(a.ServerMessageType.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=a.RequestSchema[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Ft(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await Nt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await c.readFile(t.payload.path),r=await ut(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
38
38
|
`),a=(t.payload.line_start??1)-1,o=t.payload.line_end??i.length,s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
39
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Mt(this.processManager.readANSIOutput(i.pid),64e3),f=Nt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Pt}})})}),ms=Ji({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Xo(),e.Server=ps().Server})}),hs=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=ms(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let gs=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),_s=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});gs.REQUEST,Y.string(),gs.PROXY_INIT,Y.object({method:Y.string(),headers:Y.record(Y.string(),Y.string()),url:Y.string()}),gs.PROXY_BODY,Y.instanceof(Uint8Array),gs.PROXY_WEBSOCKET_MESSAGE,Y.object({type:Y.enum([`text`,`binary`]),data:Y.instanceof(Uint8Array)}),gs.PROXY_WEBSOCKET_CLOSE,Y.object({code:Y.number().optional(),reason:Y.string().optional()}),_s.RESPONSE,Y.string(),_s.NOTIFICATION,Y.string(),_s.PROXY_INIT,Y.object({status_code:Y.number(),status_message:Y.string(),headers:Y.record(Y.string(),Y.string())}),_s.PROXY_DATA,Y.instanceof(Uint8Array),_s.PROXY_WEBSOCKET_MESSAGE,Y.instanceof(Uint8Array),_s.PROXY_WEBSOCKET_CLOSE,Y.object({code:Y.number(),reason:Y.string()}),gs.PROXY_INIT,Y.string(),Y.record(Y.string(),Y.string()),Y.string(),Y.object({command:Y.string(),args:Y.array(Y.string()),env:Y.record(Y.string(),Y.string()).optional(),cwd:Y.string().optional()}),Y.object({pid:Y.number(),data:Y.string()}),Y.object({pid:Y.number(),output_idle_timeout_ms:Y.number().optional(),timeout_ms:Y.number().optional()}),Y.object({include_dead:Y.boolean().optional()}),Y.object({pid:Y.number(),start_line:Y.number().optional(),end_line:Y.number().optional()}),Y.object({pid:Y.number(),signal:Y.string().optional()}),Y.object({env:Y.record(Y.string(),Y.string())}),Y.object({path:Y.string(),line_start:Y.number().optional(),line_end:Y.number().optional()}),Y.object({path:Y.string(),content:Y.string(),base64:Y.boolean().optional(),mode:Y.number().optional()}),Y.object({path:Y.string()}),Y.object({path:Y.string()}),Y.object({path:Y.string()});const vs=Y.object({pid:Y.number(),command:Y.string(),args:Y.array(Y.string()),title:Y.string().optional(),cwd:Y.string(),env:Y.record(Y.string(),Y.string()),exit_code:Y.number().optional(),exit_signal:Y.number().optional(),duration_ms:Y.number().optional(),output_total_lines:Y.number()});vs.extend({ansi_output:Y.string(),plain_output:Y.object({lines:Y.array(Y.string()),total_lines:Y.number()})}),Y.object({pid:Y.number()}),Y.object({}),Y.object({processes:Y.array(vs)}),Y.object({lines:Y.array(Y.string()),total_lines:Y.number(),duration_ms:Y.number(),exit_code:Y.number().optional(),exit_signal:Y.number().optional()}),Y.object({}),Y.object({}),Y.object({total_lines:Y.number(),lines_read:Y.number(),start_line:Y.number(),content:Y.string(),mime_type:Y.string()}),Y.object({}),Y.object({entries:Y.array(Y.object({name:Y.string(),type:Y.enum([`file`,`directory`,`symlink`])}))}),Y.object({}),Y.object({deployment_id:Y.string()});const ys=Y.object({type:Y.enum([`create`,`update`,`delete`]),path:Y.string()}),bs=Y.object({type:Y.enum([`context`,`added`,`deleted`]),content:Y.string(),oldLineNumber:Y.number().optional(),newLineNumber:Y.number().optional()}),xs=Y.object({oldStart:Y.number(),oldLines:Y.number(),newStart:Y.number(),newLines:Y.number(),lines:Y.array(bs)}),Ss=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:Y.string().optional(),insertions:Y.number(),deletions:Y.number(),chunks:Y.array(xs)}),Cs=Y.object({totalFiles:Y.number(),totalInsertions:Y.number(),totalDeletions:Y.number(),netChange:Y.number(),startHash:Y.string().optional(),currentHash:Y.string().optional(),timespan:Y.number(),files:Y.array(Ss)}),ws=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:Y.boolean()}),Ts=Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),email:Y.string(),date:Y.date(),timestamp:Y.date(),filesChanged:Y.number(),insertions:Y.number(),deletions:Y.number(),commitDiff:Y.array(Ss).optional()});Y.object({files:Y.array(ws),branch:Y.string(),ahead:Y.number(),behind:Y.number(),timestamp:Y.date(),sessionDiff:Cs.optional(),workingDirectoryDiff:Cs.optional(),newCommits:Y.array(Ts),currentCommit:Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),date:Y.date()}).optional(),diffSkipped:Y.boolean().optional(),payloadTruncated:Y.boolean().optional(),estimatedSizeKB:Y.number().optional()}),Y.object({debounceDelay:Y.number().optional(),gitStatusInterval:Y.number().optional(),ignoreDotfiles:Y.boolean().optional(),ignored:Y.array(Y.string()).optional(),watchGit:Y.boolean().optional(),includeDiffs:Y.boolean().optional(),maxDiffFiles:Y.number().optional(),maxPayloadSizeKB:Y.number().optional(),truncateLargeDiffs:Y.boolean().optional()}),Y.object({status:vs}),Y.object({pid:Y.number(),output:Y.string()}),Y.object({changes:Y.array(ys)});var Es=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};Y.object({}),Y.object({id:Y.string(),token:Y.string()});var Ds=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await Q(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new Es({send:e=>t.send(e)})}},Os=class{constructor(e){this.client=e,this.compute=new Ds(this.client)}},ks=class extends Yo{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new hs(this),this.tools=new Os(this)}},As=e((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),js=e((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),Ms=e((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),Ns=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var a=r(i(`os`)),o=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:a,path:o,process}})),Ps=e(((e,t)=>{var n=Ms(),r=Ns();t.exports=n.Adapt(r.adapter).OSPaths})),Fs=n({default:()=>Rs}),Is,Ls,Rs,zs=t((()=>{Is=o(Ps()),Ls=Is.default,Rs=Ls})),Bs=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:o((zs(),a(Fs))).default,path:s,process}})),Vs=e(((e,t)=>{var n=js(),r=Bs();t.exports=n.Adapt(r.adapter).XDG})),Hs=n({default:()=>Ws}),Us,Ws,Gs=t((()=>{Us=o(Vs()),r(Hs,o(Vs())),Ws=Us.default})),Ks=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`)),c=o((Gs(),a(Hs)));e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(i!=null&&i.main?i.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:s,process,xdg:c.default}})),qs=o(e(((e,t)=>{var n=As(),r=Ks();t.exports=n.Adapt(r.adapter).XDGAppPaths}))()).default,Js=e(((e,t)=>{t.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})),Ys=e(((e,t)=>{let n=Js(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={rgb:{channels:3,labels:`rgb`},hsl:{channels:3,labels:`hsl`},hsv:{channels:3,labels:`hsv`},hwb:{channels:3,labels:`hwb`},cmyk:{channels:4,labels:`cmyk`},xyz:{channels:3,labels:`xyz`},lab:{channels:3,labels:`lab`},lch:{channels:3,labels:`lch`},hex:{channels:1,labels:[`hex`]},keyword:{channels:1,labels:[`keyword`]},ansi16:{channels:1,labels:[`ansi16`]},ansi256:{channels:1,labels:[`ansi256`]},hcg:{channels:3,labels:[`h`,`c`,`g`]},apple:{channels:3,labels:[`r16`,`g16`,`b16`]},gray:{channels:1,labels:[`gray`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),Xs=e(((e,t)=>{let n=Ys();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),Zs=e(((e,t)=>{let n=Ys(),r=Xs(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),Qs=e(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=Zs());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),$s=e(((e,t)=>{let n=i(`os`),r=i(`tty`),a=I(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let r=s||0;if(o.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:r}function u(e){let t=l(e,e&&e.isTTY);return c(t)}t.exports={supportsColor:u,stdout:c(l(!0,r.isatty(1))),stderr:c(l(!0,r.isatty(2)))}})),ec=e(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
39
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Pt(this.processManager.readANSIOutput(i.pid),64e3),f=Ft(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return It}})})}),zu=Sc({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Cu(),e.Server=Ru().Server})}),Bu=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=zu(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let Vu=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),Hu=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});Vu.REQUEST,q.string(),Vu.PROXY_INIT,q.object({method:q.string(),headers:q.record(q.string(),q.string()),url:q.string()}),Vu.PROXY_BODY,q.instanceof(Uint8Array),Vu.PROXY_WEBSOCKET_MESSAGE,q.object({type:q.enum([`text`,`binary`]),data:q.instanceof(Uint8Array)}),Vu.PROXY_WEBSOCKET_CLOSE,q.object({code:q.number().optional(),reason:q.string().optional()}),Hu.RESPONSE,q.string(),Hu.NOTIFICATION,q.string(),Hu.PROXY_INIT,q.object({status_code:q.number(),status_message:q.string(),headers:q.record(q.string(),q.string())}),Hu.PROXY_DATA,q.instanceof(Uint8Array),Hu.PROXY_WEBSOCKET_MESSAGE,q.instanceof(Uint8Array),Hu.PROXY_WEBSOCKET_CLOSE,q.object({code:q.number(),reason:q.string()}),Vu.PROXY_INIT,q.string(),q.record(q.string(),q.string()),q.string(),q.object({command:q.string(),args:q.array(q.string()),env:q.record(q.string(),q.string()).optional(),cwd:q.string().optional()}),q.object({pid:q.number(),data:q.string()}),q.object({pid:q.number(),output_idle_timeout_ms:q.number().optional(),timeout_ms:q.number().optional()}),q.object({include_dead:q.boolean().optional()}),q.object({pid:q.number(),start_line:q.number().optional(),end_line:q.number().optional()}),q.object({pid:q.number(),signal:q.string().optional()}),q.object({env:q.record(q.string(),q.string())}),q.object({path:q.string(),line_start:q.number().optional(),line_end:q.number().optional()}),q.object({path:q.string(),content:q.string(),base64:q.boolean().optional(),mode:q.number().optional()}),q.object({path:q.string()}),q.object({path:q.string()}),q.object({path:q.string()});const Uu=q.object({pid:q.number(),command:q.string(),args:q.array(q.string()),title:q.string().optional(),cwd:q.string(),env:q.record(q.string(),q.string()),exit_code:q.number().optional(),exit_signal:q.number().optional(),duration_ms:q.number().optional(),output_total_lines:q.number()});Uu.extend({ansi_output:q.string(),plain_output:q.object({lines:q.array(q.string()),total_lines:q.number()})}),q.object({pid:q.number()}),q.object({}),q.object({processes:q.array(Uu)}),q.object({lines:q.array(q.string()),total_lines:q.number(),duration_ms:q.number(),exit_code:q.number().optional(),exit_signal:q.number().optional()}),q.object({}),q.object({}),q.object({total_lines:q.number(),lines_read:q.number(),start_line:q.number(),content:q.string(),mime_type:q.string()}),q.object({}),q.object({entries:q.array(q.object({name:q.string(),type:q.enum([`file`,`directory`,`symlink`])}))}),q.object({}),q.object({deployment_id:q.string()});const Wu=q.object({type:q.enum([`create`,`update`,`delete`]),path:q.string()}),Gu=q.object({type:q.enum([`context`,`added`,`deleted`]),content:q.string(),oldLineNumber:q.number().optional(),newLineNumber:q.number().optional()}),Ku=q.object({oldStart:q.number(),oldLines:q.number(),newStart:q.number(),newLines:q.number(),lines:q.array(Gu)}),qu=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:q.string().optional(),insertions:q.number(),deletions:q.number(),chunks:q.array(Ku)}),Ju=q.object({totalFiles:q.number(),totalInsertions:q.number(),totalDeletions:q.number(),netChange:q.number(),startHash:q.string().optional(),currentHash:q.string().optional(),timespan:q.number(),files:q.array(qu)}),Yu=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:q.boolean()}),Xu=q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),email:q.string(),date:q.date(),timestamp:q.date(),filesChanged:q.number(),insertions:q.number(),deletions:q.number(),commitDiff:q.array(qu).optional()});q.object({files:q.array(Yu),branch:q.string(),ahead:q.number(),behind:q.number(),timestamp:q.date(),sessionDiff:Ju.optional(),workingDirectoryDiff:Ju.optional(),newCommits:q.array(Xu),currentCommit:q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),date:q.date()}).optional(),diffSkipped:q.boolean().optional(),payloadTruncated:q.boolean().optional(),estimatedSizeKB:q.number().optional()}),q.object({debounceDelay:q.number().optional(),gitStatusInterval:q.number().optional(),ignoreDotfiles:q.boolean().optional(),ignored:q.array(q.string()).optional(),watchGit:q.boolean().optional(),includeDiffs:q.boolean().optional(),maxDiffFiles:q.number().optional(),maxPayloadSizeKB:q.number().optional(),truncateLargeDiffs:q.boolean().optional()}),q.object({status:Uu}),q.object({pid:q.number(),output:q.string()}),q.object({changes:q.array(Wu)});var Zu=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};q.object({}),q.object({id:q.string(),token:q.string()});var Qu=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await X(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new Zu({send:e=>t.send(e)})}},$u=class{constructor(e){this.client=e,this.compute=new Qu(this.client)}},ed=class extends Su{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Bu(this),this.tools=new $u(this)}},td=e((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),nd=e((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),rd=e((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),id=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var a=r(i(`os`)),o=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:a,path:o,process}})),ad=e(((e,t)=>{var n=rd(),r=id();t.exports=n.Adapt(r.adapter).OSPaths})),od=n({default:()=>ld}),sd,cd,ld,ud=t((()=>{sd=o(ad()),cd=sd.default,ld=cd})),dd=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:o((ud(),a(od))).default,path:s,process}})),fd=e(((e,t)=>{var n=nd(),r=dd();t.exports=n.Adapt(r.adapter).XDG})),pd=n({default:()=>hd}),md,hd,gd=t((()=>{md=o(fd()),r(pd,o(fd())),hd=md.default})),_d=e((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`)),c=o((gd(),a(pd)));e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(i!=null&&i.main?i.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:s,process,xdg:c.default}})),vd=o(e(((e,t)=>{var n=td(),r=_d();t.exports=n.Adapt(r.adapter).XDGAppPaths}))()).default;const yd=(e=0)=>t=>`\u001B[${t+e}m`,bd=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,xd=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,Z={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Z.modifier);const Sd=Object.keys(Z.color),Cd=Object.keys(Z.bgColor);[...Sd,...Cd];function wd(){let e=new Map;for(let[t,n]of Object.entries(Z)){for(let[t,r]of Object.entries(n))Z[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=Z[t],e.set(r[0],r[1]);Object.defineProperty(Z,t,{value:n,enumerable:!1})}return Object.defineProperty(Z,`codes`,{value:e,enumerable:!1}),Z.color.close=`\x1B[39m`,Z.bgColor.close=`\x1B[49m`,Z.color.ansi=yd(),Z.color.ansi256=bd(),Z.color.ansi16m=xd(),Z.bgColor.ansi=yd(10),Z.bgColor.ansi256=bd(10),Z.bgColor.ansi16m=xd(10),Object.defineProperties(Z,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Z.rgbToAnsi256(...Z.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Z.ansi256ToAnsi(Z.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Z.ansi256ToAnsi(Z.hexToAnsi256(e)),enumerable:!1}}),Z}var Td=wd();function Ed(e,t=globalThis.Deno?globalThis.Deno.args:J.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:Q}=J;let Dd;Ed(`no-color`)||Ed(`no-colors`)||Ed(`color=false`)||Ed(`color=never`)?Dd=0:(Ed(`color`)||Ed(`colors`)||Ed(`color=true`)||Ed(`color=always`))&&(Dd=1);function Od(){if(`FORCE_COLOR`in Q)return Q.FORCE_COLOR===`true`?1:Q.FORCE_COLOR===`false`?0:Q.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Q.FORCE_COLOR,10),3)}function kd(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ad(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Od();r!==void 0&&(Dd=r);let i=n?Dd:r;if(i===0)return 0;if(n){if(Ed(`color=16m`)||Ed(`color=full`)||Ed(`color=truecolor`))return 3;if(Ed(`color=256`))return 2}if(`TF_BUILD`in Q&&`AGENT_NAME`in Q)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Q.TERM===`dumb`)return a;if(J.platform===`win32`){let e=je.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in Q)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Q)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Q)||Q.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Q)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION)?1:0;if(Q.COLORTERM===`truecolor`||Q.TERM===`xterm-kitty`||Q.TERM===`xterm-ghostty`||Q.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Q){let e=Number.parseInt((Q.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Q.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Q.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM)||`COLORTERM`in Q?1:a}function jd(e,t={}){let n=Ad(e,{streamIsTTY:e&&e.isTTY,...t});return kd(n)}var Md={stdout:jd({isTTY:Me.isatty(1)}),stderr:jd({isTTY:Me.isatty(2)})};function Nd(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function Pd(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
40
40
|
`:`
|
|
41
41
|
`)+n,i=r+1,r=e.indexOf(`
|
|
42
|
-
`,i)}while(r!==-1);return a+=e.
|
|
43
|
-
`],[`r`,`\r`],[`t`,` `],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`0`,`\0`],[`\\`,`\\`],[`e`,`\x1B`],[`a`,`\x07`]]);function s(e){let t=e[0]===`u`,n=e[1]===`{`;return t&&!n&&e.length===5||e[0]===`x`&&e.length===3?String.fromCharCode(parseInt(e.slice(1),16)):t&&n?String.fromCodePoint(parseInt(e.slice(2,-1),16)):o.get(e)||e}function c(e,t){let n=[],r=t.trim().split(/\s*,\s*/g),o;for(let t of r){let r=Number(t);if(!Number.isNaN(r))n.push(r);else if(o=t.match(i))n.push(o[2].replace(a,(e,t,n)=>t?s(t):n));else throw Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`)}return n}function l(e){r.lastIndex=0;let t=[],n;for(;(n=r.exec(e))!==null;){let e=n[1];if(n[2]){let r=c(e,n[2]);t.push([e].concat(r))}else t.push([e])}return t}function u(e,t){let n={};for(let e of t)for(let t of e.styles)n[t[0]]=e.inverse?null:t.slice(1);let r=e;for(let[e,t]of Object.entries(n))if(Array.isArray(t)){if(!(e in r))throw Error(`Unknown Chalk style: ${e}`);r=t.length>0?r[e](...t):r[e]}return r}t.exports=(e,t)=>{let r=[],i=[],a=[];if(t.replace(n,(t,n,o,c,d,f)=>{if(n)a.push(s(n));else if(c){let t=a.join(``);a=[],i.push(r.length===0?t:u(e,r)(t)),r.push({inverse:o,styles:l(c)})}else if(d){if(r.length===0)throw Error(`Found extraneous } in Chalk template literal`);i.push(u(e,r)(a.join(``))),a=[],r.pop()}else a.push(f)}),i.push(a.join(``)),r.length>0){let e=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?``:`s`} (\`}\`)`;throw Error(e)}return i.join(``)}})),nc=e(((e,t)=>{let n=Qs(),{stdout:r,stderr:i}=$s(),{stringReplaceAll:a,stringEncaseCRLFWithFirstIndex:o}=ec(),{isArray:s}=Array,c=[`ansi`,`ansi`,`ansi256`,`ansi16m`],l=Object.create(null),u=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=r?r.level:0;e.level=t.level===void 0?n:t.level};var d=class{constructor(e){return f(e)}};let f=e=>{let t={};return u(t,e),t.template=(...e)=>b(t.template,...e),Object.setPrototypeOf(t,p.prototype),Object.setPrototypeOf(t.template,t),t.template.constructor=()=>{throw Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},t.template.Instance=d,t.template};function p(e){return f(e)}for(let[e,t]of Object.entries(n))l[e]={get(){let n=_(this,g(t.open,t.close,this._styler),this._isEmpty);return Object.defineProperty(this,e,{value:n}),n}};l.visible={get(){let e=_(this,this._styler,!0);return Object.defineProperty(this,`visible`,{value:e}),e}};let m=[`rgb`,`hex`,`keyword`,`hsl`,`hsv`,`hwb`,`ansi`,`ansi256`];for(let e of m)l[e]={get(){let{level:t}=this;return function(...r){let i=g(n.color[c[t]][e](...r),n.color.close,this._styler);return _(this,i,this._isEmpty)}}};for(let e of m){let t=`bg`+e[0].toUpperCase()+e.slice(1);l[t]={get(){let{level:t}=this;return function(...r){let i=g(n.bgColor[c[t]][e](...r),n.bgColor.close,this._styler);return _(this,i,this._isEmpty)}}}}let h=Object.defineProperties(()=>{},{...l,level:{enumerable:!0,get(){return this._generator.level},set(e){this._generator.level=e}}}),g=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},_=(e,t,n)=>{let r=(...e)=>s(e[0])&&s(e[0].raw)?v(r,b(r,...e)):v(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,h),r._generator=e,r._styler=t,r._isEmpty=n,r},v=(e,t)=>{if(e.level<=0||!t)return e._isEmpty?``:t;let n=e._styler;if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.indexOf(`\x1B`)!==-1)for(;n!==void 0;)t=a(t,n.close,n.open),n=n.parent;let s=t.indexOf(`
|
|
44
|
-
`);return s!==-1&&(t=o(t,i,r,s)),r+t+i},y,b=(e,...t)=>{let[n]=t;if(!s(n)||!s(n.raw))return t.join(` `);let r=t.slice(1),i=[n.raw[0]];for(let e=1;e<n.length;e++)i.push(String(r[e-1]).replace(/[{}\\]/g,`\\$&`),String(n.raw[e]));return y===void 0&&(y=tc()),y(e,i.join(``))};Object.defineProperties(p.prototype,l);let x=p();x.supportsColor=r,x.stderr=p({level:i?i.level:0}),x.stderr.supportsColor=i,t.exports=x})),rc=e(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),ic=e(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),ac=o(nc());rc(),ic();function oc({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}oc();function sc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var cc={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(cc);var lc=cc.exports;sc(lc),sc(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g});const uc=(e=0)=>t=>`\x1B[${t+e}m`,dc=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,fc=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys($.modifier);const pc=Object.keys($.color),mc=Object.keys($.bgColor);[...pc,...mc];function hc(){let e=new Map;for(let[t,n]of Object.entries($)){for(let[t,r]of Object.entries(n))$[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=$[t],e.set(r[0],r[1]);Object.defineProperty($,t,{value:n,enumerable:!1})}return Object.defineProperty($,`codes`,{value:e,enumerable:!1}),$.color.close=`\x1B[39m`,$.bgColor.close=`\x1B[49m`,$.color.ansi=uc(),$.color.ansi256=dc(),$.color.ansi16m=fc(),$.bgColor.ansi=uc(10),$.bgColor.ansi256=dc(10),$.bgColor.ansi16m=fc(10),Object.defineProperties($,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>$.rgbToAnsi256(...$.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>$.ansi256ToAnsi($.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>$.ansi256ToAnsi($.hexToAnsi256(e)),enumerable:!1}}),$}hc();const gc={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function _c(e,t){if(typeof e==`string`)return gc.aliases.get(e)===t;for(let n of e)if(n!==void 0&&_c(n,t))return!0;return!1}globalThis.process.platform.startsWith(`win`),Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty;var vc=o(ic(),1);rc();function yc(){return X.platform===`win32`?!!X.env.CI||!!X.env.WT_SESSION||!!X.env.TERMINUS_SUBLIME||X.env.ConEmuTask===`{cmd::Cmder}`||X.env.TERM_PROGRAM===`Terminus-Sublime`||X.env.TERM_PROGRAM===`vscode`||X.env.TERM===`xterm-256color`||X.env.TERM===`alacritty`||X.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:X.env.TERM!==`linux`}const bc=yc(),xc=(e,t)=>bc?e:t,Sc=xc(`◇`,`o`),Cc=xc(`│`,`|`),wc=xc(`●`,`•`),Tc=xc(`◆`,`*`),Ec=xc(`▲`,`!`),Dc=xc(`■`,`x`),Oc={message:(e=``,{symbol:t=vc.default.gray(Cc)}={})=>{let n=[`${vc.default.gray(Cc)}`];if(e){let[r,...i]=e.split(`
|
|
45
|
-
`);n.push(`${t} ${r}`,...i.map(e=>`${vc.default.gray(Cc)} ${e}`))}process.stdout.write(`${n.join(`
|
|
42
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:Fd,stderr:Id}=Md,Ld=Symbol(`GENERATOR`),Rd=Symbol(`STYLER`),zd=Symbol(`IS_EMPTY`),Bd=[`ansi`,`ansi`,`ansi256`,`ansi16m`],Vd=Object.create(null),Hd=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=Fd?Fd.level:0;e.level=t.level===void 0?n:t.level},Ud=e=>{let t=(...e)=>e.join(` `);return Hd(t,e),Object.setPrototypeOf(t,Wd.prototype),t};function Wd(e){return Ud(e)}Object.setPrototypeOf(Wd.prototype,Function.prototype);for(let[e,t]of Object.entries(Td))Vd[e]={get(){let n=Jd(this,qd(t.open,t.close,this[Rd]),this[zd]);return Object.defineProperty(this,e,{value:n}),n}};Vd.visible={get(){let e=Jd(this,this[Rd],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const Gd=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?Td[n].ansi16m(...r):t===`ansi256`?Td[n].ansi256(Td.rgbToAnsi256(...r)):Td[n].ansi(Td.rgbToAnsi(...r)):e===`hex`?Gd(`rgb`,t,n,...Td.hexToRgb(...r)):Td[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){Vd[e]={get(){let{level:t}=this;return function(...n){let r=qd(Gd(e,Bd[t],`color`,...n),Td.color.close,this[Rd]);return Jd(this,r,this[zd])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);Vd[t]={get(){let{level:t}=this;return function(...n){let r=qd(Gd(e,Bd[t],`bgColor`,...n),Td.bgColor.close,this[Rd]);return Jd(this,r,this[zd])}}}}const Kd=Object.defineProperties(()=>{},{...Vd,level:{enumerable:!0,get(){return this[Ld].level},set(e){this[Ld].level=e}}}),qd=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},Jd=(e,t,n)=>{let r=(...e)=>Yd(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,Kd),r[Ld]=e,r[Rd]=t,r[zd]=n,r},Yd=(e,t)=>{if(e.level<=0||!t)return e[zd]?``:t;let n=e[Rd];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=Nd(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
43
|
+
`);return a!==-1&&(t=Pd(t,i,r,a)),r+t+i};Object.defineProperties(Wd.prototype,Vd);const Xd=Wd();Wd({level:Id?Id.level:0});var Zd=Xd,Qd=e(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),$d=e(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}));Qd(),$d();function ef({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}ef();function tf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var nf={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(nf);var rf=nf.exports;tf(rf),tf(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g});const af=(e=0)=>t=>`\x1B[${t+e}m`,sf=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,cf=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys($.modifier);const lf=Object.keys($.color),uf=Object.keys($.bgColor);[...lf,...uf];function df(){let e=new Map;for(let[t,n]of Object.entries($)){for(let[t,r]of Object.entries(n))$[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=$[t],e.set(r[0],r[1]);Object.defineProperty($,t,{value:n,enumerable:!1})}return Object.defineProperty($,`codes`,{value:e,enumerable:!1}),$.color.close=`\x1B[39m`,$.bgColor.close=`\x1B[49m`,$.color.ansi=af(),$.color.ansi256=sf(),$.color.ansi16m=cf(),$.bgColor.ansi=af(10),$.bgColor.ansi256=sf(10),$.bgColor.ansi16m=cf(10),Object.defineProperties($,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>$.rgbToAnsi256(...$.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>$.ansi256ToAnsi($.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>$.ansi256ToAnsi($.hexToAnsi256(e)),enumerable:!1}}),$}df();const ff={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function pf(e,t){if(typeof e==`string`)return ff.aliases.get(e)===t;for(let n of e)if(n!==void 0&&pf(n,t))return!0;return!1}globalThis.process.platform.startsWith(`win`),Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty;var mf=o($d(),1);Qd();function hf(){return J.platform===`win32`?!!J.env.CI||!!J.env.WT_SESSION||!!J.env.TERMINUS_SUBLIME||J.env.ConEmuTask===`{cmd::Cmder}`||J.env.TERM_PROGRAM===`Terminus-Sublime`||J.env.TERM_PROGRAM===`vscode`||J.env.TERM===`xterm-256color`||J.env.TERM===`alacritty`||J.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:J.env.TERM!==`linux`}const gf=hf(),_f=(e,t)=>gf?e:t,vf=_f(`◇`,`o`),yf=_f(`│`,`|`),bf=_f(`●`,`•`),xf=_f(`◆`,`*`),Sf=_f(`▲`,`!`),Cf=_f(`■`,`x`),wf={message:(e=``,{symbol:t=mf.default.gray(yf)}={})=>{let n=[`${mf.default.gray(yf)}`];if(e){let[r,...i]=e.split(`
|
|
44
|
+
`);n.push(`${t} ${r}`,...i.map(e=>`${mf.default.gray(yf)} ${e}`))}process.stdout.write(`${n.join(`
|
|
46
45
|
`)}
|
|
47
|
-
`)},info:e=>{
|
|
46
|
+
`)},info:e=>{wf.message(e,{symbol:mf.default.blue(bf)})},success:e=>{wf.message(e,{symbol:mf.default.green(xf)})},step:e=>{wf.message(e,{symbol:mf.default.green(vf)})},warn:e=>{wf.message(e,{symbol:mf.default.yellow(Sf)})},warning:e=>{wf.warn(e)},error:e=>{wf.message(e,{symbol:mf.default.red(Cf)})}},Tf=`${mf.default.gray(yf)} `,Ef={message:async(e,{symbol:t=mf.default.gray(yf)}={})=>{process.stdout.write(`${mf.default.gray(yf)}
|
|
48
47
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
49
|
-
${
|
|
50
|
-
`)&&(n=3+
|
|
51
|
-
`))).length);let e=
|
|
52
|
-
${
|
|
53
|
-
`)},info:e=>Ac.message(e,{symbol:vc.default.blue(wc)}),success:e=>Ac.message(e,{symbol:vc.default.green(Tc)}),step:e=>Ac.message(e,{symbol:vc.default.green(Sc)}),warn:e=>Ac.message(e,{symbol:vc.default.yellow(Ec)}),warning:e=>Ac.warn(e),error:e=>Ac.message(e,{symbol:vc.default.red(Dc)})};let jc;function Mc(){try{return le.statSync(`/.dockerenv`),!0}catch{return!1}}function Nc(){try{return le.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Pc(){return jc===void 0&&(jc=Mc()||Nc()),jc}let Fc;const Ic=()=>{try{return le.statSync(`/run/.containerenv`),!0}catch{return!1}};function Lc(){return Fc===void 0&&(Fc=Ic()||Pc()),Fc}const Rc=()=>{if(X.platform!==`linux`)return!1;if(Xe.release().toLowerCase().includes(`microsoft`))return!Lc();try{return le.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Lc():!1}catch{return!1}};var zc=X.env.__IS_WSL_TEST__?Rc:Rc();const Bc=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Je.access(n,Ye.F_OK),r=!0}catch{}if(!r)return e;let i=await Je.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Vc=async()=>`${await Bc()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Hc=async()=>zc?Vc():`${X.env.SYSTEMROOT||X.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Uc(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Wc=_e(qe);async function Gc(){if(X.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Wc(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Kc=_e(qe);async function qc(e,{humanReadableOutput:t=!0,signal:n}={}){if(X.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Kc(`osascript`,[`-e`,e,r],i);return a.trim()}async function Jc(e){return qc(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Yc=_e(qe),Xc={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Zc=class extends Error{};async function Qc(e=Yc){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Zc(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Xc[r];if(!i)throw new Zc(`Unknown browser ID: ${r}`);return i}const $c=_e(qe),el=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function tl(){if(X.platform===`darwin`){let e=await Gc();return{name:await Jc(e),id:e}}if(X.platform===`linux`){let{stdout:e}=await $c(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:el(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(X.platform===`win32`)return Qc();throw Error(`Only macOS, Linux, and Windows are supported`)}const nl=_e(Ke.execFile),rl=ze.dirname(he(import.meta.url)),il=ze.join(rl,`xdg-open`),{platform:al,arch:ol}=X;async function sl(){let e=await Hc(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=V.from(t,`utf16le`).toString(`base64`),{stdout:r}=await nl(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const cl=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ll=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return cl(e.app,t=>ll({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return cl(t,t=>ll({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=zc?await sl():await tl();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ll({...e,app:{name:pl[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(al===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(al===`win32`||zc&&!Lc()&&!t){r=await Hc(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),zc||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=V.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!rl||rl===`/`,t=!1;try{await Je.access(il,Ye.X_OK),t=!0}catch{}r=X.versions.electron??(al===`android`||e||!t)?`xdg-open`:il}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}al===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ke.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},ul=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ll({...t,target:e})};function dl(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ol]:t}=e;if(!t)throw Error(`${ol} is not supported`);return t}function fl({[al]:e},{wsl:t}){if(t&&zc)return dl(t);if(!e)throw Error(`${al} is not supported`);return dl(e)}const pl={};Uc(pl,`chrome`,()=>fl({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Uc(pl,`brave`,()=>fl({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Uc(pl,`firefox`,()=>fl({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Uc(pl,`edge`,()=>fl({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Uc(pl,`browser`,()=>`browser`),Uc(pl,`browserPrivate`,()=>`browserPrivate`);var ml=ul;async function hl(e,t=void 0){try{(await ml(e)).once(`error`,n=>{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(ac.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}nc();function gl(e){let t=e||yl();if(ue(t)){let e=fe(t,`utf8`);return JSON.parse(e).token}}function _l(e,t){let n=t||yl();ue(Be(n))||de(Be(n),{recursive:!0}),me(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function vl(e){let t=e||yl();ue(t)&&pe(t)}function yl(){let e=qs(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Ve(e[0],`auth.json`)}function bl(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=q(),[s,c]=q(()=>gl(i)),[l,u]=q(),d=Le(n),f=Le(r);K(()=>{d.current=n,f.current=r},[n,r]);let p=G(async()=>{u(void 0);try{let e=gl(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ks({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=G(async()=>{u(void 0);try{let e=new ks,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();_l(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=G(()=>{vl(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return K(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function xl(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=Ie(()=>oe(t),[t]),[o,s]=q(void 0),[c,l]=q(void 0),[u,d]=q(`building`),f=Le(n),p=Le(r),m=Le(i);return K(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),K(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),Ie(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function Sl(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Cl(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const wl=/^\.+(\\|\/)|^\.+$/,Tl=/[. ]+$/,El=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Dl=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ol=e=>e===``,kl=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Al=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let jl;function Ml(){return jl??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),jl}function Nl(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Sl().test(n)||[...n].some(e=>Dl.test(e)&&!Ol(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Al,` `),n.length>0&&(e=e.replaceAll(kl,`$1`)),e=e.replace(Tl,``),e=e.replace(wl,n),e=e.replace(Sl(),n),e=e.replaceAll(El,e=>Ol(e)?e:n),e.length===0&&(e=n),e=Cl().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Pl(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Pl(n,a)+i}}return e}function Pl(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Ml().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Fl(e){return`${e}.lock`}function Il(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ll(e,t={}){let n=Fl(e),r=process.pid.toString();try{return H.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(H.readFileSync(n,`utf8`),10)}catch{return H.unlinkSync(n),Ll(e,{...t,stale:0})}if(!Il(i))try{return H.unlinkSync(n),Ll(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Ll(e,{...t,stale:0});throw n}return!1}}async function Rl(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Re.resolve(e),i=0;for(;i<=n.retries;){if(Ll(r,n))return()=>zl(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function zl(e){let t=Re.resolve(e),n=Fl(t);try{if(parseInt(H.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}H.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Bl(e){let t=Re.resolve(e),n=Fl(t);try{if(!H.existsSync(n))return{locked:!1};let e=H.readFileSync(n,`utf8`),t=parseInt(e,10);return Il(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Vl=e=>{H.mkdirSync(e,{recursive:!0})},Hl=e=>{try{H.fdatasyncSync(e)}catch{}try{H.closeSync(e)}catch{}},Ul=e=>{try{let t=H.openSync(e,`r`);try{H.fsyncSync(t)}finally{H.closeSync(t)}}catch{}},Wl=(e,t)=>{let n=Re.dirname(e);Vl(n);let r=Re.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=H.openSync(r,`w`),H.writeFileSync(i,t,`utf-8`),Hl(i),i=void 0,H.renameSync(r,e),Ul(e),Ul(n)}catch(e){if(i!==void 0)try{H.closeSync(i)}catch{}try{H.rmSync(r,{force:!0})}catch{}throw e}},Gl=(e,t)=>{let n=new Map,r,i=e=>{if(H.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(e,`utf-8`))},a=(e,t)=>{Wl(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Re.join(e,`index.json`);Vl(e),H.existsSync(t)||H.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Rl(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Re.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Re.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Re.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Re.join(e,n);if(H.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(H.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Nl(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Re.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!H.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Re.join(e,i),a=H.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Bl(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Nl(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Re.join(e,t);Vl(e),H.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Bl(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Rl(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Re.join(e,n);try{H.rmSync(i,{force:!0}),Ul(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Kl=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Re.join(e,`index.json`),u=()=>{try{if(!H.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=H.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Re.join(e,n);try{let e=H.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Bl(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(H.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{H.mkdirSync(e,{recursive:!0})}catch{}a=H.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function ql({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Jl}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=Ae({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Jl=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ke);return n.length===0||n.some(e=>ee(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Yl=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Xl(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Zl=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Gl(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Kl(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Xl(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!ke(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await ql({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Ql(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=Le(null),[s,c]=q({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});K(()=>{o.current&&o.current.dispose();let e=new Zl({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),K(()=>{o.current&&o.current.setAgent(n)},[n]);let l=G(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=G(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=G(()=>{o.current&&o.current.stopStreaming()},[]),f=G(async()=>{o.current&&await o.current.resetChat()},[]),p=G(()=>{o.current&&o.current.clearQueue()},[]),m=G(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=G(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function $l(e){return Se(e,`.blink`,`devhook.txt`)}function eu(e){return Ce($l(e))}function tu(e){let t=$l(e);if(Ce(t))return Te(t,`utf-8`).trim()}function nu(e){let t=$l(e);if(we(xe(t),{recursive:!0}),Ce(t))return Te(t,`utf-8`);let n=crypto.randomUUID();return De(t,n),n}const ru=(e,t)=>e.json({error:t},400),iu=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},au=()=>new d,ou=au().get(`/:key`,async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,ie(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?ru(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:ru(t,`Value must be a string`):ru(t,`Value is required`)}),async e=>{let{key:t,err:n}=iu(e);if(n)return ru(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=iu(e);return n?ru(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),su=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},cu=ie(`param`,e=>({id:e.id})),lu=au().post(`/:key`,async e=>{let{key:t,err:n}=su(e);return n?ru(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,cu,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,ie(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):ru(e,`ID is required`)}).delete(`/:id/messages`,cu,ie(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,cu,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),uu=au().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),du=new d().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,ou).route(`/chat`,lu).route(`/otlp`,uu);var fu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function pu(e){return typeof e==`string`&&fu.test(e)}var mu=pu;function hu(e){if(!mu(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var gu=hu;const _u=[];for(let e=0;e<256;++e)_u.push((e+256).toString(16).slice(1));function vu(e,t=0){return(_u[e[t+0]]+_u[e[t+1]]+_u[e[t+2]]+_u[e[t+3]]+`-`+_u[e[t+4]]+_u[e[t+5]]+`-`+_u[e[t+6]]+_u[e[t+7]]+`-`+_u[e[t+8]]+_u[e[t+9]]+`-`+_u[e[t+10]]+_u[e[t+11]]+_u[e[t+12]]+_u[e[t+13]]+_u[e[t+14]]+_u[e[t+15]]).toLowerCase()}function yu(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function bu(e,t,n,r,i,a){let o=typeof n==`string`?yu(n):n,s=typeof r==`string`?gu(r):r;if(typeof r==`string`&&(r=gu(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return vu(c)}function xu(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ye(`sha1`).update(e).digest()}var Su=xu;function Cu(e,t,n,r){return bu(80,Su,e,t,n,r)}Cu.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Cu.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var wu=Cu;function Tu(e){let t=Ve(e.dataDirectory,`chats`),n={},r=Ve(e.dataDirectory,`storage.json`);H.existsSync(r)&&(n=JSON.parse(H.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Zl({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=wu(JSON.stringify(e),wu.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Yl(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],H.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=be(O(e=>du.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Gl(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Eu({agent:e,capabilities:t,messages:n}){let[r,i]=q(void 0),[a,o]=q(!0),[s,c]=q(void 0),l=Le(s);K(()=>{l.current=s},[s]);let[u,d]=q(()=>M(n));K(()=>{d(e=>{let t=M(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=q(void 0),m=G((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=G(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);K(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=Le(void 0),_=Le(void 0);K(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),K(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=G((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}var Du=o(nc());function Ou(e){let t=Le(e.onRequest);K(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=q(`disconnected`);return K(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Ve(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Rl(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Bl(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Du.default.red(`\nError: Another ${Du.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Du.default.red(`Please stop the other process and try again.
|
|
54
|
-
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(
|
|
48
|
+
${Tf}`),t.includes(`
|
|
49
|
+
`)&&(n=3+oe(t.slice(t.lastIndexOf(`
|
|
50
|
+
`))).length);let e=oe(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
51
|
+
${Tf}${t.trimStart()}`),n=3+oe(t.trimStart()).length)}process.stdout.write(`
|
|
52
|
+
`)},info:e=>Ef.message(e,{symbol:mf.default.blue(bf)}),success:e=>Ef.message(e,{symbol:mf.default.green(xf)}),step:e=>Ef.message(e,{symbol:mf.default.green(vf)}),warn:e=>Ef.message(e,{symbol:mf.default.yellow(Sf)}),warning:e=>Ef.warn(e),error:e=>Ef.message(e,{symbol:mf.default.red(Cf)})};let Df;function Of(){try{return ne.statSync(`/.dockerenv`),!0}catch{return!1}}function kf(){try{return ne.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Af(){return Df===void 0&&(Df=Of()||kf()),Df}let jf;const Mf=()=>{try{return ne.statSync(`/run/.containerenv`),!0}catch{return!1}};function Nf(){return jf===void 0&&(jf=Mf()||Af()),jf}const Pf=()=>{if(J.platform!==`linux`)return!1;if(je.release().toLowerCase().includes(`microsoft`))return!Nf();try{return ne.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Nf():!1}catch{return!1}};var Ff=J.env.__IS_WSL_TEST__?Pf:Pf();const If=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Le.access(n,Re.F_OK),r=!0}catch{}if(!r)return e;let i=await Le.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Lf=async()=>`${await If()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Rf=async()=>Ff?Lf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function zf(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Bf=ae(Ie);async function Vf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Bf(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const Hf=ae(Ie);async function Uf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Hf(`osascript`,[`-e`,e,r],i);return a.trim()}async function Wf(e){return Uf(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Gf=ae(Ie),Kf={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var qf=class extends Error{};async function Jf(e=Gf){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new qf(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Kf[r];if(!i)throw new qf(`Unknown browser ID: ${r}`);return i}const Yf=ae(Ie),Xf=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Zf(){if(J.platform===`darwin`){let e=await Vf();return{name:await Wf(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await Yf(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:Xf(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return Jf();throw Error(`Only macOS, Linux, and Windows are supported`)}const Qf=ae(Fe.execFile),$f=Ee.dirname(ie(import.meta.url)),ep=Ee.join($f,`xdg-open`),{platform:tp,arch:np}=J;async function rp(){let e=await Rf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Qf(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const ip=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ap=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return ip(e.app,t=>ap({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return ip(t,t=>ap({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Ff?await rp():await Zf();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ap({...e,app:{name:lp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(tp===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(tp===`win32`||Ff&&!Nf()&&!t){r=await Rf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ff||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!$f||$f===`/`,t=!1;try{await Le.access(ep,Re.X_OK),t=!0}catch{}r=J.versions.electron??(tp===`android`||e||!t)?`xdg-open`:ep}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}tp===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Fe.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},op=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ap({...t,target:e})};function sp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[np]:t}=e;if(!t)throw Error(`${np} is not supported`);return t}function cp({[tp]:e},{wsl:t}){if(t&&Ff)return sp(t);if(!e)throw Error(`${tp} is not supported`);return sp(e)}const lp={};zf(lp,`chrome`,()=>cp({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),zf(lp,`brave`,()=>cp({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),zf(lp,`firefox`,()=>cp({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),zf(lp,`edge`,()=>cp({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),zf(lp,`browser`,()=>`browser`),zf(lp,`browserPrivate`,()=>`browserPrivate`);var up=op;async function dp(e,t=void 0){try{(await up(e)).once(`error`,n=>{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Zd.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function fp(e){let t=e||hp();if(F(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function pp(e,t){let n=t||hp();F(De(n))||I(De(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function mp(e){let t=e||hp();F(t)&&re(t)}function hp(){let e=vd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return Oe(e[0],`auth.json`)}function gp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>fp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=fp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ed({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=H(async()=>{u(void 0);try{let e=new ed,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();pp(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=H(()=>{mp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function _p(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=we(()=>A(t),[t]),[o,s]=G(void 0),[c,l]=G(void 0),[u,d]=G(`building`),f=W(n),p=W(r),m=W(i);return U(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),U(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),we(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function vp(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function yp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const bp=/^\.+(\\|\/)|^\.+$/,xp=/[. ]+$/,Sp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Cp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,wp=e=>e===``,Tp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Ep=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Dp;function Op(){return Dp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Dp}function kp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(vp().test(n)||[...n].some(e=>Cp.test(e)&&!wp(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Ep,` `),n.length>0&&(e=e.replaceAll(Tp,`$1`)),e=e.replace(xp,``),e=e.replace(bp,n),e=e.replace(vp(),n),e=e.replaceAll(Sp,e=>wp(e)?e:n),e.length===0&&(e=n),e=yp().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Ap(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Ap(n,a)+i}}return e}function Ap(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Op().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function jp(e){return`${e}.lock`}function Mp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Np(e,t={}){let n=jp(e),r=process.pid.toString();try{return P.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Np(e,{...t,stale:0})}if(!Mp(i))try{return P.unlinkSync(n),Np(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Np(e,{...t,stale:0});throw n}return!1}}async function Pp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Te.resolve(e),i=0;for(;i<=n.retries;){if(Np(r,n))return()=>Fp(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Fp(e){let t=Te.resolve(e),n=jp(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ip(e){let t=Te.resolve(e),n=jp(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Mp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Lp=e=>{P.mkdirSync(e,{recursive:!0})},Rp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Bp=(e,t)=>{let n=Te.dirname(e);Lp(n);let r=Te.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Rp(i),i=void 0,P.renameSync(r,e),zp(e),zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},Vp=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Bp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Te.join(e,`index.json`);Lp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Pp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Te.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Te.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Te.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Te.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=kp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Te.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Te.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Ip(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=kp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Te.join(e,t);Lp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Ip(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Pp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Te.join(e,n);try{P.rmSync(i,{force:!0}),zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Hp=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Te.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Te.join(e,n);try{let e=P.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Ip(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{P.mkdirSync(e,{recursive:!0})}catch{}a=P.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function Up({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Wp}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=ve({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Wp=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},Gp=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Kp(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var qp=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Vp(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Hp(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Kp(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!_e(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Up({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Jp(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=W(null),[c,l]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});U(()=>{s.current&&s.current.dispose();let e=new qp({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),U(()=>{s.current&&s.current.setAgent(n)},[n]);let u=H(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=H(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=H(()=>{s.current&&s.current.stopStreaming()},[]),p=H(async()=>{s.current&&await s.current.resetChat()},[]),m=H(()=>{s.current&&s.current.clearQueue()},[]),h=H(async e=>{s.current&&await s.current.deleteMessages([e])},[]),g=H(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,stopStreaming:f,resetChat:p,clearQueue:m,deleteMessage:h,start:g}}function Yp(e){return ue(e,`.blink`,`devhook.txt`)}function Xp(e){return de(Yp(e))}function Zp(e){let t=Yp(e);if(de(t))return pe(t,`utf-8`).trim()}function Qp(e){let t=Yp(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const $p=(e,t)=>e.json({error:t},400),em=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},tm=()=>new f,nm=tm().get(`/:key`,async e=>{let{key:t,err:n}=em(e);if(n)return $p(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?$p(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:$p(t,`Value must be a string`):$p(t,`Value is required`)}),async e=>{let{key:t,err:n}=em(e);if(n)return $p(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=em(e);return n?$p(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),rm=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},im=k(`param`,e=>({id:e.id})),am=tm().post(`/:key`,async e=>{let{key:t,err:n}=rm(e);return n?$p(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,im,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):$p(e,`ID is required`)}).delete(`/:id/messages`,im,k(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,im,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),om=tm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),sm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,nm).route(`/chat`,am).route(`/otlp`,om);var cm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function lm(e){return typeof e==`string`&&cm.test(e)}var um=lm;function dm(e){if(!um(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var fm=dm;const pm=[];for(let e=0;e<256;++e)pm.push((e+256).toString(16).slice(1));function mm(e,t=0){return(pm[e[t+0]]+pm[e[t+1]]+pm[e[t+2]]+pm[e[t+3]]+`-`+pm[e[t+4]]+pm[e[t+5]]+`-`+pm[e[t+6]]+pm[e[t+7]]+`-`+pm[e[t+8]]+pm[e[t+9]]+`-`+pm[e[t+10]]+pm[e[t+11]]+pm[e[t+12]]+pm[e[t+13]]+pm[e[t+14]]+pm[e[t+15]]).toLowerCase()}function hm(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}function gm(e,t,n,r,i,a){let o=typeof n==`string`?hm(n):n,s=typeof r==`string`?fm(r):r;if(typeof r==`string`&&(r=fm(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return mm(c)}function _m(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var vm=_m;function ym(e,t,n,r){return gm(80,vm,e,t,n,r)}ym.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,ym.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var bm=ym;function xm(e){let t=Oe(e.dataDirectory,`chats`),n={},r=Oe(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new qp({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=bm(JSON.stringify(e),bm.URL),n=a(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>Gp(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=le(w(e=>sm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=Vp(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Sm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Cm(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=Oe(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Pp(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ip(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Zd.red(`\nError: Another ${Zd.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Zd.red(`Please stop the other process and try again.
|
|
53
|
+
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(Zd.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(Zd.yellow(`Continuing without lock. Multiple ${Zd.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new ed({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var wm=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Tm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=wm().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
55
54
|
`);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
56
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function ju(e,t){let n=e;for(;n!==xe(n);){let e=Se(n,t);try{return await Ne(e),e}catch{}n=xe(n)}}function Mu(e,t=`.env.local`){let[n,r]=q({});return K(()=>{let n,i=e=>{try{let t=Te(e,`utf-8`),n=(0,Au.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return ju(e,t).then(e=>{if(!e){r({});return}i(e),n=Ee(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Nu=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Nu{};function Pu(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Fu(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Iu(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Lu(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Ru(e,t){return Iu(e,t,``)}function zu(e,t){return Lu(e,t,``)}function Bu(e,t){return t.slice(0,Vu(e,t))}function Vu(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Hu(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Uu(e){let t=e.match(/^\s*/);return t?t[0]:``}const Wu=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Gu=RegExp(`[${Wu}]+|\\s+|[^${Wu}]`,`ug`);new class extends Nu{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Gu)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Ku(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Ku(n,i,r,null),e}};function Ku(e,t,n,r){if(t&&n){let i=Uu(t.value),a=Hu(t.value),o=Uu(n.value),s=Hu(n.value);if(e){let r=Pu(i,o);e.value=Lu(e.value,o,r),t.value=Ru(t.value,r),n.value=Ru(n.value,r)}if(r){let e=Fu(a,s);r.value=Iu(r.value,s,e),t.value=zu(t.value,e),n.value=zu(n.value,e)}}else if(n){if(e){let e=Uu(n.value);n.value=n.value.substring(e.length)}if(r){let e=Uu(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Uu(r.value),i=Uu(t.value),a=Hu(t.value),o=Pu(n,i);t.value=Ru(t.value,o);let s=Fu(Ru(n,o),a);t.value=zu(t.value,s),r.value=Iu(r.value,n,s),e.value=Lu(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Uu(r.value),n=Hu(t.value),i=Bu(n,e);t.value=zu(t.value,i)}else if(e){let n=Hu(e.value),r=Uu(t.value),i=Bu(n,r);t.value=Ru(t.value,i)}}new class extends Nu{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Wu}]+|[^\\S\\n\\r]+|[^${Wu}]`,`ug`);return e.match(t)||[]}};const qu=new class extends Nu{constructor(){super(...arguments),this.tokenize=Yu}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
55
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function Em(e,t){let n=e;for(;n!==B(n);){let e=ue(n,t);try{return await V(e),e}catch{}n=B(n)}}function Dm(e,t=`.env.local`){let[n,r]=G({});return U(()=>{let n,i=e=>{try{let t=pe(e,`utf-8`),n=(0,Tm.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Em(e,t).then(e=>{if(!e){r({});return}i(e),n=me(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Om=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends Om{};function km(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Am(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function jm(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Mm(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Nm(e,t){return jm(e,t,``)}function Pm(e,t){return Mm(e,t,``)}function Fm(e,t){return t.slice(0,Im(e,t))}function Im(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Lm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Rm(e){let t=e.match(/^\s*/);return t?t[0]:``}const zm=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Bm=RegExp(`[${zm}]+|\\s+|[^${zm}]`,`ug`);new class extends Om{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Bm)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Vm(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Vm(n,i,r,null),e}};function Vm(e,t,n,r){if(t&&n){let i=Rm(t.value),a=Lm(t.value),o=Rm(n.value),s=Lm(n.value);if(e){let r=km(i,o);e.value=Mm(e.value,o,r),t.value=Nm(t.value,r),n.value=Nm(n.value,r)}if(r){let e=Am(a,s);r.value=jm(r.value,s,e),t.value=Pm(t.value,e),n.value=Pm(n.value,e)}}else if(n){if(e){let e=Rm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Rm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Rm(r.value),i=Rm(t.value),a=Lm(t.value),o=km(n,i);t.value=Nm(t.value,o);let s=Am(Nm(n,o),a);t.value=Pm(t.value,s),r.value=jm(r.value,n,s),e.value=Mm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Rm(r.value),n=Lm(t.value),i=Fm(n,e);t.value=Pm(t.value,i)}else if(e){let n=Lm(e.value),r=Rm(t.value),i=Fm(n,r);t.value=Nm(t.value,i)}}new class extends Om{tokenize(e){let t=RegExp(`(\\r?\\n)|[${zm}]+|[^\\S\\n\\r]+|[^${zm}]`,`ug`);return e.match(t)||[]}};const Hm=new class extends Om{constructor(){super(...arguments),this.tokenize=Wm}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
57
56
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
58
57
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
59
58
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
60
|
-
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function
|
|
61
|
-
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function
|
|
62
|
-
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function
|
|
59
|
+
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function Um(e,t,n){return Hm.diff(e,t,n)}function Wm(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
60
|
+
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function Gm(e){return e==`.`||e==`!`||e==`?`}new class extends Om{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(Gm(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends Om{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends Om{constructor(){super(...arguments),this.tokenize=Wm}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(Km(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function Km(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=Km(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=Km(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends Om{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function qm(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;Um(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(Um(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||Jm(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
|
|
61
|
+
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function Jm(e){let t=e.endsWith(`
|
|
63
62
|
`),n=e.split(`
|
|
64
63
|
`).map(e=>e+`
|
|
65
|
-
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const
|
|
64
|
+
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const Ym={readLineLimit:2e3,readLineLengthLimit:2e3,plainOutputCharacterLimit:8192};let Xm;const Zm=e=>{let t=()=>Xm||(Xm=Promise.resolve(ze().client),Xm);return{...e({client(){return t()}}),withContext:n=>{if(n.client||=t(),typeof n.client==`function`){let t=n.client;return e({client:t})}return e({client:()=>Promise.resolve(n.client)})}}},Qm=e=>{let{ansiOutput:t,...n}=e;return{type:`json`,value:n}},$m={execute_bash:Zm(({client:e})=>({description:"Execute a bash command in a compute instance. **ALL OUTPUT IS AUTOMATICALLY CAPTURED AND STORED** - never use pipes to filter output during execution.\n\n**Process Management:**\n- Use the returned PID with `process_wait` to get complete results\n- Use `process_grep_output` to search through the FULL stored output\n- Use `process_read_output` to read any portion of the stored output\n- **NEVER use pipes like `| grep`, `| head`, `| tail`** - run commands cleanly and analyze afterward\n\n**Output Storage:**\n- Every command's complete stdout/stderr is permanently stored\n- You can search, filter, and read from this stored output multiple times\n- No information is ever lost, even from long-running processes\n\nExample workflow:\n1. `execute_bash` returns PID 123\n2. `process_wait` on PID 123 to see if it completed\n3. `process_grep_output` on PID 123 to find errors",inputSchema:q.object({command:q.string(),working_directory:q.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:q.record(q.string(),q.string()),env_file:q.string().optional().describe(`A file to read environment variables from. e.g. .env.local`)}),execute:async(t,n)=>(await e()).request(`process_execute`,{command:`bash`,args:[`-c`,t.command],cwd:t.working_directory,env:t.env,env_file:t.env_file},{signal:n.abortSignal})})),execute_bash_sync:Zm(({client:e})=>({description:`Execute a bash command and return output synchronously in a compute instance. **ALL OUTPUT IS AUTOMATICALLY CAPTURED AND STORED** - never use pipes to filter output during execution.
|
|
66
65
|
|
|
67
|
-
Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:
|
|
66
|
+
Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:q.object({command:q.string(),working_directory:q.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:q.record(q.string(),q.string()),env_file:q.string().optional().describe(`A file to read environment variables from. e.g. .env.local`)}),async*execute(t,n){let r=await(await e()).request(`process_execute`,{command:`bash`,args:[`-c`,t.command],cwd:t.working_directory,env:t.env,env_file:t.env_file},{signal:n.abortSignal});for await(let t of eh({client:await e(),pid:r.pid,abortSignal:n.abortSignal}))yield t},toModelOutput:Qm})),process_send_input:Zm(({client:e})=>({description:`Send input to a process by PID that was started by the execute_bash tool.
|
|
68
67
|
|
|
69
68
|
Use "\r
|
|
70
|
-
" to send a newline (e.g. for an interactive prompt).`,inputSchema:
|
|
69
|
+
" to send a newline (e.g. for an interactive prompt).`,inputSchema:q.object({pid:q.number(),data:q.string()}),execute:async(t,n)=>(await e()).request(`process_send_input`,{pid:t.pid,data:t.data},{signal:n.abortSignal})})),process_kill:Zm(({client:e})=>({description:`Kill a process by PID that was started by the execute_bash tool.`,inputSchema:q.object({pid:q.number(),signal:q.string()}),execute:async(t,n)=>(await e()).request(`process_kill`,{pid:t.pid,signal:t.signal},{signal:n.abortSignal})})),process_wait:Zm(({client:e})=>({description:`This tool waits for a process to exit, or returns instantly if the process already has exited.
|
|
71
70
|
|
|
72
71
|
Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
|
|
73
72
|
|
|
74
73
|
IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
|
|
75
|
-
`,inputSchema:
|
|
74
|
+
`,inputSchema:q.object({pid:q.number(),timeout_ms:q.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of eh({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:Qm})),read_file:Zm(({client:e})=>be({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
|
|
76
75
|
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
|
77
76
|
|
|
78
77
|
Usage:
|
|
79
78
|
- The path parameter can be a relative path or an absolute path
|
|
80
|
-
- By default, it reads up to ${
|
|
79
|
+
- By default, it reads up to ${Ym.readLineLimit} lines starting from the beginning of the file
|
|
81
80
|
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
|
|
82
|
-
- Any lines longer than ${
|
|
81
|
+
- Any lines longer than ${Ym.readLineLengthLimit} characters will be truncated
|
|
83
82
|
- Results are returned using cat -n format, with line numbers starting at 1
|
|
84
83
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
85
84
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
86
85
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
87
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:
|
|
86
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:q.object({file_path:q.string(),line_offset:q.number(),line_limit:q.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:Zm(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:q.object({file_path:q.string(),content:q.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:Zm(({client:e})=>be({description:`Reads a directory from the workspace filesystem.`,inputSchema:q.object({directory_path:q.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:Zm(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
88
87
|
|
|
89
88
|
Before using this tool:
|
|
90
89
|
|
|
@@ -122,7 +121,7 @@ When making edits:
|
|
|
122
121
|
If you want to create a new file, use:
|
|
123
122
|
- A new file path, including dir name if needed
|
|
124
123
|
- First edit: empty old_string and the new file's contents as new_string
|
|
125
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:
|
|
124
|
+
- Subsequent edits: normal edit operations on the created content`,inputSchema:q.object({file_path:q.string(),edits:q.array(q.object({old_string:q.string(),new_string:q.string(),expected_replacements:q.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string,r=e.new_string;if(n===r)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let i=th(a,n);if(i===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(i!==t)throw Error(`input is invalid: Found ${i} matches of the string to replace, but expected ${t}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${n}`)}for(let e of t.edits){let t=e.old_string,n=e.new_string;a=nh(a,t,n),o.push({old_string:t,new_string:n})}await r.request(`write_file`,{path:t.file_path,content:a},{signal:n.abortSignal});let s=qm(t.file_path,t.file_path,i,a);return{edits:o,file_path:t.file_path,structured_patch:s.hunks.map(e=>({old_start:e.oldStart,old_end:e.oldLines,new_start:e.newStart,new_end:e.newLines,lines:e.lines}))}}})),process_grep_output:Zm(({client:e})=>({description:`Search through the output of a running or completed process. **This is the PRIMARY tool for analyzing command output** - use this instead of piping commands to grep, tail, or re-running commands with filters.
|
|
126
125
|
|
|
127
126
|
Use this for:
|
|
128
127
|
- Finding test failures and error messages
|
|
@@ -130,13 +129,20 @@ Use this for:
|
|
|
130
129
|
- Extracting relevant information from verbose output
|
|
131
130
|
- Analyzing build or test results
|
|
132
131
|
|
|
133
|
-
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:
|
|
134
|
-
# Store local environment variables here.
|
|
132
|
+
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},eh=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const th=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},nh=(e,t,n)=>t.length===0?e:e.split(t).join(n),rh={scratch:{".env.local.hbs":`# Store local environment variables here.
|
|
135
133
|
# They will be used by blink dev for development.
|
|
136
|
-
#
|
|
137
|
-
|
|
134
|
+
{{#each envLocal}}
|
|
135
|
+
{{this.[0]}}={{this.[1]}}
|
|
136
|
+
{{/each}}
|
|
137
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
138
|
+
# OPENAI_API_KEY=
|
|
139
|
+
# ANTHROPIC_API_KEY=
|
|
140
|
+
# AI_GATEWAY_API_KEY=
|
|
141
|
+
{{/unless}}`,".env.production":`# Store production environment variables here.
|
|
138
142
|
# They will be upserted as secrets on blink deploy.
|
|
139
|
-
#
|
|
143
|
+
# OPENAI_API_KEY=
|
|
144
|
+
# ANTHROPIC_API_KEY=
|
|
145
|
+
# AI_GATEWAY_API_KEY=
|
|
140
146
|
`,".gitignore":`# dependencies
|
|
141
147
|
node_modules
|
|
142
148
|
|
|
@@ -373,13 +379,15 @@ import { openai } from "@ai-sdk/openai";
|
|
|
373
379
|
model: anthropic("claude-sonnet-4.5", {
|
|
374
380
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
375
381
|
});
|
|
376
|
-
|
|
382
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
383
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
377
384
|
\`\`\`
|
|
378
385
|
|
|
379
386
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
380
387
|
|
|
381
388
|
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
382
389
|
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
390
|
+
3. If \`AI_GATEWAY_API_KEY\` is set: uses \`anthropic/claude-sonnet-4-5\` via the Vercel AI Gateway
|
|
383
391
|
|
|
384
392
|
Available SDKs:
|
|
385
393
|
|
|
@@ -582,12 +590,7 @@ agent.on("chat", async ({ messages }) => {
|
|
|
582
590
|
{{#if (eq aiProvider "anthropic")}}
|
|
583
591
|
model: anthropic("claude-sonnet-4-5"),
|
|
584
592
|
{{else if (eq aiProvider "openai")}}
|
|
585
|
-
model: openai("gpt-5
|
|
586
|
-
providerOptions: {
|
|
587
|
-
openai: {
|
|
588
|
-
reasoningSummary: "detailed",
|
|
589
|
-
},
|
|
590
|
-
},
|
|
593
|
+
model: openai.chat("gpt-5"),
|
|
591
594
|
{{else if (eq aiProvider "vercel")}}
|
|
592
595
|
model: "anthropic/claude-sonnet-4.5",
|
|
593
596
|
{{else}}
|
|
@@ -661,15 +664,25 @@ agent.serve();
|
|
|
661
664
|
"types": ["node"]
|
|
662
665
|
}
|
|
663
666
|
}
|
|
664
|
-
`},"slack-bot":{".env.local"
|
|
665
|
-
# Store local environment variables here.
|
|
667
|
+
`},"slack-bot":{".env.local.hbs":`# Store local environment variables here.
|
|
666
668
|
# They will be used by blink dev for development.
|
|
669
|
+
{{#each envLocal}}
|
|
670
|
+
{{this.[0]}}={{this.[1]}}
|
|
671
|
+
{{/each}}
|
|
672
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
673
|
+
# OPENAI_API_KEY=
|
|
674
|
+
# ANTHROPIC_API_KEY=
|
|
675
|
+
# AI_GATEWAY_API_KEY=
|
|
676
|
+
{{/unless}}
|
|
667
677
|
SLACK_BOT_TOKEN=xoxb-your-token-here
|
|
668
678
|
SLACK_SIGNING_SECRET=your-signing-secret-here
|
|
669
679
|
`,".env.production":`# Store production environment variables here.
|
|
670
680
|
# They will be upserted as secrets on blink deploy.
|
|
671
|
-
#
|
|
672
|
-
|
|
681
|
+
# SLACK_BOT_TOKEN=
|
|
682
|
+
# SLACK_SIGNING_SECRET=
|
|
683
|
+
# OPENAI_API_KEY=
|
|
684
|
+
# ANTHROPIC_API_KEY=
|
|
685
|
+
# AI_GATEWAY_API_KEY=`,".gitignore":`# dependencies
|
|
673
686
|
node_modules
|
|
674
687
|
|
|
675
688
|
# config and build
|
|
@@ -905,7 +918,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
905
918
|
model: anthropic("claude-sonnet-4.5", {
|
|
906
919
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
907
920
|
});
|
|
908
|
-
|
|
921
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
922
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
909
923
|
\`\`\`
|
|
910
924
|
|
|
911
925
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -1190,12 +1204,7 @@ agent.on("chat", async ({ messages }) => {
|
|
|
1190
1204
|
{{#if (eq aiProvider "anthropic")}}
|
|
1191
1205
|
model: anthropic("claude-sonnet-4-5"),
|
|
1192
1206
|
{{else if (eq aiProvider "openai")}}
|
|
1193
|
-
model: openai("gpt-5
|
|
1194
|
-
providerOptions: {
|
|
1195
|
-
openai: {
|
|
1196
|
-
reasoningSummary: "detailed",
|
|
1197
|
-
},
|
|
1198
|
-
},
|
|
1207
|
+
model: openai.chat("gpt-5"),
|
|
1199
1208
|
{{else if (eq aiProvider "vercel")}}
|
|
1200
1209
|
model: "anthropic/claude-sonnet-4.5",
|
|
1201
1210
|
{{else}}
|
|
@@ -1261,7 +1270,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1261
1270
|
"types": ["node"]
|
|
1262
1271
|
}
|
|
1263
1272
|
}
|
|
1264
|
-
`}};function
|
|
1273
|
+
`}};function ih(e,t,n){let r,i=ce.createServer(w(async a=>{let o=new URL(a.url,r);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await n?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await n?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let r=t.message;return new Response(`Error: ${r}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{i.close()}let c={...e,redirect_url:r},l=`<!DOCTYPE html>
|
|
1265
1274
|
<html>
|
|
1266
1275
|
<body>
|
|
1267
1276
|
<form id="f" method="POST" action="${t?`https://github.com/organizations/${t}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
@@ -1269,7 +1278,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1269
1278
|
</form>
|
|
1270
1279
|
<script>document.getElementById('f').submit()<\/script>
|
|
1271
1280
|
</body>
|
|
1272
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const ud=Y.enum([`read`,`write`]),dd=Y.union([Y.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),Y.literal(`check_run`).describe(`Check run created, completed, or requested`),Y.literal(`check_suite`).describe(`Check suite completed or requested`),Y.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),Y.literal(`commit_comment`).describe(`Commit comment created`),Y.literal(`create`).describe(`Branch or tag created`),Y.literal(`delete`).describe(`Branch or tag deleted`),Y.literal(`deployment`).describe(`Deployment created`),Y.literal(`deployment_status`).describe(`Deployment status created`),Y.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),Y.literal(`discussion`).describe(`Discussion created, edited, or deleted`),Y.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),Y.literal(`fork`).describe(`Repository forked`),Y.literal(`gollum`).describe(`Wiki page created or updated`),Y.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),Y.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),Y.literal(`label`).describe(`Label created, edited, or deleted`),Y.literal(`member`).describe(`Collaborator added, removed, or edited`),Y.literal(`membership`).describe(`Team membership added or removed`),Y.literal(`meta`).describe(`GitHub App webhook configuration changed`),Y.literal(`milestone`).describe(`Milestone created, closed, or deleted`),Y.literal(`organization`).describe(`Organization member added, removed, or invited`),Y.literal(`org_block`).describe(`Organization blocked or unblocked a user`),Y.literal(`package`).describe(`Package published or updated`),Y.literal(`page_build`).describe(`GitHub Pages site built`),Y.literal(`project`).describe(`Project created, updated, or deleted`),Y.literal(`project_card`).describe(`Project card created, edited, or deleted`),Y.literal(`project_column`).describe(`Project column created, updated, or deleted`),Y.literal(`public`).describe(`Repository visibility changed to public`),Y.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),Y.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),Y.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),Y.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),Y.literal(`push`).describe(`Git push to a repository`),Y.literal(`registry_package`).describe(`Registry package published or updated`),Y.literal(`release`).describe(`Release published or edited`),Y.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),Y.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),Y.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),Y.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),Y.literal(`star`).describe(`Repository starred or unstarred`),Y.literal(`status`).describe(`Commit status created`),Y.literal(`team`).describe(`Team created, deleted, or edited`),Y.literal(`team_add`).describe(`Repository added to team`),Y.literal(`watch`).describe(`User started watching repository`),Y.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),Y.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),Y.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),fd=Y.object({name:Y.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:Y.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:Y.string().optional().describe(`The description of the GitHub App.`),public:Y.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:Y.object({url:Y.url(),active:Y.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:Y.array(Y.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:Y.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:Y.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:Y.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:Y.array(dd).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:Y.record(Y.string(),ud).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function pd(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const md=Y.union([Y.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),Y.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),Y.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),Y.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),Y.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),Y.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),Y.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),Y.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),Y.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),Y.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),Y.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),Y.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),Y.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),Y.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),Y.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),Y.literal(`file_created`).describe(`File was created. Requires scope: files:read`),Y.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),Y.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),Y.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),Y.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),Y.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),Y.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),Y.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),Y.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),Y.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),Y.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),Y.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),Y.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),Y.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),Y.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),Y.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),Y.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),Y.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),Y.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),Y.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),Y.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),Y.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),hd=Y.union([Y.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),Y.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),Y.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),Y.literal(`channels:join`).describe(`Join public channels`),Y.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),Y.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),Y.literal(`chat:write`).describe(`Send messages as the bot`),Y.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),Y.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),Y.literal(`commands`).describe(`Add and use slash commands`),Y.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),Y.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),Y.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),Y.literal(`files:write`).describe(`Upload, edit, and delete files`),Y.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),Y.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),Y.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),Y.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),Y.literal(`im:read`).describe(`View basic information about direct messages with the bot`),Y.literal(`im:write`).describe(`Start and manage direct messages with users`),Y.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),Y.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),Y.literal(`metadata.message:read`).describe(`Read message metadata`),Y.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),Y.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),Y.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),Y.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),Y.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),Y.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),Y.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),Y.literal(`reminders:read`).describe(`View reminders created by the bot`),Y.literal(`reminders:write`).describe(`Create, update, and delete reminders`),Y.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),Y.literal(`usergroups:read`).describe(`View user groups and their members`),Y.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),Y.literal(`users.profile:read`).describe(`View profile information about users`),Y.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),Y.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),Y.literal(`users:write`).describe(`Set presence and status for the bot user`)]),gd=Y.union([Y.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),Y.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),Y.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),Y.literal(`chat:write`).describe(`Send messages on behalf of the user`),Y.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),Y.literal(`files:read`).describe(`View files on behalf of the user`),Y.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),Y.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),Y.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),Y.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),Y.literal(`im:history`).describe(`Read direct message history on behalf of the user`),Y.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),Y.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),Y.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),Y.literal(`links:write`).describe(`Show URL previews on behalf of the user`),Y.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),Y.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),Y.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),Y.literal(`pins:read`).describe(`View pinned items on behalf of the user`),Y.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),Y.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),Y.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),Y.literal(`reminders:read`).describe(`View reminders on behalf of the user`),Y.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),Y.literal(`search:read`).describe(`Search messages and files on behalf of the user`),Y.literal(`stars:read`).describe(`View starred items on behalf of the user`),Y.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),Y.literal(`team:read`).describe(`View workspace information on behalf of the user`),Y.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),Y.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),Y.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),Y.literal(`users.profile:write`).describe(`Edit the user's profile information`),Y.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),Y.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),Y.literal(`users:write`).describe(`Set presence for the user`)]),_d=Y.object({display_information:Y.object({name:Y.string().describe(`The name of the Slack app.`),description:Y.string().optional().describe(`A short description of the app.`),background_color:Y.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:Y.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:Y.object({bot_user:Y.object({display_name:Y.string().describe(`The display name for the bot user.`),always_online:Y.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:Y.object({home_tab_enabled:Y.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:Y.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:Y.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:Y.object({assistant_description:Y.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:Y.array(Y.object({command:Y.string().regex(/^\//).describe(`The command (must start with /).`),description:Y.string().describe(`Description of the command.`),usage_hint:Y.string().optional().describe(`Usage hint for the command.`),should_escape:Y.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:Y.array(Y.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:Y.object({redirect_urls:Y.array(Y.url()).optional().describe(`OAuth redirect URLs.`),scopes:Y.object({bot:Y.array(Y.union([hd,Y.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:Y.array(Y.union([gd,Y.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:Y.object({event_subscriptions:Y.object({request_url:Y.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:Y.array(Y.union([md,Y.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:Y.object({is_enabled:Y.boolean().describe(`Enable interactivity.`),request_url:Y.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:Y.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:Y.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:Y.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:Y.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function vd(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1281
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const ah=q.enum([`read`,`write`]),oh=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),sh=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(oh).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),ah).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function ch(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const lh=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),uh=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),dh=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),fh=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([uh,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([dh,q.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([lh,q.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function ph(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1273
1282
|
|
|
1274
1283
|
The agent source code is in the directory: "${e.directory}".
|
|
1275
1284
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
@@ -1296,9 +1305,9 @@ You are *NOT* responsible for:
|
|
|
1296
1305
|
- Continuing any work the run mode agent started
|
|
1297
1306
|
|
|
1298
1307
|
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
1299
|
-
`}]});let{execute_bash:s,execute_bash_sync:c,...l}
|
|
1308
|
+
`}]});let{execute_bash:s,execute_bash_sync:c,...l}=$m,u={execute_bash:s,execute_bash_sync:c};process.env.BLINK_AUTO_APPROVE||(u=await O.withApproval({messages:i,tools:u}));let d={...l,...u,...await O.withApproval({messages:i,tools:{get_reverse_tunnel_url:be({description:`Gets or creates a reverse tunnel for the user's agent. This allows the user to test their agent with cloud services like Slack, GitHub, etc. without having to deploy it.
|
|
1300
1309
|
|
|
1301
|
-
You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:
|
|
1310
|
+
You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:q.object({}),execute:async()=>e.getDevhookUrl()}),create_github_app:be({description:`Creates a GitHub App using GitHub's app manifest flow.
|
|
1302
1311
|
|
|
1303
1312
|
IMPORTANT: You must explain to the user what's happening and why:
|
|
1304
1313
|
- Tell them this will open a localhost URL that redirects them to GitHub
|
|
@@ -1310,14 +1319,14 @@ You *must* ensure the organization is correct - ask the user prior.
|
|
|
1310
1319
|
|
|
1311
1320
|
Once they complete the app creation, environment variables will be automatically set in the provided environment file.
|
|
1312
1321
|
|
|
1313
|
-
After approval, the URL will be opened automatically in their browser.`,inputSchema:
|
|
1322
|
+
After approval, the URL will be opened automatically in their browser.`,inputSchema:q.object({manifest:sh,envFile:q.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:q.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(n,i)=>{let a=await ih(n.manifest,n.organization,async(i,a)=>{if(i){await t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${i.message}`}]}]);return}if(a){try{let t=n.envFile===`production`?`.env.production`:`.env.local`,r=ue(e.directory,t),i=``;try{i=await xe(r,`utf-8`)}catch{}let o=`
|
|
1314
1323
|
# GitHub App credentials (created with the blink edit agent)
|
|
1315
1324
|
GITHUB_APP_ID=${a.id}
|
|
1316
1325
|
GITHUB_CLIENT_ID=${a.client_id}
|
|
1317
1326
|
GITHUB_CLIENT_SECRET=${a.client_secret}
|
|
1318
1327
|
GITHUB_WEBHOOK_SECRET=${a.webhook_secret}
|
|
1319
1328
|
GITHUB_PRIVATE_KEY="${btoa(a.pem)}"
|
|
1320
|
-
`;await
|
|
1329
|
+
`;await Se(r,i+o,`utf-8`)}catch(e){await t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created but failed to write credentials to env file: ${e instanceof Error?e.message:String(e)}`}]}]);return}await t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${n.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return await dp(a),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:be({description:`Creates a Slack App with the provided manifest.
|
|
1321
1330
|
|
|
1322
1331
|
IMPORTANT - when ran, you MUST:
|
|
1323
1332
|
1. Inform the user that the URL has opened in their browser automatically to *Slack*.
|
|
@@ -1325,11 +1334,11 @@ IMPORTANT - when ran, you MUST:
|
|
|
1325
1334
|
3. Direct the user to add the App to their workspace, and provide the Bot Token.
|
|
1326
1335
|
|
|
1327
1336
|
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
|
|
1328
|
-
`,inputSchema:
|
|
1337
|
+
`,inputSchema:fh,execute:async(e,t)=>{let n=ch(e);return await dp(n),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:be({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
1329
1338
|
|
|
1330
|
-
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:
|
|
1339
|
+
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:q.object({message:q.string()}),execute:async(e,t)=>{if(!n)return`User agent URL is not available. Cannot test user agent.`;let r=await new vc({baseUrl:n}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=ve({stream:r}),a;for await(let e of i)a=e;return a}}),typecheck_agent:be({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
1331
1340
|
|
|
1332
|
-
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:
|
|
1341
|
+
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:q.object({}),execute:async()=>{let t=Ce(`node`,[ue(e.directory,`node_modules/.bin/tsc`),`--noEmit`],{stdio:`pipe`,cwd:e.directory}),n=``,r=``,i;return t.stdout.on(`data`,e=>{n+=Buffer.from(e).toString(`utf-8`)}),t.stderr.on(`data`,e=>{r+=Buffer.from(e).toString(`utf-8`)}),await new Promise(e=>{t.on(`close`,t=>{i=t??void 0,e()})}),{stdout:n,stderr:r,exitCode:i}}})},f=ge(i,{ignoreIncompleteToolCalls:!0,tools:d});f.unshift({role:`system`,content:`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
|
|
1333
1342
|
|
|
1334
1343
|
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+T. After making changes, instruct the user to switch to run mode to use their agent.
|
|
1335
1344
|
|
|
@@ -1362,4 +1371,4 @@ Slack:
|
|
|
1362
1371
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1363
1372
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1364
1373
|
</agent_development>
|
|
1365
|
-
`});let p=
|
|
1374
|
+
`});let p=rh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:hh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function mh(e){if(e.ANTHROPIC_API_KEY)return gn({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ao({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function hh(e){let t=mh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function gh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!mh(e.env)){o(!0);return}return o(!1),(async()=>{s.current=ph({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await _h(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new vc({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),we(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function _h(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function vh(e){let{directory:t}=e,[n,r]=G(),[i,a]=G(!1),[o,s]=G(`run`),c=W(`run`);U(()=>{c.current=o},[o]);let l=H(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=H(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=_p({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=gp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Dm(t),_=we(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=W(void 0);U(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=W(void 0),b=we(()=>xm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=yc({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:D,missingApiKey:O,setUserAgentUrl:k}=gh({directory:t,apiServerUrl:b.url,env:_,getDevhookUrl:H(()=>{let e=Zp(t)??Qp(t);return F(e),`https://${e}.blink.host`},[t])}),[A,j]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{y.current=x},[x]),U(()=>{x&&k(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(A)?.stopStreaming()},[x,T,o,A,b,k]);let M=W(void 0),N=Jp({chatId:A,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&M.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:M.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(Kp(e.metadata)||e.mode===`edit`),onError:t=>{e.onError?.(`${Zd.red(`⚙ [Chat Error]`)} ${Zd.gray(t)}`)}}),ee=W(0);U(()=>{if(S.length===ee.current)return;let t=ee.current;for(let n of S.slice(t))e.onAgentLog?.(n);ee.current=S.length},[S,e.onAgentLog,N.upsertMessage]);let[te,P]=G([]);U(()=>{b.listChats().then(e=>{P(e.map(e=>e.key))})},[b]),U(()=>{A&&!te.includes(A)&&P(e=>[...e,A])},[A,te]);let[ne,F]=G(()=>Xp(t)?Zp(t):Qp(t)),I=Cm({id:ne,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});U(()=>{I.status!==`connected`||!I.url||e.onDevhookConnected?.(I.url)},[I.status,I.url]);let{schema:L,options:re,error:R,setOption:ie}=Sm({agent:o===`run`?x:T,capabilities:w,messages:N.messages});U(()=>{M.current=re},[re]);let z=we(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),D&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${D.message}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,D,R,o]),ae=W(new Map);U(()=>{let t=ae.current,n=z;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[z,e.onError]);let oe=we(()=>{let e=[...N.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(_e);if(t.length!==0&&t.some(e=>E(e.output)&&e.output.outcome===`pending`))return e},[N.messages,n]),se=H(async(e,t)=>{if(!oe)return;t&&e&&a(!0),r(oe.id);let n=N.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&E(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await N.upsertMessage({...i,parts:o}),await N.start()},[oe,N]);U(()=>{i&&oe&&se(!0)},[i,oe,se]);let ce=H(()=>{let e=crypto.randomUUID();j(e),P(t=>[...t,e]),r(void 0)},[]),le=H(e=>{j(e),r(void 0)},[]),B=we(()=>{if(oe)return{message:oe,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:i}},[oe,se,i]),de=we(()=>{let e=N.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[N.messages]),fe=we(()=>{if(N.status!==`streaming`)return!1;if(!N.streamingMessage)return!0;let e=N.streamingMessage.parts.filter(_e);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[N.status,N.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:N,chats:te,switchChat:le,newChat:ce,build:{status:f,error:d,entrypoint:m},devhook:{connected:I.status===`connected`,url:I.status===`connected`?I.url:void 0},capabilities:w,options:{schema:L,selected:re,error:R,setOption:ie},approval:B,tokenUsage:de,auth:h,server:b,showWaitingPlaceholder:fe,editModeMissingApiKey:O}}export{yc as useAgent,gp as useAuth,_p as useBundler,Jp as useChat,vh as useDevMode,Cm as useDevhook,Dm as useDotenv,gh as useEditAgent,Sm as useOptions};
|