expect-cli 0.0.11 → 0.0.12

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/index.js CHANGED
@@ -1,58 +1,58 @@
1
1
  #!/usr/bin/env node
2
- import{n as e,r as t,t as n}from"./chunk-wdO_pP5q.js";import{a as r,i}from"./server-D776aGSk.js";import{createRequire as a}from"node:module";import{Array as o,Cause as s,Config as c,DateTime as l,Effect as u,Exit as d,FiberMap as f,FileSystem as p,Layer as m,Logger as h,Match as g,Option as _,Predicate as v,PubSub as y,Queue as b,References as x,Schema as S,ServiceMap as C,Stream as w,String as ee}from"effect";import{Command as T}from"commander";import{Box as E,Static as D,Text as O,render as k,useApp as A,useInput as te,useStdout as ne}from"ink";import{QueryClient as j,QueryClientProvider as M,useMutation as N,useQuery as P}from"@tanstack/react-query";import{c as re}from"react/compiler-runtime";import{createContext as ie,useCallback as ae,useContext as F,useEffect as oe,useMemo as I,useRef as L,useState as R}from"react";import*as z from"node:child_process";import{exec as B,execFile as se,execSync as ce,spawnSync as V}from"node:child_process";import{Fragment as le,jsx as H,jsxs as U}from"react/jsx-runtime";import W from"figures";import G from"picocolors";import*as K from"node:path";import ue,{join as de,normalize as fe}from"node:path";import*as pe from"node:url";import{fileURLToPath as me,pathToFileURL as he}from"node:url";import{z as ge}from"zod";import{z as q}from"zod/v4";import{ChildProcess as _e,ChildProcessSpawner as ve}from"effect/unstable/process";import*as ye from"@effect/platform-node/NodeServices";import*as be from"effect/Array";import*as xe from"effect/String";import*as Se from"effect/Function";import*as Ce from"node:crypto";import{createHash as we}from"node:crypto";import{Buffer as Te}from"node:buffer";import{execSync as Ee,spawn as De}from"child_process";import{EventEmitter as Oe}from"node:events";import{FileSystem as ke}from"effect/FileSystem";import*as Ae from"node:os";import{platform as je}from"node:os";import*as Me from"@effect/platform-node/NodeHttpClient";import*as Ne from"@effect/platform-node/NodeSocket";import{ChildProcessSpawner as Pe}from"effect/unstable/process/ChildProcessSpawner";import{request as Fe}from"node:http";import*as Ie from"node:fs/promises";import Le from"ink-spinner";import Re from"cli-truncate";import ze from"string-width";import{create as Be}from"zustand";import*as Ve from"effect/Data";import*as He from"@effect/platform-node/NodeFileSystem";import{dirname as Ue,posix as We,sep as Ge}from"path";import*as Ke from"node:fs";import{createReadStream as qe}from"node:fs";import{createInterface as Je}from"node:readline";import{AsyncLocalStorage as Ye}from"node:async_hooks";import{DevTools as Xe}from"effect/unstable/devtools";import*as Ze from"effect/unstable/observability/Otlp";import{createJSONStorage as Qe,persist as $e}from"zustand/middleware";import*as et from"effect/unstable/reactivity/AsyncResult";import*as tt from"effect/unstable/reactivity/Atom";import{RegistryProvider as nt,useAtom as rt,useAtomSet as it,useAtomValue as at}from"@effect/atom-react";import ot from"pretty-ms";import{detectTerminal as st}from"detect-terminal";import ct from"supports-terminal-graphics";import lt from"ink-link";import{Hono as ut}from"hono";import{proxy as dt}from"hono/proxy";import{serve as ft}from"@hono/node-server";import"node-notifier";import pt from"prompts";import mt from"ora";const ht=`0.0.11`,gt=`\x1B[?1049l`,_t=process.env.SUPPORT_CLICK===`true`||process.env.SUPPORT_CLICK===`1`,vt=[`lint`,`check`,`format`,`typecheck`,`type-check`],yt=`expect-cli`,bt={"pnpm-lock.yaml":`pnpm`,"pnpm-workspace.yaml":`pnpm`,"yarn.lock":`yarn`,"package-lock.json":`npm`,"npm-shrinkwrap.json":`npm`,"bun.lock":`bun`,"bun.lockb":`bun`,"deno.lock":`deno`},xt=()=>{},St=ie({subscribeClick:()=>xt}),Ct=/\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[[\d;?<>=]*[A-Za-z~]|\[<[\d;]+[Mm]|\[\d+;\d+R|\[\?[\d;]+[a-z]/g,wt=({children:e})=>{if(!_t)return H(le,{children:e});let t=L(new Set),n=L(!1);if(!n.current){n.current=!0,process.stdout.write(`\x1B[?1003l\x1B[?1002l\x1B[?1000h\x1B[?1006h`);let e=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(n,...r){if(n===`data`){let i=(typeof r[0]==`string`?r[0]:String(r[0])).replace(Ct,(e,n,r,i,a)=>{if(n===`0`)for(let e of t.current)e({x:Number(r),y:Number(i)},a===`M`?`press`:`release`);return``});return i.length===0?!0:e(n,i)}return e(n,...r)}}let r=ae(e=>(t.current.add(e),()=>{t.current.delete(e)}),[]);return H(St.Provider,{value:{subscribeClick:r},children:e})},Tt=()=>{let e=re(1);if(e[0]!==`35703fbc37b9d963e330527161df9fe36b70875a77771f1d737994ab88cecbb3`){for(let t=0;t<1;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`35703fbc37b9d963e330527161df9fe36b70875a77771f1d737994ab88cecbb3`}return F(St)},Et=/\x1b\[[\d;?<>=]*[A-Za-z~]|\[<[\d;]+[Mm]|\[\?[\d;]+[a-z]|\[\d+;\d+R/g,Dt=e=>_t?e.replace(Et,``):e,Ot=e=>e&&e>0?e:80,kt=e=>e&&e>0?e:24,At=()=>{let{stdout:e}=ne(),[t,n]=R([Ot(e.columns),kt(e.rows)]),r=L(!1);return r.current||(r.current=!0,e.on(`resize`,()=>n([Ot(e.columns),kt(e.rows)]))),t},jt=`NO_COLOR`in process.env,J={primary:jt?``:`whiteBright`,secondary:jt?``:`gray`,accent:jt?``:`white`,error:jt?``:`red`,warning:jt?``:`yellow`,success:jt?``:`green`,info:jt?``:`gray`,text:jt?``:`white`,textMuted:jt?``:`gray`,border:jt?``:`gray`,borderActive:jt?``:`white`,borderSubtle:jt?``:`blackBright`,shimmerBase:jt?``:`#555555`,shimmerHighlight:jt?``:`#ffffff`,inputBg:jt?``:`#1e1e1e`,bannerBg:jt?``:`#332b00`,errorBg:jt?``:`#330b0b`},Mt={TEXT:J.text,DIM:J.textMuted,GREEN:J.success,PRIMARY:J.primary,SELECTION:J.accent,RED:J.error,BORDER:J.border,DIVIDER:J.borderSubtle,YELLOW:J.warning,PURPLE:J.secondary,CYAN:J.info,INPUT_BG:J.inputBg,BANNER_BG:J.bannerBg,ERROR_BG:J.errorBg},Nt=()=>Mt,Pt=e=>{let t=re(21);if(t[0]!==`c91257771a99332d5805ee6c49b36d74b00fa9357a1ef3353879ee4c78179ae7`){for(let e=0;e<21;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`c91257771a99332d5805ee6c49b36d74b00fa9357a1ef3353879ee4c78179ae7`}let{color:n,children:r,marginTop:i,marginBottom:a,paddingX:o,ref:s}=e,c=o===void 0?1:o,[l]=At(),u;t[1]===l?u=t[2]:(u=`─`.repeat(l),t[1]=l,t[2]=u);let d;t[3]!==n||t[4]!==u?(d=H(O,{color:n,wrap:`truncate`,children:u}),t[3]=n,t[4]=u,t[5]=d):d=t[5];let f;t[6]!==r||t[7]!==c?(f=H(E,{flexDirection:`column`,paddingX:c,children:r}),t[6]=r,t[7]=c,t[8]=f):f=t[8];let p;t[9]===l?p=t[10]:(p=`─`.repeat(l),t[9]=l,t[10]=p);let m;t[11]!==n||t[12]!==p?(m=H(O,{color:n,wrap:`truncate`,children:p}),t[11]=n,t[12]=p,t[13]=m):m=t[13];let h;return t[14]!==a||t[15]!==i||t[16]!==s||t[17]!==d||t[18]!==f||t[19]!==m?(h=U(E,{flexDirection:`column`,width:`100%`,marginTop:i,marginBottom:a,ref:s,children:[d,f,m]}),t[14]=a,t[15]=i,t[16]=s,t[17]=d,t[18]=f,t[19]=m,t[20]=h):h=t[20],h},Ft=e=>{let t=e,n=1,r=1;for(;t;){if(!t.yogaNode)return{left:n,top:r};let e=t.yogaNode.getComputedLayout();n+=e.left,r+=e.top,t=t.parentNode}return{left:n,top:r}},It=({onClick:e,children:t,fullWidth:n=!0})=>{let{subscribeClick:r}=Tt(),i=L(e);return i.current=e,H(E,{ref:ae(e=>{if(e)return r((t,n)=>{if(n!==`press`||!e.yogaNode)return;let r=Ft(e),a=e.yogaNode.getComputedLayout(),o=t.x<r.left||t.x>=r.left+a.width,s=t.y<r.top||t.y>=r.top+a.height;!o&&!s&&i.current?.()})},[r]),width:n?`100%`:void 0,children:t})},Lt=e=>/\w/.test(e),Rt=(e,t)=>{let n=t-1;for(;n>0&&!Lt(e[n]);)n--;for(;n>0&&Lt(e[n-1]);)n--;return n},zt=(e,t)=>{let n=t;for(;n<e.length&&Lt(e[n]);)n++;for(;n<e.length&&!Lt(e[n]);)n++;return n},Bt=(e,t)=>{let n=e.split(`
3
- `),r=0;for(let e=0;e<n.length;e++){let i=n[e].length;if(t<=r+i)return{lineIndex:e,column:t-r,lines:n};r+=i+1}let i=n.length-1;return{lineIndex:i,column:n[i].length,lines:n}},Vt=(e,t,n)=>{let r=0;for(let n=0;n<t;n++)r+=e[n].length+1;return r+Math.min(n,e[t].length)},Ht=({value:e,placeholder:t=``,focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:a=!0,multiline:o=!1,onChange:s,onSubmit:c,onUpArrowAtTop:l,onDownArrowAtBottom:u})=>{let[d,f]=R({cursorOffset:(e||``).length,cursorWidth:0}),{cursorOffset:p,cursorWidth:m}=d,h=L({originalValue:e,focus:n,showCursor:a});(h.current.originalValue!==e||h.current.focus!==n||h.current.showCursor!==a)&&(h.current={originalValue:e,focus:n,showCursor:a},f(t=>{if(!n||!a)return t;let r=e||``;return t.cursorOffset>r.length-1?{cursorOffset:r.length,cursorWidth:0}:t}));let g=i?m:0,_=r?r.repeat(e.length):e,v=_,y=t?G.gray(t):void 0;if(a&&n){y=t.length>0?G.inverse(t[0])+G.gray(t.slice(1)):G.inverse(` `),v=_.length>0?``:G.inverse(` `);let e=0;for(let t of _){let n=e>=p-g&&e<=p;n&&t===`
4
- `?v+=G.inverse(` `)+`
5
- `:v+=n?G.inverse(t):t,e++}_.length>0&&p===_.length&&(v+=G.inverse(` `))}return te((t,n)=>{if(!o&&(n.upArrow||n.downArrow)||n.ctrl&&t===`c`||n.tab||n.shift&&n.tab)return;let r=p,i=e,d=0,m=!1;if(o&&n.upArrow&&a){let{lineIndex:t,column:n,lines:i}=Bt(e,p);t>0?r=Vt(i,t-1,n):l?.(),m=!0}else if(o&&n.downArrow&&a){let{lineIndex:t,column:n,lines:i}=Bt(e,p);t<i.length-1?r=Vt(i,t+1,n):u?.(),m=!0}else if(n.ctrl&&t===`a`&&a)r=0,m=!0;else if(n.ctrl&&t===`e`&&a)r=e.length,m=!0;else if(n.ctrl&&t===`f`&&a)r=p+1,m=!0;else if(n.ctrl&&t===`b`&&a)r=p-1,m=!0;else if(n.ctrl&&t===`k`)i=e.slice(0,p),m=!0;else if(n.ctrl&&t===`u`)p>0&&(i=e.slice(p),r=0),m=!0;else if(n.ctrl&&t===`w`){if(p>0){let t=Rt(e,p);i=e.slice(0,t)+e.slice(p),r=t}m=!0}else if(n.ctrl&&t===`d`)p<e.length&&(i=e.slice(0,p)+e.slice(p+1)),m=!0;else if(n.ctrl&&t===`t`)p>0&&p<e.length&&(i=e.slice(0,p-1)+e[p]+e[p-1]+e.slice(p+1),r=p+1),m=!0;else if(n.meta&&t===`b`&&a)r=Rt(e,p),m=!0;else if(n.meta&&t===`f`&&a)r=zt(e,p),m=!0;else if(n.meta&&(n.backspace||n.delete)){if(p>0){let t=Rt(e,p);i=e.slice(0,t)+e.slice(p),r=t}m=!0}else if(n.meta)return;if(!m)if(n.return)if(o&&n.shift)i=e.slice(0,p)+`
6
- `+e.slice(p),r++;else{c&&c(e);return}else n.leftArrow?a&&r--:n.rightArrow?a&&r++:n.backspace||n.delete?p>0&&(i=e.slice(0,p-1)+e.slice(p,e.length),r--):(i=e.slice(0,p)+t+e.slice(p,e.length),r+=t.length,t.length>1&&(d=t.length));r<0&&(r=0),r>i.length&&(r=i.length),f({cursorOffset:r,cursorWidth:d}),i!==e&&s(i)},{isActive:n}),H(O,{children:t?_.length>0?v:y:v})},Ut=e=>{let t=re(13);if(t[0]!==`ed5db14495474995e96712c30462d38da6b6aa36bffcbec475f62d8824e8125d`){for(let e=0;e<13;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`ed5db14495474995e96712c30462d38da6b6aa36bffcbec475f62d8824e8125d`}let{isSearching:n,query:r,onChange:i,onSubmit:a}=e,o=Nt();if(n){let e;t[1]===o.DIM?e=t[2]:(e=H(O,{color:o.DIM,children:`/`}),t[1]=o.DIM,t[2]=e);let n;t[3]!==i||t[4]!==a||t[5]!==r?(n=H(Ht,{focus:!0,value:r,onChange:i,onSubmit:a}),t[3]=i,t[4]=a,t[5]=r,t[6]=n):n=t[6];let s;return t[7]!==e||t[8]!==n?(s=U(E,{marginTop:1,children:[e,n]}),t[7]=e,t[8]=n,t[9]=s):s=t[9],s}if(r){let e;return t[10]!==o.DIM||t[11]!==r?(e=H(E,{marginTop:1,children:U(O,{color:o.DIM,children:[`/`,r]})}),t[10]=o.DIM,t[11]=r,t[12]=e):e=t[12],e}return null},Wt=S.Literals([`pending`,`in_progress`,`completed`,`failed`]),Gt=S.Literals([`read`,`edit`,`delete`,`move`,`search`,`execute`,`think`,`fetch`,`switch_mode`,`other`]);S.Literals([`end_turn`,`max_tokens`,`max_turn_requests`,`refusal`,`cancelled`]);const Kt=S.Union([S.Struct({type:S.Literal(`text`),text:S.String}),S.Struct({type:S.Literal(`image`),data:S.String,mimeType:S.String}),S.Struct({type:S.Literal(`resource_link`),uri:S.String}),S.Struct({type:S.Literal(`resource`),uri:S.String})]),qt=S.Union([S.Struct({type:S.Literal(`content`),content:Kt}),S.Struct({type:S.Literal(`diff`),path:S.String,oldText:S.optional(S.NullOr(S.String)),newText:S.optional(S.NullOr(S.String))}),S.Struct({type:S.Literal(`terminal`),terminalId:S.String})]),Jt=S.Struct({path:S.String,lineNumber:S.optional(S.NullOr(S.Number))});var Yt=class extends S.Class(`AcpAgentMessageChunk`)({sessionUpdate:S.Literal(`agent_message_chunk`),content:Kt,messageId:S.optional(S.NullOr(S.String))}){},Xt=class extends S.Class(`AcpAgentThoughtChunk`)({sessionUpdate:S.Literal(`agent_thought_chunk`),content:Kt,messageId:S.optional(S.NullOr(S.String))}){},Zt=class extends S.Class(`AcpUserMessageChunk`)({sessionUpdate:S.Literal(`user_message_chunk`),content:Kt,messageId:S.optional(S.NullOr(S.String))}){},Qt=class extends S.Class(`AcpToolCall`)({sessionUpdate:S.Literal(`tool_call`),toolCallId:S.String,title:S.String,kind:S.optional(Gt),status:S.optional(Wt),content:S.optional(S.Array(qt)),locations:S.optional(S.Array(Jt)),rawInput:S.optional(S.Unknown),rawOutput:S.optional(S.Unknown)}){},$t=class extends S.Class(`AcpToolCallUpdate`)({sessionUpdate:S.Literal(`tool_call_update`),toolCallId:S.String,title:S.optional(S.NullOr(S.String)),kind:S.optional(S.NullOr(Gt)),status:S.optional(S.NullOr(Wt)),content:S.optional(S.NullOr(S.Array(qt))),locations:S.optional(S.NullOr(S.Array(Jt))),rawInput:S.optional(S.Unknown),rawOutput:S.optional(S.Unknown)}){};const en=S.Literals([`pending`,`in_progress`,`completed`]),tn=S.Literals([`high`,`medium`,`low`]);var nn=class extends S.Class(`AcpPlanUpdate`)({sessionUpdate:S.Literal(`plan`),entries:S.Array(S.Struct({content:S.String,priority:tn,status:en}))}){},rn=class extends S.Class(`AcpAvailableCommandsUpdate`)({sessionUpdate:S.Literal(`available_commands_update`)}){},an=class extends S.Class(`AcpCurrentModeUpdate`)({sessionUpdate:S.Literal(`current_mode_update`)}){},on=class extends S.Class(`AcpConfigOptionUpdate`)({sessionUpdate:S.Literal(`config_option_update`)}){},sn=class extends S.Class(`AcpSessionInfoUpdate`)({sessionUpdate:S.Literal(`session_info_update`)}){},cn=class extends S.Class(`AcpUsageUpdate`)({sessionUpdate:S.Literal(`usage_update`)}){};const ln=S.Union([Yt,Xt,Zt,Qt,$t,nn,rn,an,on,sn,cn]);S.Struct({inputTokens:S.Number,outputTokens:S.Number,cachedReadTokens:S.optional(S.NullOr(S.Number)),cachedWriteTokens:S.optional(S.NullOr(S.Number)),thoughtTokens:S.optional(S.NullOr(S.Number))});const un=S.Literals([`claude`,`codex`,`cursor`]);var dn=class extends S.Class(`@ami/FileStat`)({relativePath:S.String,added:S.Number,removed:S.Number}){},fn=class extends S.Class(`@supervisor/GitState`)({isGitRepo:S.Boolean,currentBranch:S.String,mainBranch:S.UndefinedOr(S.String),isOnMain:S.Boolean,hasChangesFromMain:S.Boolean,hasUnstagedChanges:S.Boolean,hasBranchCommits:S.Boolean,branchCommitCount:S.Number,fileStats:S.Array(dn),workingTreeFileStats:S.Array(dn),fingerprint:S.UndefinedOr(S.String),savedFingerprint:S.UndefinedOr(S.String)}){get hasUntestedChanges(){return this.hasChangesFromMain||this.hasUnstagedChanges}get totalChangedLines(){return this.fileStats.reduce((e,t)=>e+t.added+t.removed,0)}get isCurrentStateTested(){return!this.fingerprint||!this.savedFingerprint?!1:this.fingerprint===this.savedFingerprint}};const pn=S.String.pipe(S.brand(`StepId`)),mn=S.String.pipe(S.brand(`PlanId`)),hn=S.TaggedUnion({WorkingTree:{},Branch:{mainBranch:S.String},Changes:{mainBranch:S.String},Commit:{hash:S.String}}),gn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working tree`,Branch:()=>`branch`,Changes:()=>`changes`,Commit:({hash:e})=>e.slice(0,7)})),_n=S.Struct({number:S.Number,headRefName:S.String,author:S.Struct({login:S.String}),state:S.String,updatedAt:S.String}),vn=[`recent`,`all`,`open`,`draft`,`merged`,`no-pr`];var yn=class extends S.Class(`@supervisor/RemoteBranch`)({name:S.String,author:S.String,prNumber:S.NullOr(S.Number),prStatus:S.NullOr(S.Literals([`open`,`draft`,`merged`])),updatedAt:S.NullOr(S.String)}){static filterBranches(e,t,n){let r=e.filter(e=>t===`recent`||t===`all`?!0:t===`no-pr`?e.prStatus===null:e.prStatus===t);if(n){let e=n.toLowerCase();r=r.filter(t=>t.name.toLowerCase().includes(e))}return t===`recent`&&(r=[...r].filter(e=>e.updatedAt!==null).sort((e,t)=>{let n=new Date(e.updatedAt??0).getTime();return new Date(t.updatedAt??0).getTime()-n})),r}};const bn=S.Literals([`pending`,`active`,`passed`,`failed`,`skipped`]);var xn=class e extends S.Class(`@supervisor/TestPlanStep`)({id:pn,title:S.String,instruction:S.String,expectedOutcome:S.String,routeHint:S.OptionFromNullOr(S.String),status:bn,summary:S.OptionFromNullOr(S.String),startedAt:S.OptionFromNullOr(S.DateTimeUtc),endedAt:S.OptionFromNullOr(S.DateTimeUtc)}){update(t){return new e({...this,...t})}},Sn=class extends S.Class(`@supervisor/TestCoverageEntry`)({path:S.String,testFiles:S.Array(S.String),covered:S.Boolean}){},Cn=class extends S.Class(`@supervisor/TestCoverageReport`)({entries:S.Array(Sn),coveredCount:S.Number,totalCount:S.Number,percent:S.Number}){};const wn=S.String.pipe(S.brand(`DraftId`));var Tn=class e extends S.Class(`@supervisor/TestPlanDraft`)({id:wn,changesFor:hn,currentBranch:S.String,diffPreview:S.String,fileStats:S.Array(dn),instruction:S.String,baseUrl:S.Option(S.String),isHeadless:S.Boolean,requiresCookies:S.Boolean,testCoverage:S.Option(Cn)}){update(t){return new e({...this,...t})}},En=class e extends Tn.extend(`@supervisor/TestPlan`)({id:mn,title:S.String,rationale:S.String,steps:S.Array(xn)}){update(t){return new e({...this,...t})}updateStep(t,n){return new e({...this,steps:this.steps.map((e,r)=>r===t?n(e):e)})}get stepCount(){return this.steps.length}get resetForRerun(){return new e({...this,steps:this.steps.map(e=>new xn({...e,status:`pending`,summary:_.none(),startedAt:_.none(),endedAt:_.none()}))})}},Dn=class extends S.TaggedClass()(`RunStarted`,{plan:En}){get id(){return`run-started-${this.plan.id}`}},On=class extends S.TaggedClass()(`StepStarted`,{stepId:pn,title:S.String}){get id(){return`step-started-${this.stepId}`}},kn=class extends S.TaggedClass()(`StepCompleted`,{stepId:pn,summary:S.String}){get id(){return`step-completed-${this.stepId}`}},An=class extends S.TaggedClass()(`StepFailed`,{stepId:pn,message:S.String}){get id(){return`step-failed-${this.stepId}`}},jn=class extends S.TaggedClass()(`StepSkipped`,{stepId:pn,reason:S.String}){get id(){return`step-skipped-${this.stepId}`}},Mn=class extends S.TaggedClass()(`ToolCall`,{toolName:S.String,input:S.Unknown}){get id(){return`tool-call-${this.toolName}-${JSON.stringify(this.input)}`}get displayText(){return v.isObject(this.input)&&`command`in this.input?String(this.input.command).slice(0,80):this.toolName}},Nn=class extends S.TaggedClass()(`ToolProgress`,{toolName:S.String,outputSize:S.Number}){get id(){return`tool-progress-${this.toolName}-${this.outputSize}`}},Pn=class extends S.TaggedClass()(`ToolResult`,{toolName:S.String,result:S.String,isError:S.Boolean}){get id(){return`tool-result-${this.toolName}-${this.result}`}},Fn=class extends S.TaggedClass()(`AgentThinking`,{text:S.String}){get id(){return`agent-thinking-${this.text}`}},In=class extends S.TaggedClass()(`AgentText`,{text:S.String}){get id(){return`agent-text-${this.text}`}},Ln=class extends S.TaggedClass()(`RunFinished`,{status:S.Literals([`passed`,`failed`]),summary:S.String}){get id(){return`run-finished-${this.status}`}};const Rn=e=>{if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}},zn=e=>{let t=e.indexOf(`|`);if(t===-1)return;let n=e.slice(0,t),r=e.slice(t+1),i=r.indexOf(`|`),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1);if(n===`STEP_START`)return new On({stepId:pn.makeUnsafe(a),title:o});if(n===`STEP_DONE`)return new kn({stepId:pn.makeUnsafe(a),summary:o});if(n===`ASSERTION_FAILED`)return new An({stepId:pn.makeUnsafe(a),message:o});if(n===`STEP_SKIPPED`)return new jn({stepId:pn.makeUnsafe(a),reason:o});if(n===`RUN_COMPLETED`)return new Ln({status:a===`failed`?`failed`:`passed`,summary:o})},Bn=S.Union([Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln]);var Vn=class extends S.TaggedClass()(`RunCompleted`,{report:S.suspend(()=>Qn)}){};const Hn=S.Union([Dn,On,kn,An,jn,Mn,Pn,Fn,Ln,Vn]);var Un=class extends S.Class(`@supervisor/Update`)({content:Hn,receivedAt:S.DateTimeUtc}){},Wn=class extends S.Class(`@supervisor/PullRequest`)({number:S.Number,url:S.String,title:S.String,headRefName:S.String}){};const Gn=S.TaggedUnion({WorkingTree:{},Branch:{branch:yn},PullRequest:{branch:yn},Commit:{hash:S.String,shortHash:S.String,subject:S.String}}),Kn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working-tree`,Branch:({branch:e})=>`branch-${e.name}`,PullRequest:({branch:e})=>`pr-${e.prNumber}`,Commit:({hash:e})=>`commit-${e}`})),qn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>`#${e.prNumber} ${e.name} ${e.author}`,Commit:({shortHash:e,subject:t})=>`${e} ${t}`})),Jn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`Local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>e.name,Commit:({shortHash:e})=>e})),Yn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working tree`,Branch:({branch:e})=>e.author?`by ${e.author}`:``,PullRequest:({branch:e})=>`#${e.prNumber} ${e.prStatus??``}`.trim(),Commit:({subject:e})=>e})),Xn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`Local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>`#${e.prNumber}`,Commit:({shortHash:e})=>e}));S.TaggedUnion({Branch:{branchName:S.String}});var Zn=class e extends En.extend(`@supervisor/ExecutedTestPlan`)({events:S.Array(Bn)}){addEvent(t){if(t.sessionUpdate===`agent_thought_chunk`){if(t.content.type!==`text`||t.content.text===void 0)return this;let n=this.finalizeTextBlock(),r=n.events.at(-1);return r?._tag===`AgentThinking`?new e({...n,events:[...n.events.slice(0,-1),new Fn({text:r.text+t.content.text})]}):new e({...n,events:[...n.events,new Fn({text:t.content.text})]})}if(t.sessionUpdate===`agent_message_chunk`){if(t.content.type!==`text`||t.content.text===void 0)return this;let n=this.events.at(-1);return n?._tag===`AgentText`?new e({...this,events:[...this.events.slice(0,-1),new In({text:n.text+t.content.text})]}):new e({...this,events:[...this.events,new In({text:t.content.text})]})}if(t.sessionUpdate===`tool_call`){let n=this.finalizeTextBlock();return new e({...n,events:[...n.events,new Mn({toolName:t.title,input:JSON.stringify(t.rawInput??{})})]})}if(t.sessionUpdate===`tool_call_update`){let n;if(t.rawInput!==void 0){let r=[...this.events];for(let e=r.length-1;e>=0;e--){let n=r[e];if(n._tag===`ToolCall`&&n.toolName===(t.title??``)){r[e]=new Mn({toolName:n.toolName,input:JSON.stringify(t.rawInput)});break}}n=new e({...this,events:r})}let r=n??this;if(t.status===`completed`||t.status===`failed`)return new e({...r,events:[...r.events,new Pn({toolName:t.title??``,result:Rn(t.rawOutput),isError:t.status===`failed`})]});if(t.rawOutput!==void 0){let n=Rn(t.rawOutput).length;return new e({...r,events:[...r.events.filter(e=>!(e._tag===`ToolProgress`&&e.toolName===(t.title??``))),new Nn({toolName:t.title??``,outputSize:n})]})}return r}return this}finalizeTextBlock(){let t=this.events.at(-1);if(t?._tag!==`AgentText`)return this;let n=t.text.split(`
7
- `).map(zn).filter(v.isNotUndefined);if(n.length===0)return this;let r=new e({...this,events:[...this.events,...n]});for(let e of n)r=r.applyMarker(e);return r}applyMarker(t){return t._tag===`StepStarted`?this.steps.some(e=>e.id===t.stepId)?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`active`,title:t.title,startedAt:_.some(l.nowUnsafe())}):e)}):new e({...this,steps:[...this.steps,new xn({id:t.stepId,title:t.title,instruction:t.title,expectedOutcome:``,routeHint:_.none(),status:`active`,summary:_.none(),startedAt:_.some(l.nowUnsafe()),endedAt:_.none()})]}):t._tag===`StepCompleted`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`passed`,summary:_.some(t.summary),expectedOutcome:t.summary,endedAt:_.some(l.nowUnsafe())}):e)}):t._tag===`StepFailed`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`failed`,summary:_.some(t.message),expectedOutcome:t.message,endedAt:_.some(l.nowUnsafe())}):e)}):t._tag===`StepSkipped`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`skipped`,summary:_.some(t.reason),endedAt:_.some(l.nowUnsafe())}):e)}):this}get activeStep(){return this.steps.find(e=>e.status===`active`)}get completedStepCount(){return this.steps.filter(e=>e.status===`passed`||e.status===`failed`||e.status===`skipped`).length}get lastToolCallDisplayText(){let e=this.events.findLast(e=>e._tag===`ToolCall`);if(!(!e||e._tag!==`ToolCall`))return e.displayText}},Qn=class extends Zn.extend(`@supervisor/TestReport`)({summary:S.String,screenshotPaths:S.Array(S.String),pullRequest:S.Option(S.suspend(()=>Wn)),testCoverageReport:S.Option(Cn)}){get stepStatuses(){let e=new Map(this.steps.map(e=>[e.id,{status:`not-run`,summary:``}]));for(let t of this.events)t._tag===`StepCompleted`?e.set(t.stepId,{status:`passed`,summary:t.summary}):t._tag===`StepFailed`?e.set(t.stepId,{status:`failed`,summary:t.message}):t._tag===`StepSkipped`&&e.set(t.stepId,{status:`skipped`,summary:t.reason});return e}get status(){let e=this.stepStatuses;for(let{status:t}of e.values())if(t===`failed`)return`failed`;return`passed`}get toPlainText(){let e=this.stepStatuses,t=this.steps.filter(t=>e.get(t.id)?.status===`passed`).length,n=this.steps.filter(t=>e.get(t.id)?.status===`failed`).length,r=this.steps.filter(t=>e.get(t.id)?.status===`skipped`).length,i=this.status===`passed`?`✅`:`❌`,a=[`${t} passed`,`${n} failed`];r>0&&a.push(`${r} skipped`);let o=[`${i} ${this.title} \u2014 ${this.status.toUpperCase()}`,``,this.summary,``,`${a.join(`, `)} out of ${this.steps.length} steps`,``];for(let t of this.steps){let n=e.get(t.id),r=n?.status??`not-run`,i=r===`passed`?`✓`:r===`failed`?`✗`:r===`skipped`?`→`:`–`;o.push(` ${i} ${t.title}`),n?.summary&&o.push(` ${n.summary}`)}if(_.isSome(this.testCoverageReport)){let e=this.testCoverageReport.value;o.push(``),o.push(`Test coverage: ${e.percent}% (${e.coveredCount}/${e.totalCount} changed files have tests)`);let t=e.entries.filter(e=>!e.covered);if(t.length>0){o.push(` Untested files:`);for(let e of t)o.push(` - ${e.path}`)}}return o.join(`
8
- `)}},$n=class extends C.Service()(`@supervisor/Updates`,{make:u.gen(function*(){let e=yield*y.unbounded();return{publish:u.fn(`Updates.publish`)(function*(t){yield*y.publish(e,new Un({content:t,receivedAt:l.nowUnsafe()}))}),stream:u.fn(`Updates.stream`)(function*(){return w.fromPubSub(e)})}})}){static layer=m.effect(this)(this.make)};const er=S.Struct({name:S.String,value:S.String});var tr=class extends S.Class(`AgentStreamOptions`)({cwd:S.String,sessionId:S.Option(S.String),prompt:S.String,systemPrompt:S.Option(S.String),mcpEnv:S.optional(S.Array(er))}){};const nr={authenticate:`authenticate`,initialize:`initialize`,session_cancel:`session/cancel`,session_close:`session/close`,session_fork:`session/fork`,session_list:`session/list`,session_load:`session/load`,session_new:`session/new`,session_prompt:`session/prompt`,session_resume:`session/resume`,session_set_config_option:`session/set_config_option`,session_set_mode:`session/set_mode`,session_set_model:`session/set_model`},rr={fs_read_text_file:`fs/read_text_file`,fs_write_text_file:`fs/write_text_file`,session_request_permission:`session/request_permission`,session_update:`session/update`,terminal_create:`terminal/create`,terminal_kill:`terminal/kill`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`},ir=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),terminal:q.boolean().optional().default(!1)}),ar=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),label:q.string().nullish(),name:q.string(),optional:q.boolean().optional().default(!1),secret:q.boolean().optional().default(!0)}),or=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string().nullish(),id:q.string(),name:q.string()}),sr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string().nullish(),id:q.string(),link:q.string().nullish(),name:q.string(),vars:q.array(ar)}),cr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),args:q.array(q.string()).optional(),description:q.string().nullish(),env:q.record(q.string(),q.string()).optional(),id:q.string(),name:q.string()}),lr=q.union([sr.and(q.object({type:q.literal(`env_var`)})),cr.and(q.object({type:q.literal(`terminal`)})),or]),ur=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),methodId:q.string()}),dr=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),fr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),blob:q.string(),mimeType:q.string().nullish(),uri:q.string()}),pr=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),mr=q.object({amount:q.number(),currency:q.string()}),hr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),terminalId:q.string()}),gr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),newText:q.string(),oldText:q.string().nullish(),path:q.string()}),_r=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),name:q.string(),value:q.string()}),vr=q.union([q.literal(-32700),q.literal(-32600),q.literal(-32601),q.literal(-32602),q.literal(-32603),q.literal(-32800),q.literal(-32e3),q.literal(-32002),q.number().int().min(-2147483648,{message:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{message:`Invalid value: Expected int32 to be <= 2147483647`})]),yr=q.object({code:vr,data:q.unknown().optional(),message:q.string()}),br=q.unknown(),xr=q.unknown(),Sr=q.unknown(),Cr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),readTextFile:q.boolean().optional().default(!1),writeTextFile:q.boolean().optional().default(!1)}),wr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),auth:ir.optional().default({terminal:!1}),fs:Cr.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:q.boolean().optional().default(!1)}),Tr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),name:q.string(),value:q.string()}),Er=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),name:q.string(),title:q.string().nullish(),version:q.string()}),Dr=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),Or=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cursor:q.string().nullish(),cwd:q.string().nullish()}),kr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),http:q.boolean().optional().default(!1),sse:q.boolean().optional().default(!1)}),Ar=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),headers:q.array(Tr),name:q.string(),url:q.string()}),jr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),headers:q.array(Tr),name:q.string(),url:q.string()}),Mr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),args:q.array(q.string()),command:q.string(),env:q.array(_r),name:q.string()}),Nr=q.union([Ar.and(q.object({type:q.literal(`http`)})),jr.and(q.object({type:q.literal(`sse`)})),Mr]),Pr=q.string(),Fr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string().nullish(),modelId:Pr,name:q.string()}),Ir=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cwd:q.string(),mcpServers:q.array(Nr)}),Lr=q.string(),Rr=q.union([q.literal(`allow_once`),q.literal(`allow_always`),q.literal(`reject_once`),q.literal(`reject_always`)]),zr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),kind:Rr,name:q.string(),optionId:Lr}),Br=q.union([q.literal(`high`),q.literal(`medium`),q.literal(`low`)]),Vr=q.union([q.literal(`pending`),q.literal(`in_progress`),q.literal(`completed`)]),Hr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:q.string(),priority:Br,status:Vr}),Ur=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),entries:q.array(Hr)}),Wr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),audio:q.boolean().optional().default(!1),embeddedContext:q.boolean().optional().default(!1),image:q.boolean().optional().default(!1)}),Gr=q.number().int().gte(0).lte(65535),Kr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),clientCapabilities:wr.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:Er.nullish(),protocolVersion:Gr}),qr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:q.string()}),Jr=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),Yr=q.union([q.number(),q.string()]).nullable();q.object({_meta:q.record(q.string(),q.unknown()).nullish(),requestId:Yr});const Xr=q.enum([`assistant`,`user`]),Zr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),audience:q.array(Xr).nullish(),lastModified:q.string().nullish(),priority:q.number().nullish()}),Qr=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),annotations:Zr.nullish(),data:q.string(),mimeType:q.string()}),$r=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),annotations:Zr.nullish(),data:q.string(),mimeType:q.string(),uri:q.string().nullish()}),ei=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),annotations:Zr.nullish(),description:q.string().nullish(),mimeType:q.string().nullish(),name:q.string(),size:q.number().nullish(),title:q.string().nullish(),uri:q.string()}),ti=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),optionId:Lr}),ni=q.union([q.object({outcome:q.literal(`cancelled`)}),ti.and(q.object({outcome:q.literal(`selected`)}))]),ri=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),outcome:ni}),ii=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),ai=q.object({currentValue:q.boolean()}),oi=q.string(),si=q.string(),ci=q.union([q.literal(`mode`),q.literal(`model`),q.literal(`thought_level`),q.string()]),li=q.string(),ui=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string().nullish(),name:q.string(),value:li}),di=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),group:oi,name:q.string(),options:q.array(ui)}),fi=q.union([q.array(ui),q.array(di)]),pi=q.object({currentValue:li,options:fi}),mi=q.intersection(q.union([pi.and(q.object({type:q.literal(`select`)})),ai.and(q.object({type:q.literal(`boolean`)}))]),q.object({_meta:q.record(q.string(),q.unknown()).nullish(),category:ci.nullish(),description:q.string().nullish(),id:si,name:q.string()})),hi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi)}),gi=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),_i=q.string(),vi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i});q.object({method:q.string(),params:q.union([vi,br]).nullish()});const yi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i}),bi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),args:q.array(q.string()).optional(),command:q.string(),cwd:q.string().nullish(),env:q.array(_r).optional(),outputByteLimit:q.number().nullish(),sessionId:_i}),xi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cwd:q.string(),mcpServers:q.array(Nr).optional(),sessionId:_i}),Si=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i,terminalId:q.string()}),Ci=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cwd:q.string(),mcpServers:q.array(Nr),sessionId:_i}),wi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),limit:q.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),line:q.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:q.string(),sessionId:_i}),Ti=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i,terminalId:q.string()}),Ei=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cwd:q.string(),mcpServers:q.array(Nr).optional(),sessionId:_i}),Di=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cwd:q.string(),sessionId:_i,title:q.string().nullish(),updatedAt:q.string().nullish()}),Oi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),nextCursor:q.string().nullish(),sessions:q.array(Di)}),ki=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),title:q.string().nullish(),updatedAt:q.string().nullish()}),Ai=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),ji=q.string(),Mi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),currentModeId:ji}),Ni=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string().nullish(),id:ji,name:q.string()}),Pi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),availableModes:q.array(Ni),currentModeId:ji}),Fi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),availableModels:q.array(Fr),currentModelId:Pr}),Ii=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi).nullish(),models:Fi.nullish(),modes:Pi.nullish(),sessionId:_i}),Li=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi).nullish(),models:Fi.nullish(),modes:Pi.nullish()}),Ri=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi).nullish(),models:Fi.nullish(),modes:Pi.nullish(),sessionId:_i}),zi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi).nullish(),models:Fi.nullish(),modes:Pi.nullish()}),Bi=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),Vi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),close:ii.nullish(),fork:gi.nullish(),list:Ai.nullish(),resume:Bi.nullish()}),Hi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),loadSession:q.boolean().optional().default(!1),mcpCapabilities:kr.optional().default({http:!1,sse:!1}),promptCapabilities:Wr.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:Vi.optional().default({})}),Ui=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),agentCapabilities:Hi.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:Er.nullish(),authMethods:q.array(lr).optional().default([]),protocolVersion:Gr}),Wi=q.intersection(q.union([q.object({type:q.literal(`boolean`),value:q.boolean()}),q.object({value:li})]),q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configId:si,sessionId:_i})),Gi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),configOptions:q.array(mi)}),Ki=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),modeId:ji,sessionId:_i}),qi=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),Ji=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),modelId:Pr,sessionId:_i}),Yi=q.object({_meta:q.record(q.string(),q.unknown()).nullish()}),Xi=q.union([q.literal(`end_turn`),q.literal(`max_tokens`),q.literal(`max_turn_requests`),q.literal(`refusal`),q.literal(`cancelled`)]),Zi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),terminalId:q.string()}),Qi=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),exitCode:q.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:q.string().nullish()}),$i=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i,terminalId:q.string()}),ea=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),exitStatus:Qi.nullish(),output:q.string(),truncated:q.boolean()}),ta=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),annotations:Zr.nullish(),text:q.string()}),na=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),mimeType:q.string().nullish(),text:q.string(),uri:q.string()}),ra=q.union([na,fr]),ia=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),annotations:Zr.nullish(),resource:ra}),aa=q.union([ta.and(q.object({type:q.literal(`text`)})),$r.and(q.object({type:q.literal(`image`)})),Qr.and(q.object({type:q.literal(`audio`)})),ei.and(q.object({type:q.literal(`resource_link`)})),ia.and(q.object({type:q.literal(`resource`)}))]),oa=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:aa}),sa=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:aa,messageId:q.string().nullish()}),ca=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),messageId:q.string().nullish(),prompt:q.array(aa),sessionId:_i});q.object({id:Yr,method:q.string(),params:q.union([Kr,ur,Ir,Ci,Or,xi,Ei,yi,Ki,Wi,ca,Ji,xr]).nullish()});const la=q.union([oa.and(q.object({type:q.literal(`content`)})),gr.and(q.object({type:q.literal(`diff`)})),Zi.and(q.object({type:q.literal(`terminal`)}))]),ua=q.string(),da=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),line:q.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:q.string()}),fa=q.union([q.literal(`pending`),q.literal(`in_progress`),q.literal(`completed`),q.literal(`failed`)]),pa=q.union([q.literal(`read`),q.literal(`edit`),q.literal(`delete`),q.literal(`move`),q.literal(`search`),q.literal(`execute`),q.literal(`think`),q.literal(`fetch`),q.literal(`switch_mode`),q.literal(`other`)]),ma=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:q.array(la).optional(),kind:pa.optional(),locations:q.array(da).optional(),rawInput:q.unknown().optional(),rawOutput:q.unknown().optional(),status:fa.optional(),title:q.string(),toolCallId:ua}),ha=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:q.array(la).nullish(),kind:pa.nullish(),locations:q.array(da).nullish(),rawInput:q.unknown().optional(),rawOutput:q.unknown().optional(),status:fa.nullish(),title:q.string().nullish(),toolCallId:ua}),ga=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),options:q.array(zr),sessionId:_i,toolCall:ha}),_a=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),hint:q.string()}),va=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),description:q.string(),input:_a.nullish(),name:q.string()}),ya=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),availableCommands:q.array(va)}),ba=q.object({cachedReadTokens:q.number().nullish(),cachedWriteTokens:q.number().nullish(),inputTokens:q.number(),outputTokens:q.number(),thoughtTokens:q.number().nullish(),totalTokens:q.number()}),xa=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),stopReason:Xi,usage:ba.nullish(),userMessageId:q.string().nullish()});q.union([q.object({id:Yr,result:q.union([Ui,dr,Ri,Li,Oi,Ii,zi,pr,qi,Gi,xa,Yi,Sr])}),q.object({error:yr,id:Yr})]);const Sa=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),cost:mr.nullish(),size:q.number(),used:q.number()}),Ca=q.union([sa.and(q.object({sessionUpdate:q.literal(`user_message_chunk`)})),sa.and(q.object({sessionUpdate:q.literal(`agent_message_chunk`)})),sa.and(q.object({sessionUpdate:q.literal(`agent_thought_chunk`)})),ma.and(q.object({sessionUpdate:q.literal(`tool_call`)})),ha.and(q.object({sessionUpdate:q.literal(`tool_call_update`)})),Ur.and(q.object({sessionUpdate:q.literal(`plan`)})),ya.and(q.object({sessionUpdate:q.literal(`available_commands_update`)})),Mi.and(q.object({sessionUpdate:q.literal(`current_mode_update`)})),hi.and(q.object({sessionUpdate:q.literal(`config_option_update`)})),ki.and(q.object({sessionUpdate:q.literal(`session_info_update`)})),Sa.and(q.object({sessionUpdate:q.literal(`usage_update`)}))]),wa=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i,update:Ca});q.object({method:q.string(),params:q.union([wa,br]).nullish()});const Ta=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),sessionId:_i,terminalId:q.string()}),Ea=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),exitCode:q.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:q.string().nullish()}),Da=q.object({_meta:q.record(q.string(),q.unknown()).nullish(),content:q.string(),path:q.string(),sessionId:_i});q.object({id:Yr,method:q.string(),params:q.union([Da,wi,ga,bi,$i,Ti,Ta,Si,xr]).nullish()});const Oa=q.object({_meta:q.record(q.string(),q.unknown()).nullish()});q.union([q.object({id:Yr,result:q.union([Oa,qr,ri,hr,ea,Jr,Ea,Dr,Sr])}),q.object({error:yr,id:Yr})]);function ka(e,t){let n=new TextEncoder,r=new TextDecoder;return{readable:new ReadableStream({async start(e){let n=``,i=t.getReader();try{for(;;){let{value:t,done:a}=await i.read();if(a)break;if(!t)continue;n+=r.decode(t,{stream:!0});let o=n.split(`
2
+ import{n as e,r as t,t as n}from"./chunk-wdO_pP5q.js";import{a as r,i}from"./server-D776aGSk.js";import{createRequire as a}from"node:module";import{Array as o,Cause as s,Config as c,DateTime as l,Effect as u,Exit as d,FiberMap as f,FileSystem as p,Layer as m,Logger as h,Match as g,Option as _,Predicate as v,PubSub as y,Queue as b,References as x,Schema as S,ServiceMap as C,Stream as w,String as ee}from"effect";import{Command as T}from"commander";import{Box as E,Static as D,Text as O,render as k,useApp as A,useInput as te,useStdout as ne}from"ink";import{QueryClient as re,QueryClientProvider as j,useMutation as M,useQuery as N}from"@tanstack/react-query";import{c as ie}from"react/compiler-runtime";import{createContext as ae,useCallback as oe,useContext as P,useEffect as se,useMemo as F,useRef as I,useState as L}from"react";import*as R from"node:child_process";import{exec as z,execFile as ce,execSync as le,spawnSync as B}from"node:child_process";import{Fragment as ue,jsx as V,jsxs as H}from"react/jsx-runtime";import U from"figures";import W from"picocolors";import*as G from"node:path";import de,{join as fe,normalize as pe}from"node:path";import*as me from"node:url";import{fileURLToPath as he,pathToFileURL as ge}from"node:url";import{z as _e}from"zod";import{z as K}from"zod/v4";import{ChildProcess as ve,ChildProcessSpawner as ye}from"effect/unstable/process";import*as be from"@effect/platform-node/NodeServices";import*as xe from"effect/Array";import*as q from"effect/String";import*as Se from"effect/Function";import*as Ce from"node:crypto";import{createHash as we}from"node:crypto";import{Buffer as Te}from"node:buffer";import{execSync as Ee,spawn as De}from"child_process";import{EventEmitter as Oe}from"node:events";import{FileSystem as ke}from"effect/FileSystem";import*as Ae from"node:os";import{platform as je}from"node:os";import*as Me from"@effect/platform-node/NodeHttpClient";import*as Ne from"@effect/platform-node/NodeSocket";import{ChildProcessSpawner as Pe}from"effect/unstable/process/ChildProcessSpawner";import{request as Fe}from"node:http";import*as Ie from"node:fs/promises";import Le from"ink-spinner";import Re from"cli-truncate";import ze from"string-width";import{create as Be}from"zustand";import*as Ve from"effect/Data";import*as He from"@effect/platform-node/NodeFileSystem";import{dirname as Ue,posix as We,sep as Ge}from"path";import*as Ke from"node:fs";import{appendFileSync as qe,createReadStream as Je}from"node:fs";import{createInterface as Ye}from"node:readline";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{DevTools as Ze}from"effect/unstable/devtools";import*as Qe from"effect/unstable/observability/Otlp";import{createJSONStorage as $e,persist as et}from"zustand/middleware";import*as tt from"effect/unstable/reactivity/AsyncResult";import*as nt from"effect/unstable/reactivity/Atom";import{RegistryProvider as rt,useAtom as it,useAtomSet as at,useAtomValue as ot}from"@effect/atom-react";import st from"pretty-ms";import{detectTerminal as ct}from"detect-terminal";import lt from"supports-terminal-graphics";import ut from"ink-link";import{Hono as dt}from"hono";import{proxy as ft}from"hono/proxy";import{serve as pt}from"@hono/node-server";import"node-notifier";import mt from"prompts";import ht from"ora";const gt=`0.0.12`,_t=`\x1B[?1049l`,vt=process.env.SUPPORT_CLICK===`true`||process.env.SUPPORT_CLICK===`1`,yt=[`lint`,`check`,`format`,`typecheck`,`type-check`],bt=`expect-cli`,xt={"pnpm-lock.yaml":`pnpm`,"pnpm-workspace.yaml":`pnpm`,"yarn.lock":`yarn`,"package-lock.json":`npm`,"npm-shrinkwrap.json":`npm`,"bun.lock":`bun`,"bun.lockb":`bun`,"deno.lock":`deno`},St=()=>{},Ct=ae({subscribeClick:()=>St}),wt=/\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[[\d;?<>=]*[A-Za-z~]|\[<[\d;]+[Mm]|\[\d+;\d+R|\[\?[\d;]+[a-z]/g,Tt=({children:e})=>{if(!vt)return V(ue,{children:e});let t=I(new Set),n=I(!1);if(!n.current){n.current=!0,process.stdout.write(`\x1B[?1003l\x1B[?1002l\x1B[?1000h\x1B[?1006h`);let e=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(n,...r){if(n===`data`){let i=(typeof r[0]==`string`?r[0]:String(r[0])).replace(wt,(e,n,r,i,a)=>{if(n===`0`)for(let e of t.current)e({x:Number(r),y:Number(i)},a===`M`?`press`:`release`);return``});return i.length===0?!0:e(n,i)}return e(n,...r)}}let r=oe(e=>(t.current.add(e),()=>{t.current.delete(e)}),[]);return V(Ct.Provider,{value:{subscribeClick:r},children:e})},Et=()=>{let e=ie(1);if(e[0]!==`35703fbc37b9d963e330527161df9fe36b70875a77771f1d737994ab88cecbb3`){for(let t=0;t<1;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`35703fbc37b9d963e330527161df9fe36b70875a77771f1d737994ab88cecbb3`}return P(Ct)},Dt=/\x1b\[[\d;?<>=]*[A-Za-z~]|\[<[\d;]+[Mm]|\[\?[\d;]+[a-z]|\[\d+;\d+R/g,Ot=e=>vt?e.replace(Dt,``):e,kt=e=>e&&e>0?e:80,At=e=>e&&e>0?e:24,jt=()=>{let{stdout:e}=ne(),[t,n]=L([kt(e.columns),At(e.rows)]),r=I(!1);return r.current||(r.current=!0,e.on(`resize`,()=>n([kt(e.columns),At(e.rows)]))),t},Mt=`NO_COLOR`in process.env,J={primary:Mt?``:`whiteBright`,secondary:Mt?``:`gray`,accent:Mt?``:`white`,error:Mt?``:`red`,warning:Mt?``:`yellow`,success:Mt?``:`green`,info:Mt?``:`gray`,text:Mt?``:`white`,textMuted:Mt?``:`gray`,border:Mt?``:`gray`,borderActive:Mt?``:`white`,borderSubtle:Mt?``:`blackBright`,shimmerBase:Mt?``:`#555555`,shimmerHighlight:Mt?``:`#ffffff`,inputBg:Mt?``:`#1e1e1e`,bannerBg:Mt?``:`#332b00`,errorBg:Mt?``:`#330b0b`},Nt={TEXT:J.text,DIM:J.textMuted,GREEN:J.success,PRIMARY:J.primary,SELECTION:J.accent,RED:J.error,BORDER:J.border,DIVIDER:J.borderSubtle,YELLOW:J.warning,PURPLE:J.secondary,CYAN:J.info,INPUT_BG:J.inputBg,BANNER_BG:J.bannerBg,ERROR_BG:J.errorBg},Pt=()=>Nt,Ft=e=>{let t=ie(21);if(t[0]!==`c91257771a99332d5805ee6c49b36d74b00fa9357a1ef3353879ee4c78179ae7`){for(let e=0;e<21;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`c91257771a99332d5805ee6c49b36d74b00fa9357a1ef3353879ee4c78179ae7`}let{color:n,children:r,marginTop:i,marginBottom:a,paddingX:o,ref:s}=e,c=o===void 0?1:o,[l]=jt(),u;t[1]===l?u=t[2]:(u=`─`.repeat(l),t[1]=l,t[2]=u);let d;t[3]!==n||t[4]!==u?(d=V(O,{color:n,wrap:`truncate`,children:u}),t[3]=n,t[4]=u,t[5]=d):d=t[5];let f;t[6]!==r||t[7]!==c?(f=V(E,{flexDirection:`column`,paddingX:c,children:r}),t[6]=r,t[7]=c,t[8]=f):f=t[8];let p;t[9]===l?p=t[10]:(p=`─`.repeat(l),t[9]=l,t[10]=p);let m;t[11]!==n||t[12]!==p?(m=V(O,{color:n,wrap:`truncate`,children:p}),t[11]=n,t[12]=p,t[13]=m):m=t[13];let h;return t[14]!==a||t[15]!==i||t[16]!==s||t[17]!==d||t[18]!==f||t[19]!==m?(h=H(E,{flexDirection:`column`,width:`100%`,marginTop:i,marginBottom:a,ref:s,children:[d,f,m]}),t[14]=a,t[15]=i,t[16]=s,t[17]=d,t[18]=f,t[19]=m,t[20]=h):h=t[20],h},It=e=>{let t=e,n=1,r=1;for(;t;){if(!t.yogaNode)return{left:n,top:r};let e=t.yogaNode.getComputedLayout();n+=e.left,r+=e.top,t=t.parentNode}return{left:n,top:r}},Lt=({onClick:e,children:t,fullWidth:n=!0})=>{let{subscribeClick:r}=Et(),i=I(e);return i.current=e,V(E,{ref:oe(e=>{if(e)return r((t,n)=>{if(n!==`press`||!e.yogaNode)return;let r=It(e),a=e.yogaNode.getComputedLayout(),o=t.x<r.left||t.x>=r.left+a.width,s=t.y<r.top||t.y>=r.top+a.height;!o&&!s&&i.current?.()})},[r]),width:n?`100%`:void 0,children:t})},Rt=e=>/\w/.test(e),zt=(e,t)=>{let n=t-1;for(;n>0&&!Rt(e[n]);)n--;for(;n>0&&Rt(e[n-1]);)n--;return n},Bt=(e,t)=>{let n=t;for(;n<e.length&&Rt(e[n]);)n++;for(;n<e.length&&!Rt(e[n]);)n++;return n},Vt=(e,t)=>{let n=e.split(`
3
+ `),r=0;for(let e=0;e<n.length;e++){let i=n[e].length;if(t<=r+i)return{lineIndex:e,column:t-r,lines:n};r+=i+1}let i=n.length-1;return{lineIndex:i,column:n[i].length,lines:n}},Ht=(e,t,n)=>{let r=0;for(let n=0;n<t;n++)r+=e[n].length+1;return r+Math.min(n,e[t].length)},Ut=({value:e,placeholder:t=``,focus:n=!0,mask:r,highlightPastedText:i=!1,showCursor:a=!0,multiline:o=!1,onChange:s,onSubmit:c,onUpArrowAtTop:l,onDownArrowAtBottom:u})=>{let[d,f]=L({cursorOffset:(e||``).length,cursorWidth:0}),{cursorOffset:p,cursorWidth:m}=d,h=I({originalValue:e,focus:n,showCursor:a});(h.current.originalValue!==e||h.current.focus!==n||h.current.showCursor!==a)&&(h.current={originalValue:e,focus:n,showCursor:a},f(t=>{if(!n||!a)return t;let r=e||``;return t.cursorOffset>r.length-1?{cursorOffset:r.length,cursorWidth:0}:t}));let g=i?m:0,_=r?r.repeat(e.length):e,v=_,y=t?W.gray(t):void 0;if(a&&n){y=t.length>0?W.inverse(t[0])+W.gray(t.slice(1)):W.inverse(` `),v=_.length>0?``:W.inverse(` `);let e=0;for(let t of _){let n=e>=p-g&&e<=p;n&&t===`
4
+ `?v+=W.inverse(` `)+`
5
+ `:v+=n?W.inverse(t):t,e++}_.length>0&&p===_.length&&(v+=W.inverse(` `))}return te((t,n)=>{if(!o&&(n.upArrow||n.downArrow)||n.ctrl&&t===`c`||n.tab||n.shift&&n.tab)return;let r=p,i=e,d=0,m=!1;if(o&&n.upArrow&&a){let{lineIndex:t,column:n,lines:i}=Vt(e,p);t>0?r=Ht(i,t-1,n):l?.(),m=!0}else if(o&&n.downArrow&&a){let{lineIndex:t,column:n,lines:i}=Vt(e,p);t<i.length-1?r=Ht(i,t+1,n):u?.(),m=!0}else if(n.ctrl&&t===`a`&&a)r=0,m=!0;else if(n.ctrl&&t===`e`&&a)r=e.length,m=!0;else if(n.ctrl&&t===`f`&&a)r=p+1,m=!0;else if(n.ctrl&&t===`b`&&a)r=p-1,m=!0;else if(n.ctrl&&t===`k`)i=e.slice(0,p),m=!0;else if(n.ctrl&&t===`u`)p>0&&(i=e.slice(p),r=0),m=!0;else if(n.ctrl&&t===`w`){if(p>0){let t=zt(e,p);i=e.slice(0,t)+e.slice(p),r=t}m=!0}else if(n.ctrl&&t===`d`)p<e.length&&(i=e.slice(0,p)+e.slice(p+1)),m=!0;else if(n.ctrl&&t===`t`)p>0&&p<e.length&&(i=e.slice(0,p-1)+e[p]+e[p-1]+e.slice(p+1),r=p+1),m=!0;else if(n.meta&&t===`b`&&a)r=zt(e,p),m=!0;else if(n.meta&&t===`f`&&a)r=Bt(e,p),m=!0;else if(n.meta&&(n.backspace||n.delete)){if(p>0){let t=zt(e,p);i=e.slice(0,t)+e.slice(p),r=t}m=!0}else if(n.meta)return;if(!m)if(n.return)if(o&&n.shift)i=e.slice(0,p)+`
6
+ `+e.slice(p),r++;else{c&&c(e);return}else n.leftArrow?a&&r--:n.rightArrow?a&&r++:n.backspace||n.delete?p>0&&(i=e.slice(0,p-1)+e.slice(p,e.length),r--):(i=e.slice(0,p)+t+e.slice(p,e.length),r+=t.length,t.length>1&&(d=t.length));r<0&&(r=0),r>i.length&&(r=i.length),f({cursorOffset:r,cursorWidth:d}),i!==e&&s(i)},{isActive:n}),V(O,{children:t?_.length>0?v:y:v})},Wt=e=>{let t=ie(13);if(t[0]!==`ed5db14495474995e96712c30462d38da6b6aa36bffcbec475f62d8824e8125d`){for(let e=0;e<13;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`ed5db14495474995e96712c30462d38da6b6aa36bffcbec475f62d8824e8125d`}let{isSearching:n,query:r,onChange:i,onSubmit:a}=e,o=Pt();if(n){let e;t[1]===o.DIM?e=t[2]:(e=V(O,{color:o.DIM,children:`/`}),t[1]=o.DIM,t[2]=e);let n;t[3]!==i||t[4]!==a||t[5]!==r?(n=V(Ut,{focus:!0,value:r,onChange:i,onSubmit:a}),t[3]=i,t[4]=a,t[5]=r,t[6]=n):n=t[6];let s;return t[7]!==e||t[8]!==n?(s=H(E,{marginTop:1,children:[e,n]}),t[7]=e,t[8]=n,t[9]=s):s=t[9],s}if(r){let e;return t[10]!==o.DIM||t[11]!==r?(e=V(E,{marginTop:1,children:H(O,{color:o.DIM,children:[`/`,r]})}),t[10]=o.DIM,t[11]=r,t[12]=e):e=t[12],e}return null},Gt=S.Literals([`pending`,`in_progress`,`completed`,`failed`]),Kt=S.Literals([`read`,`edit`,`delete`,`move`,`search`,`execute`,`think`,`fetch`,`switch_mode`,`other`]);S.Literals([`end_turn`,`max_tokens`,`max_turn_requests`,`refusal`,`cancelled`]);const qt=S.Union([S.Struct({type:S.Literal(`text`),text:S.String}),S.Struct({type:S.Literal(`image`),data:S.String,mimeType:S.String}),S.Struct({type:S.Literal(`resource_link`),uri:S.String}),S.Struct({type:S.Literal(`resource`),uri:S.String})]),Jt=S.Union([S.Struct({type:S.Literal(`content`),content:qt}),S.Struct({type:S.Literal(`diff`),path:S.String,oldText:S.optional(S.NullOr(S.String)),newText:S.optional(S.NullOr(S.String))}),S.Struct({type:S.Literal(`terminal`),terminalId:S.String})]),Yt=S.Struct({path:S.String,lineNumber:S.optional(S.NullOr(S.Number))});var Xt=class extends S.Class(`AcpAgentMessageChunk`)({sessionUpdate:S.Literal(`agent_message_chunk`),content:qt,messageId:S.optional(S.NullOr(S.String))}){},Zt=class extends S.Class(`AcpAgentThoughtChunk`)({sessionUpdate:S.Literal(`agent_thought_chunk`),content:qt,messageId:S.optional(S.NullOr(S.String))}){},Qt=class extends S.Class(`AcpUserMessageChunk`)({sessionUpdate:S.Literal(`user_message_chunk`),content:qt,messageId:S.optional(S.NullOr(S.String))}){},$t=class extends S.Class(`AcpToolCall`)({sessionUpdate:S.Literal(`tool_call`),toolCallId:S.String,title:S.String,kind:S.optional(Kt),status:S.optional(Gt),content:S.optional(S.Array(Jt)),locations:S.optional(S.Array(Yt)),rawInput:S.optional(S.Unknown),rawOutput:S.optional(S.Unknown)}){},en=class extends S.Class(`AcpToolCallUpdate`)({sessionUpdate:S.Literal(`tool_call_update`),toolCallId:S.String,title:S.optional(S.NullOr(S.String)),kind:S.optional(S.NullOr(Kt)),status:S.optional(S.NullOr(Gt)),content:S.optional(S.NullOr(S.Array(Jt))),locations:S.optional(S.NullOr(S.Array(Yt))),rawInput:S.optional(S.Unknown),rawOutput:S.optional(S.Unknown)}){};const tn=S.Literals([`pending`,`in_progress`,`completed`]),nn=S.Literals([`high`,`medium`,`low`]);var rn=class extends S.Class(`AcpPlanUpdate`)({sessionUpdate:S.Literal(`plan`),entries:S.Array(S.Struct({content:S.String,priority:nn,status:tn}))}){},an=class extends S.Class(`AcpAvailableCommandsUpdate`)({sessionUpdate:S.Literal(`available_commands_update`)}){},on=class extends S.Class(`AcpCurrentModeUpdate`)({sessionUpdate:S.Literal(`current_mode_update`)}){},sn=class extends S.Class(`AcpConfigOptionUpdate`)({sessionUpdate:S.Literal(`config_option_update`)}){},cn=class extends S.Class(`AcpSessionInfoUpdate`)({sessionUpdate:S.Literal(`session_info_update`)}){},ln=class extends S.Class(`AcpUsageUpdate`)({sessionUpdate:S.Literal(`usage_update`)}){};const un=S.Union([Xt,Zt,Qt,$t,en,rn,an,on,sn,cn,ln]);S.Struct({inputTokens:S.Number,outputTokens:S.Number,cachedReadTokens:S.optional(S.NullOr(S.Number)),cachedWriteTokens:S.optional(S.NullOr(S.Number)),thoughtTokens:S.optional(S.NullOr(S.Number))});const dn=S.Literals([`claude`,`codex`,`cursor`]);var fn=class extends S.Class(`@ami/FileStat`)({relativePath:S.String,added:S.Number,removed:S.Number}){},pn=class extends S.Class(`@supervisor/GitState`)({isGitRepo:S.Boolean,currentBranch:S.String,mainBranch:S.UndefinedOr(S.String),isOnMain:S.Boolean,hasChangesFromMain:S.Boolean,hasUnstagedChanges:S.Boolean,hasBranchCommits:S.Boolean,branchCommitCount:S.Number,fileStats:S.Array(fn),workingTreeFileStats:S.Array(fn),fingerprint:S.UndefinedOr(S.String),savedFingerprint:S.UndefinedOr(S.String)}){get hasUntestedChanges(){return this.hasChangesFromMain||this.hasUnstagedChanges}get totalChangedLines(){return this.fileStats.reduce((e,t)=>e+t.added+t.removed,0)}get isCurrentStateTested(){return!this.fingerprint||!this.savedFingerprint?!1:this.fingerprint===this.savedFingerprint}};const mn=S.String.pipe(S.brand(`StepId`)),hn=S.String.pipe(S.brand(`PlanId`)),gn=S.TaggedUnion({WorkingTree:{},Branch:{mainBranch:S.String},Changes:{mainBranch:S.String},Commit:{hash:S.String}}),_n=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working tree`,Branch:()=>`branch`,Changes:()=>`changes`,Commit:({hash:e})=>e.slice(0,7)})),vn=S.Struct({number:S.Number,headRefName:S.String,author:S.Struct({login:S.String}),state:S.String,updatedAt:S.String}),yn=[`recent`,`all`,`open`,`draft`,`merged`,`no-pr`];var bn=class extends S.Class(`@supervisor/RemoteBranch`)({name:S.String,author:S.String,prNumber:S.NullOr(S.Number),prStatus:S.NullOr(S.Literals([`open`,`draft`,`merged`])),updatedAt:S.NullOr(S.String)}){static filterBranches(e,t,n){let r=e.filter(e=>t===`recent`||t===`all`?!0:t===`no-pr`?e.prStatus===null:e.prStatus===t);if(n){let e=n.toLowerCase();r=r.filter(t=>t.name.toLowerCase().includes(e))}return t===`recent`&&(r=[...r].filter(e=>e.updatedAt!==null).sort((e,t)=>{let n=new Date(e.updatedAt??0).getTime();return new Date(t.updatedAt??0).getTime()-n})),r}};const xn=S.Literals([`pending`,`active`,`passed`,`failed`,`skipped`]);var Sn=class e extends S.Class(`@supervisor/TestPlanStep`)({id:mn,title:S.String,instruction:S.String,expectedOutcome:S.String,routeHint:S.OptionFromNullOr(S.String),status:xn,summary:S.OptionFromNullOr(S.String),startedAt:S.OptionFromNullOr(S.DateTimeUtc),endedAt:S.OptionFromNullOr(S.DateTimeUtc)}){update(t){return new e({...this,...t})}},Cn=class extends S.Class(`@supervisor/TestCoverageEntry`)({path:S.String,testFiles:S.Array(S.String),covered:S.Boolean}){},wn=class extends S.Class(`@supervisor/TestCoverageReport`)({entries:S.Array(Cn),coveredCount:S.Number,totalCount:S.Number,percent:S.Number}){};const Tn=S.String.pipe(S.brand(`DraftId`));var En=class e extends S.Class(`@supervisor/TestPlanDraft`)({id:Tn,changesFor:gn,currentBranch:S.String,diffPreview:S.String,fileStats:S.Array(fn),instruction:S.String,baseUrl:S.Option(S.String),isHeadless:S.Boolean,requiresCookies:S.Boolean,testCoverage:S.Option(wn)}){update(t){return new e({...this,...t})}},Dn=class e extends En.extend(`@supervisor/TestPlan`)({id:hn,title:S.String,rationale:S.String,steps:S.Array(Sn)}){update(t){return new e({...this,...t})}updateStep(t,n){return new e({...this,steps:this.steps.map((e,r)=>r===t?n(e):e)})}get stepCount(){return this.steps.length}get resetForRerun(){return new e({...this,steps:this.steps.map(e=>new Sn({...e,status:`pending`,summary:_.none(),startedAt:_.none(),endedAt:_.none()}))})}},On=class extends S.TaggedClass()(`RunStarted`,{plan:Dn}){get id(){return`run-started-${this.plan.id}`}},kn=class extends S.TaggedClass()(`StepStarted`,{stepId:mn,title:S.String}){get id(){return`step-started-${this.stepId}`}},An=class extends S.TaggedClass()(`StepCompleted`,{stepId:mn,summary:S.String}){get id(){return`step-completed-${this.stepId}`}},jn=class extends S.TaggedClass()(`StepFailed`,{stepId:mn,message:S.String}){get id(){return`step-failed-${this.stepId}`}},Mn=class extends S.TaggedClass()(`StepSkipped`,{stepId:mn,reason:S.String}){get id(){return`step-skipped-${this.stepId}`}},Nn=class extends S.TaggedClass()(`ToolCall`,{toolName:S.String,input:S.Unknown}){get id(){return`tool-call-${this.toolName}-${JSON.stringify(this.input)}`}get displayText(){return v.isObject(this.input)&&`command`in this.input?String(this.input.command).slice(0,80):this.toolName}},Pn=class extends S.TaggedClass()(`ToolProgress`,{toolName:S.String,outputSize:S.Number}){get id(){return`tool-progress-${this.toolName}-${this.outputSize}`}},Fn=class extends S.TaggedClass()(`ToolResult`,{toolName:S.String,result:S.String,isError:S.Boolean}){get id(){return`tool-result-${this.toolName}-${this.result}`}},In=class extends S.TaggedClass()(`AgentThinking`,{text:S.String}){get id(){return`agent-thinking-${this.text}`}},Ln=class extends S.TaggedClass()(`AgentText`,{text:S.String}){get id(){return`agent-text-${this.text}`}},Rn=class extends S.TaggedClass()(`RunFinished`,{status:S.Literals([`passed`,`failed`]),summary:S.String}){get id(){return`run-finished-${this.status}`}};const zn=e=>{if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}},Bn=e=>{let t=e.indexOf(`|`);if(t===-1)return;let n=e.slice(0,t),r=e.slice(t+1),i=r.indexOf(`|`),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1);if(n===`STEP_START`)return new kn({stepId:mn.makeUnsafe(a),title:o});if(n===`STEP_DONE`)return new An({stepId:mn.makeUnsafe(a),summary:o});if(n===`ASSERTION_FAILED`)return new jn({stepId:mn.makeUnsafe(a),message:o});if(n===`STEP_SKIPPED`)return new Mn({stepId:mn.makeUnsafe(a),reason:o});if(n===`RUN_COMPLETED`)return new Rn({status:a===`failed`?`failed`:`passed`,summary:o})},Vn=S.Union([On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn]);var Hn=class extends S.TaggedClass()(`RunCompleted`,{report:S.suspend(()=>$n)}){};const Un=S.Union([On,kn,An,jn,Mn,Nn,Fn,In,Rn,Hn]);var Wn=class extends S.Class(`@supervisor/Update`)({content:Un,receivedAt:S.DateTimeUtc}){},Gn=class extends S.Class(`@supervisor/PullRequest`)({number:S.Number,url:S.String,title:S.String,headRefName:S.String}){};const Kn=S.TaggedUnion({WorkingTree:{},Branch:{branch:bn},PullRequest:{branch:bn},Commit:{hash:S.String,shortHash:S.String,subject:S.String}}),qn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working-tree`,Branch:({branch:e})=>`branch-${e.name}`,PullRequest:({branch:e})=>`pr-${e.prNumber}`,Commit:({hash:e})=>`commit-${e}`})),Jn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>`#${e.prNumber} ${e.name} ${e.author}`,Commit:({shortHash:e,subject:t})=>`${e} ${t}`})),Yn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`Local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>e.name,Commit:({shortHash:e})=>e})),Xn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`working tree`,Branch:({branch:e})=>e.author?`by ${e.author}`:``,PullRequest:({branch:e})=>`#${e.prNumber} ${e.prStatus??``}`.trim(),Commit:({subject:e})=>e})),Zn=e=>g.value(e).pipe(g.tagsExhaustive({WorkingTree:()=>`Local changes`,Branch:({branch:e})=>e.name,PullRequest:({branch:e})=>`#${e.prNumber}`,Commit:({shortHash:e})=>e}));S.TaggedUnion({Branch:{branchName:S.String}});var Qn=class e extends Dn.extend(`@supervisor/ExecutedTestPlan`)({events:S.Array(Vn)}){addEvent(t){if(t.sessionUpdate===`agent_thought_chunk`){if(t.content.type!==`text`||t.content.text===void 0)return this;let n=this.finalizeTextBlock(),r=n.events.at(-1);return r?._tag===`AgentThinking`?new e({...n,events:[...n.events.slice(0,-1),new In({text:r.text+t.content.text})]}):new e({...n,events:[...n.events,new In({text:t.content.text})]})}if(t.sessionUpdate===`agent_message_chunk`){if(t.content.type!==`text`||t.content.text===void 0)return this;let n=this.events.at(-1);return n?._tag===`AgentText`?new e({...this,events:[...this.events.slice(0,-1),new Ln({text:n.text+t.content.text})]}):new e({...this,events:[...this.events,new Ln({text:t.content.text})]})}if(t.sessionUpdate===`tool_call`){let n=this.finalizeTextBlock();return new e({...n,events:[...n.events,new Nn({toolName:t.title,input:JSON.stringify(t.rawInput??{})})]})}if(t.sessionUpdate===`tool_call_update`){let n;if(t.rawInput!==void 0){let r=[...this.events];for(let e=r.length-1;e>=0;e--){let n=r[e];if(n._tag===`ToolCall`&&n.toolName===(t.title??``)){r[e]=new Nn({toolName:n.toolName,input:JSON.stringify(t.rawInput)});break}}n=new e({...this,events:r})}let r=n??this;if(t.status===`completed`||t.status===`failed`)return new e({...r,events:[...r.events,new Fn({toolName:t.title??``,result:zn(t.rawOutput),isError:t.status===`failed`})]});if(t.rawOutput!==void 0){let n=zn(t.rawOutput).length;return new e({...r,events:[...r.events.filter(e=>!(e._tag===`ToolProgress`&&e.toolName===(t.title??``))),new Pn({toolName:t.title??``,outputSize:n})]})}return r}return this}finalizeTextBlock(){let t=this.events.at(-1);if(t?._tag!==`AgentText`)return this;let n=t.text.split(`
7
+ `).map(Bn).filter(v.isNotUndefined);if(n.length===0)return this;let r=new e({...this,events:[...this.events,...n]});for(let e of n)r=r.applyMarker(e);return r}applyMarker(t){return t._tag===`StepStarted`?this.steps.some(e=>e.id===t.stepId)?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`active`,title:t.title,startedAt:_.some(l.nowUnsafe())}):e)}):new e({...this,steps:[...this.steps,new Sn({id:t.stepId,title:t.title,instruction:t.title,expectedOutcome:``,routeHint:_.none(),status:`active`,summary:_.none(),startedAt:_.some(l.nowUnsafe()),endedAt:_.none()})]}):t._tag===`StepCompleted`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`passed`,summary:_.some(t.summary),expectedOutcome:t.summary,endedAt:_.some(l.nowUnsafe())}):e)}):t._tag===`StepFailed`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`failed`,summary:_.some(t.message),expectedOutcome:t.message,endedAt:_.some(l.nowUnsafe())}):e)}):t._tag===`StepSkipped`?new e({...this,steps:this.steps.map(e=>e.id===t.stepId?e.update({status:`skipped`,summary:_.some(t.reason),endedAt:_.some(l.nowUnsafe())}):e)}):this}get activeStep(){return this.steps.find(e=>e.status===`active`)}get completedStepCount(){return this.steps.filter(e=>e.status===`passed`||e.status===`failed`||e.status===`skipped`).length}get lastToolCallDisplayText(){let e=this.events.findLast(e=>e._tag===`ToolCall`);if(!(!e||e._tag!==`ToolCall`))return e.displayText}},$n=class extends Qn.extend(`@supervisor/TestReport`)({summary:S.String,screenshotPaths:S.Array(S.String),pullRequest:S.Option(S.suspend(()=>Gn)),testCoverageReport:S.Option(wn)}){get stepStatuses(){let e=new Map(this.steps.map(e=>[e.id,{status:`not-run`,summary:``}]));for(let t of this.events)t._tag===`StepCompleted`?e.set(t.stepId,{status:`passed`,summary:t.summary}):t._tag===`StepFailed`?e.set(t.stepId,{status:`failed`,summary:t.message}):t._tag===`StepSkipped`&&e.set(t.stepId,{status:`skipped`,summary:t.reason});return e}get status(){let e=this.stepStatuses;for(let{status:t}of e.values())if(t===`failed`)return`failed`;return`passed`}get toPlainText(){let e=this.stepStatuses,t=this.steps.filter(t=>e.get(t.id)?.status===`passed`).length,n=this.steps.filter(t=>e.get(t.id)?.status===`failed`).length,r=this.steps.filter(t=>e.get(t.id)?.status===`skipped`).length,i=this.status===`passed`?`✅`:`❌`,a=[`${t} passed`,`${n} failed`];r>0&&a.push(`${r} skipped`);let o=[`${i} ${this.title} \u2014 ${this.status.toUpperCase()}`,``,this.summary,``,`${a.join(`, `)} out of ${this.steps.length} steps`,``];for(let t of this.steps){let n=e.get(t.id),r=n?.status??`not-run`,i=r===`passed`?`✓`:r===`failed`?`✗`:r===`skipped`?`→`:`–`;o.push(` ${i} ${t.title}`),n?.summary&&o.push(` ${n.summary}`)}if(_.isSome(this.testCoverageReport)){let e=this.testCoverageReport.value;o.push(``),o.push(`Test coverage: ${e.percent}% (${e.coveredCount}/${e.totalCount} changed files have tests)`);let t=e.entries.filter(e=>!e.covered);if(t.length>0){o.push(` Untested files:`);for(let e of t)o.push(` - ${e.path}`)}}return o.join(`
8
+ `)}},er=class extends C.Service()(`@supervisor/Updates`,{make:u.gen(function*(){let e=yield*y.unbounded();return{publish:u.fn(`Updates.publish`)(function*(t){yield*y.publish(e,new Wn({content:t,receivedAt:l.nowUnsafe()}))}),stream:u.fn(`Updates.stream`)(function*(){return w.fromPubSub(e)})}})}){static layer=m.effect(this)(this.make)};const tr=S.Struct({name:S.String,value:S.String});var nr=class extends S.Class(`AgentStreamOptions`)({cwd:S.String,sessionId:S.Option(S.String),prompt:S.String,systemPrompt:S.Option(S.String),mcpEnv:S.optional(S.Array(tr))}){};const rr={authenticate:`authenticate`,initialize:`initialize`,session_cancel:`session/cancel`,session_close:`session/close`,session_fork:`session/fork`,session_list:`session/list`,session_load:`session/load`,session_new:`session/new`,session_prompt:`session/prompt`,session_resume:`session/resume`,session_set_config_option:`session/set_config_option`,session_set_mode:`session/set_mode`,session_set_model:`session/set_model`},ir={fs_read_text_file:`fs/read_text_file`,fs_write_text_file:`fs/write_text_file`,session_request_permission:`session/request_permission`,session_update:`session/update`,terminal_create:`terminal/create`,terminal_kill:`terminal/kill`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`},ar=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),terminal:K.boolean().optional().default(!1)}),or=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),label:K.string().nullish(),name:K.string(),optional:K.boolean().optional().default(!1),secret:K.boolean().optional().default(!0)}),sr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string().nullish(),id:K.string(),name:K.string()}),cr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string().nullish(),id:K.string(),link:K.string().nullish(),name:K.string(),vars:K.array(or)}),lr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),args:K.array(K.string()).optional(),description:K.string().nullish(),env:K.record(K.string(),K.string()).optional(),id:K.string(),name:K.string()}),ur=K.union([cr.and(K.object({type:K.literal(`env_var`)})),lr.and(K.object({type:K.literal(`terminal`)})),sr]),dr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),methodId:K.string()}),fr=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),pr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),blob:K.string(),mimeType:K.string().nullish(),uri:K.string()}),mr=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),hr=K.object({amount:K.number(),currency:K.string()}),gr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),terminalId:K.string()}),_r=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),newText:K.string(),oldText:K.string().nullish(),path:K.string()}),vr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),name:K.string(),value:K.string()}),yr=K.union([K.literal(-32700),K.literal(-32600),K.literal(-32601),K.literal(-32602),K.literal(-32603),K.literal(-32800),K.literal(-32e3),K.literal(-32002),K.number().int().min(-2147483648,{message:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{message:`Invalid value: Expected int32 to be <= 2147483647`})]),br=K.object({code:yr,data:K.unknown().optional(),message:K.string()}),xr=K.unknown(),Sr=K.unknown(),Cr=K.unknown(),wr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),readTextFile:K.boolean().optional().default(!1),writeTextFile:K.boolean().optional().default(!1)}),Tr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),auth:ar.optional().default({terminal:!1}),fs:wr.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:K.boolean().optional().default(!1)}),Er=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),name:K.string(),value:K.string()}),Dr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),name:K.string(),title:K.string().nullish(),version:K.string()}),Or=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),kr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cursor:K.string().nullish(),cwd:K.string().nullish()}),Ar=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),http:K.boolean().optional().default(!1),sse:K.boolean().optional().default(!1)}),jr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),headers:K.array(Er),name:K.string(),url:K.string()}),Mr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),headers:K.array(Er),name:K.string(),url:K.string()}),Nr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),args:K.array(K.string()),command:K.string(),env:K.array(vr),name:K.string()}),Pr=K.union([jr.and(K.object({type:K.literal(`http`)})),Mr.and(K.object({type:K.literal(`sse`)})),Nr]),Fr=K.string(),Ir=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string().nullish(),modelId:Fr,name:K.string()}),Lr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cwd:K.string(),mcpServers:K.array(Pr)}),Rr=K.string(),zr=K.union([K.literal(`allow_once`),K.literal(`allow_always`),K.literal(`reject_once`),K.literal(`reject_always`)]),Br=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),kind:zr,name:K.string(),optionId:Rr}),Vr=K.union([K.literal(`high`),K.literal(`medium`),K.literal(`low`)]),Hr=K.union([K.literal(`pending`),K.literal(`in_progress`),K.literal(`completed`)]),Ur=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:K.string(),priority:Vr,status:Hr}),Wr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),entries:K.array(Ur)}),Gr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),audio:K.boolean().optional().default(!1),embeddedContext:K.boolean().optional().default(!1),image:K.boolean().optional().default(!1)}),Kr=K.number().int().gte(0).lte(65535),qr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),clientCapabilities:Tr.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:Dr.nullish(),protocolVersion:Kr}),Jr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:K.string()}),Yr=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),Xr=K.union([K.number(),K.string()]).nullable();K.object({_meta:K.record(K.string(),K.unknown()).nullish(),requestId:Xr});const Zr=K.enum([`assistant`,`user`]),Qr=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),audience:K.array(Zr).nullish(),lastModified:K.string().nullish(),priority:K.number().nullish()}),$r=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),annotations:Qr.nullish(),data:K.string(),mimeType:K.string()}),ei=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),annotations:Qr.nullish(),data:K.string(),mimeType:K.string(),uri:K.string().nullish()}),ti=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),annotations:Qr.nullish(),description:K.string().nullish(),mimeType:K.string().nullish(),name:K.string(),size:K.number().nullish(),title:K.string().nullish(),uri:K.string()}),ni=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),optionId:Rr}),ri=K.union([K.object({outcome:K.literal(`cancelled`)}),ni.and(K.object({outcome:K.literal(`selected`)}))]),ii=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),outcome:ri}),ai=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),oi=K.object({currentValue:K.boolean()}),si=K.string(),ci=K.string(),li=K.union([K.literal(`mode`),K.literal(`model`),K.literal(`thought_level`),K.string()]),ui=K.string(),di=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string().nullish(),name:K.string(),value:ui}),fi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),group:si,name:K.string(),options:K.array(di)}),pi=K.union([K.array(di),K.array(fi)]),mi=K.object({currentValue:ui,options:pi}),hi=K.intersection(K.union([mi.and(K.object({type:K.literal(`select`)})),oi.and(K.object({type:K.literal(`boolean`)}))]),K.object({_meta:K.record(K.string(),K.unknown()).nullish(),category:li.nullish(),description:K.string().nullish(),id:ci,name:K.string()})),gi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi)}),_i=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),vi=K.string(),yi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi});K.object({method:K.string(),params:K.union([yi,xr]).nullish()});const bi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi}),xi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),args:K.array(K.string()).optional(),command:K.string(),cwd:K.string().nullish(),env:K.array(vr).optional(),outputByteLimit:K.number().nullish(),sessionId:vi}),Si=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cwd:K.string(),mcpServers:K.array(Pr).optional(),sessionId:vi}),Ci=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi,terminalId:K.string()}),wi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cwd:K.string(),mcpServers:K.array(Pr),sessionId:vi}),Ti=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),limit:K.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),line:K.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:K.string(),sessionId:vi}),Ei=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi,terminalId:K.string()}),Di=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cwd:K.string(),mcpServers:K.array(Pr).optional(),sessionId:vi}),Oi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cwd:K.string(),sessionId:vi,title:K.string().nullish(),updatedAt:K.string().nullish()}),ki=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),nextCursor:K.string().nullish(),sessions:K.array(Oi)}),Ai=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),title:K.string().nullish(),updatedAt:K.string().nullish()}),ji=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),Mi=K.string(),Ni=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),currentModeId:Mi}),Pi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string().nullish(),id:Mi,name:K.string()}),Fi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),availableModes:K.array(Pi),currentModeId:Mi}),Ii=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),availableModels:K.array(Ir),currentModelId:Fr}),Li=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi).nullish(),models:Ii.nullish(),modes:Fi.nullish(),sessionId:vi}),Ri=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi).nullish(),models:Ii.nullish(),modes:Fi.nullish()}),zi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi).nullish(),models:Ii.nullish(),modes:Fi.nullish(),sessionId:vi}),Bi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi).nullish(),models:Ii.nullish(),modes:Fi.nullish()}),Vi=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),Hi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),close:ai.nullish(),fork:_i.nullish(),list:ji.nullish(),resume:Vi.nullish()}),Ui=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),loadSession:K.boolean().optional().default(!1),mcpCapabilities:Ar.optional().default({http:!1,sse:!1}),promptCapabilities:Gr.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:Hi.optional().default({})}),Wi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),agentCapabilities:Ui.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:Dr.nullish(),authMethods:K.array(ur).optional().default([]),protocolVersion:Kr}),Gi=K.intersection(K.union([K.object({type:K.literal(`boolean`),value:K.boolean()}),K.object({value:ui})]),K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configId:ci,sessionId:vi})),Ki=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),configOptions:K.array(hi)}),qi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),modeId:Mi,sessionId:vi}),Ji=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),Yi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),modelId:Fr,sessionId:vi}),Xi=K.object({_meta:K.record(K.string(),K.unknown()).nullish()}),Zi=K.union([K.literal(`end_turn`),K.literal(`max_tokens`),K.literal(`max_turn_requests`),K.literal(`refusal`),K.literal(`cancelled`)]),Qi=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),terminalId:K.string()}),$i=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),exitCode:K.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:K.string().nullish()}),ea=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi,terminalId:K.string()}),ta=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),exitStatus:$i.nullish(),output:K.string(),truncated:K.boolean()}),na=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),annotations:Qr.nullish(),text:K.string()}),ra=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),mimeType:K.string().nullish(),text:K.string(),uri:K.string()}),ia=K.union([ra,pr]),aa=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),annotations:Qr.nullish(),resource:ia}),oa=K.union([na.and(K.object({type:K.literal(`text`)})),ei.and(K.object({type:K.literal(`image`)})),$r.and(K.object({type:K.literal(`audio`)})),ti.and(K.object({type:K.literal(`resource_link`)})),aa.and(K.object({type:K.literal(`resource`)}))]),sa=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:oa}),ca=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:oa,messageId:K.string().nullish()}),la=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),messageId:K.string().nullish(),prompt:K.array(oa),sessionId:vi});K.object({id:Xr,method:K.string(),params:K.union([qr,dr,Lr,wi,kr,Si,Di,bi,qi,Gi,la,Yi,Sr]).nullish()});const ua=K.union([sa.and(K.object({type:K.literal(`content`)})),_r.and(K.object({type:K.literal(`diff`)})),Qi.and(K.object({type:K.literal(`terminal`)}))]),da=K.string(),fa=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),line:K.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),path:K.string()}),pa=K.union([K.literal(`pending`),K.literal(`in_progress`),K.literal(`completed`),K.literal(`failed`)]),ma=K.union([K.literal(`read`),K.literal(`edit`),K.literal(`delete`),K.literal(`move`),K.literal(`search`),K.literal(`execute`),K.literal(`think`),K.literal(`fetch`),K.literal(`switch_mode`),K.literal(`other`)]),ha=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:K.array(ua).optional(),kind:ma.optional(),locations:K.array(fa).optional(),rawInput:K.unknown().optional(),rawOutput:K.unknown().optional(),status:pa.optional(),title:K.string(),toolCallId:da}),ga=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:K.array(ua).nullish(),kind:ma.nullish(),locations:K.array(fa).nullish(),rawInput:K.unknown().optional(),rawOutput:K.unknown().optional(),status:pa.nullish(),title:K.string().nullish(),toolCallId:da}),_a=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),options:K.array(Br),sessionId:vi,toolCall:ga}),va=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),hint:K.string()}),ya=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),description:K.string(),input:va.nullish(),name:K.string()}),ba=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),availableCommands:K.array(ya)}),xa=K.object({cachedReadTokens:K.number().nullish(),cachedWriteTokens:K.number().nullish(),inputTokens:K.number(),outputTokens:K.number(),thoughtTokens:K.number().nullish(),totalTokens:K.number()}),Sa=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),stopReason:Zi,usage:xa.nullish(),userMessageId:K.string().nullish()});K.union([K.object({id:Xr,result:K.union([Wi,fr,zi,Ri,ki,Li,Bi,mr,Ji,Ki,Sa,Xi,Cr])}),K.object({error:br,id:Xr})]);const Ca=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),cost:hr.nullish(),size:K.number(),used:K.number()}),wa=K.union([ca.and(K.object({sessionUpdate:K.literal(`user_message_chunk`)})),ca.and(K.object({sessionUpdate:K.literal(`agent_message_chunk`)})),ca.and(K.object({sessionUpdate:K.literal(`agent_thought_chunk`)})),ha.and(K.object({sessionUpdate:K.literal(`tool_call`)})),ga.and(K.object({sessionUpdate:K.literal(`tool_call_update`)})),Wr.and(K.object({sessionUpdate:K.literal(`plan`)})),ba.and(K.object({sessionUpdate:K.literal(`available_commands_update`)})),Ni.and(K.object({sessionUpdate:K.literal(`current_mode_update`)})),gi.and(K.object({sessionUpdate:K.literal(`config_option_update`)})),Ai.and(K.object({sessionUpdate:K.literal(`session_info_update`)})),Ca.and(K.object({sessionUpdate:K.literal(`usage_update`)}))]),Ta=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi,update:wa});K.object({method:K.string(),params:K.union([Ta,xr]).nullish()});const Ea=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),sessionId:vi,terminalId:K.string()}),Da=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),exitCode:K.number().int().gte(0).max(4294967295,{message:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),signal:K.string().nullish()}),Oa=K.object({_meta:K.record(K.string(),K.unknown()).nullish(),content:K.string(),path:K.string(),sessionId:vi});K.object({id:Xr,method:K.string(),params:K.union([Oa,Ti,_a,xi,ea,Ei,Ea,Ci,Sr]).nullish()});const ka=K.object({_meta:K.record(K.string(),K.unknown()).nullish()});K.union([K.object({id:Xr,result:K.union([ka,Jr,ii,gr,ta,Yr,Da,Or,Cr])}),K.object({error:br,id:Xr})]);function Aa(e,t){let n=new TextEncoder,r=new TextDecoder;return{readable:new ReadableStream({async start(e){let n=``,i=t.getReader();try{for(;;){let{value:t,done:a}=await i.read();if(a)break;if(!t)continue;n+=r.decode(t,{stream:!0});let o=n.split(`
9
9
  `);n=o.pop()||``;for(let t of o){let n=t.trim();if(n)try{let t=JSON.parse(n);e.enqueue(t)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}}}}finally{i.releaseLock(),e.close()}}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
10
- `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}Symbol.asyncDispose;var Aa=class{#e;constructor(e,t){let n=e(this);this.#e=new ja(async(e,t)=>{switch(e){case rr.fs_write_text_file:{let e=Da.parse(t);return n.writeTextFile?.(e)}case rr.fs_read_text_file:{let e=wi.parse(t);return n.readTextFile?.(e)}case rr.session_request_permission:{let e=ga.parse(t);return n.requestPermission(e)}case rr.terminal_create:{let e=bi.parse(t);return n.createTerminal?.(e)}case rr.terminal_output:{let e=$i.parse(t);return n.terminalOutput?.(e)}case rr.terminal_release:{let e=Ti.parse(t);return await n.releaseTerminal?.(e)??{}}case rr.terminal_wait_for_exit:{let e=Ta.parse(t);return n.waitForTerminalExit?.(e)}case rr.terminal_kill:{let e=Si.parse(t);return await n.killTerminal?.(e)??{}}default:if(n.extMethod)return n.extMethod(e,t);throw Ma.methodNotFound(e)}},async(e,t)=>{switch(e){case rr.session_update:{let e=wa.parse(t);return n.sessionUpdate(e)}default:if(n.extNotification)return n.extNotification(e,t);throw Ma.methodNotFound(e)}},t)}async initialize(e){return await this.#e.sendRequest(nr.initialize,e)}async newSession(e){return await this.#e.sendRequest(nr.session_new,e)}async loadSession(e){return await this.#e.sendRequest(nr.session_load,e)??{}}async unstable_forkSession(e){return await this.#e.sendRequest(nr.session_fork,e)}async listSessions(e){return await this.#e.sendRequest(nr.session_list,e)}async unstable_resumeSession(e){return await this.#e.sendRequest(nr.session_resume,e)}async unstable_closeSession(e){return await this.#e.sendRequest(nr.session_close,e)}async setSessionMode(e){return await this.#e.sendRequest(nr.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.#e.sendRequest(nr.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.#e.sendRequest(nr.session_set_config_option,e)}async authenticate(e){return await this.#e.sendRequest(nr.authenticate,e)??{}}async prompt(e){return await this.#e.sendRequest(nr.session_prompt,e)}async cancel(e){return await this.#e.sendNotification(nr.session_cancel,e)}async extMethod(e,t){return await this.#e.sendRequest(e,t)}async extNotification(e,t){return await this.#e.sendNotification(e,t)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},ja=class{#e=new Map;#t=0;#n;#r;#i;#a=Promise.resolve();#o=new AbortController;#s;constructor(e,t,n){this.#n=e,this.#r=t,this.#i=n,this.#s=new Promise(e=>{this.#o.signal.addEventListener(`abort`,()=>e())}),this.#c()}get signal(){return this.#o.signal}get closed(){return this.#s}async#c(){let e=this.#i.readable.getReader();try{for(;;){let{value:t,done:n}=await e.read();if(n)break;if(t)try{this.#l(t)}catch(e){console.error(`Unexpected error during message processing:`,t,e),`id`in t&&t.id!==void 0&&this.#p({jsonrpc:`2.0`,id:t.id,error:{code:-32700,message:`Parse error`}})}}}finally{e.releaseLock(),this.#o.abort()}}async#l(e){if(`method`in e&&`id`in e){let t=await this.#u(e.method,e.params);`error`in t&&console.error(`Error handling request`,e,t.error),await this.#p({jsonrpc:`2.0`,id:e.id,...t})}else if(`method`in e){let t=await this.#d(e.method,e.params);`error`in t&&console.error(`Error handling notification`,e,t.error)}else `id`in e?this.#f(e):console.error(`Invalid message`,{message:e})}async#u(e,t){try{return{result:await this.#n(e,t)??null}}catch(e){if(e instanceof Ma)return e.toResult();if(e instanceof ge.ZodError)return Ma.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return Ma.internalError(t?JSON.parse(t):{}).toResult()}catch{return Ma.internalError({details:t}).toResult()}}}async#d(e,t){try{return await this.#r(e,t),{result:null}}catch(e){if(e instanceof Ma)return e.toResult();if(e instanceof ge.ZodError)return Ma.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return Ma.internalError(t?JSON.parse(t):{}).toResult()}catch{return Ma.internalError({details:t}).toResult()}}}#f(e){let t=this.#e.get(e.id);t?(`result`in e?t.resolve(e.result):`error`in e&&t.reject(e.error),this.#e.delete(e.id)):console.error(`Got response to unknown request`,e.id)}async sendRequest(e,t){let n=this.#t++,r=new Promise((e,t)=>{this.#e.set(n,{resolve:e,reject:t})});return await this.#p({jsonrpc:`2.0`,id:n,method:e,params:t}),r}async sendNotification(e,t){await this.#p({jsonrpc:`2.0`,method:e,params:t})}async#p(e){return this.#a=this.#a.then(async()=>{let t=this.#i.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{console.error(`ACP write error:`,e)}),this.#a}},Ma=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};const Na=v.compose(v.isObject,v.compose(v.hasProperty(`message`),v.Struct({message:v.isString}))),Pa=S.String.pipe(S.brand(`SessionId`));var Fa=class extends S.ErrorClass(`AcpStreamError`)({_tag:S.tag(`AcpStreamError`),cause:S.Unknown}){displayName=`An unexpected error occurred while streaming`;message=`Streaming failed: ${this.cause}`},Ia=class extends S.ErrorClass(`AcpProviderNotInstalledError`)({_tag:S.tag(`AcpProviderNotInstalledError`),provider:un}){displayName=`${ee.capitalize(this.provider)} is not installed`;message=g.value(this.provider).pipe(g.when(`claude`,()=>"Claude Code is not installed. Install it from https://code.claude.com/docs/en/overview#native-install-recommended, or use codex agent with `expect -a codex`."),g.when(`codex`,()=>"Codex CLI is not installed. Install it with `npm install -g @openai/codex`, or use Claude Code by removing the `--agent codex` option."),g.orElse(()=>`Your coding agent CLI is not installed. Please install it and then re-run expect.`))},La=class extends S.ErrorClass(`AcpProviderUnauthenticatedError`)({_tag:S.tag(`AcpProviderUnauthenticatedError`),provider:un}){displayName=`Your ${this.provider} agent is not authenticated`;message=g.value(this.provider).pipe(g.when(`claude`,()=>"Please log in using `claude login`, and then re-run expect."),g.when(`codex`,()=>"Please log in using `codex login`, and then re-run expect."),g.orElse(()=>`Please sign in to your coding agent, and then re-run expect.`))},Ra=class extends S.ErrorClass(`AcpProviderUsageLimitError`)({_tag:S.tag(`AcpProviderUsageLimitError`),provider:un}){displayName=`Your ${this.provider} agent has exceeded its usage limits`;message=`Usage limits exceeded for ${this.provider}. Please check your plan and billing.`},za=class extends S.ErrorClass(`AcpSessionCreateError`)({_tag:S.tag(`AcpSessionCreateError`),cause:S.Unknown}){displayName=`Creating a chat session failed`;message=`Creating session failed: ${s.pretty(s.fail(this.cause))}`},Ba=class extends S.ErrorClass(`AcpConnectionInitError`)({_tag:S.tag(`AcpConnectionInitError`),cause:S.Unknown}){message=`Init connection failed: ${this.cause}`},Va=class extends S.ErrorClass(`AcpAdapterNotFoundError`)({_tag:S.tag(`AcpAdapterNotFoundError`),packageName:S.String,cause:S.Unknown}){message=`ACP adapter not found: ${this.packageName}. Error: ${s.pretty(s.fail(this.cause))}`},Ha=class e extends C.Service()(`@expect/AcpAdapter`){static layerCodex=m.effect(e)(u.try({try:()=>{let t=a(typeof __filename<`u`?__filename:import.meta.url).resolve(`@zed-industries/codex-acp/bin/codex-acp.js`);return e.of({provider:`codex`,bin:process.execPath,args:[t],env:{}})},catch:e=>new Va({packageName:`@zed-industries/codex-acp`,cause:e})}));static layerClaude=m.effect(e)(u.gen(function*(){let t=yield*ve.ChildProcessSpawner,n=S.Struct({loggedIn:S.Boolean});return yield*_e.make(`claude`,[`auth`,`status`]).pipe(t.string,u.flatMap(S.decodeEffect(S.fromJsonString(n))),u.flatMap(({loggedIn:e})=>e?u.void:new La({provider:`claude`}).asEffect()),u.catchReason(`PlatformError`,`NotFound`,()=>new Ia({provider:`claude`}).asEffect())),yield*u.try({try:()=>{let t=a(typeof __filename<`u`?__filename:import.meta.url).resolve(`@zed-industries/claude-agent-acp/dist/index.js`);return e.of({provider:`claude`,bin:process.execPath,args:[t],env:{}})},catch:e=>new Va({packageName:`@zed-industries/claude-agent-acp`,cause:e})})})).pipe(m.provide(ye.layer))},Ua=class extends C.Service()(`@expect/AcpClient`,{make:u.gen(function*(){let e=yield*Ha;yield*u.annotateLogsScoped({adapter:e.args[0]}),yield*u.logInfo(`Initializing AcpClient`);let t=yield*ve.ChildProcessSpawner,n=yield*f.make(),r=yield*b.unbounded(),i=new Map,a={requestPermission:e=>Promise.resolve({outcome:{outcome:`selected`,optionId:e.options.find(e=>e.kind===`allow_always`||e.kind===`allow_once`)?.optionId??e.options[0].optionId}}),sessionUpdate:async({sessionId:e,update:t})=>{let n=i.get(Pa.makeUnsafe(e));if(n===void 0)return console.warn(`updates queue not found for session ${e}`);let r=S.decodeUnknownSync(ln)(t);b.offerUnsafe(n,r)}},o=yield*_e.make(e.bin,e.args,{env:e.env}).pipe(t.spawn);yield*u.annotateLogsScoped({pid:o.pid}),yield*u.logDebug(`ACP adapter subprocess spawned`),yield*w.fromQueue(r).pipe(w.run(o.stdin),u.forkScoped);let s=w.toReadableStream(o.stdout),c=new Aa(e=>a,ka(new WritableStream({write:e=>void b.offerUnsafe(r,e)}),s)),l=me(new URL(`./browser-mcp.js`,import.meta.url)),d=e=>[{command:process.execPath,args:[l],env:[...e],name:`browser`}],p=yield*u.tryPromise({try:()=>c.initialize({protocolVersion:1}),catch:e=>new Ba({cause:e})});yield*u.logInfo(`ACP connection initialized`,{capabilities:p.agentCapabilities});let m=u.fn(`AcpClient.createSession`)(function*(t,n=[]){yield*u.annotateCurrentSpan({cwd:t});let r=d(n);return yield*u.tryPromise({try:()=>c.newSession({cwd:t,mcpServers:r}),catch:t=>{let n=Na(t)?t.message:String(t);return[`authentication`].some(e=>n.toLowerCase().includes(e))?new La({provider:e.provider}):[`out of usage`,`limits exceeded`,`usage exceeded`].some(e=>n.toLowerCase().includes(e))?new Ra({provider:e.provider}):new za({cause:t})}}).pipe(u.map(({sessionId:e})=>Pa.makeUnsafe(e)),u.tap(e=>u.gen(function*(){let t=yield*b.unbounded();i.set(e,t),yield*u.logInfo(`ACP session created`,{sessionId:e})})))}),h=u.fn(`AcpClient.getQueueBySessionId`)(function*(e){if(!i.has(e))return yield*u.die(`Session ${e} not initialized, did you forget to call createSession?`);let t=yield*b.unbounded();return i.set(e,t),t});return{createSession:m,stream:u.fn(`AcpClient.stream`)(function*({prompt:e,sessionId:t,cwd:r,mcpEnv:i=[]}){let a=_.isSome(t)?t.value:yield*m(r,i);yield*u.logDebug(`ACP stream starting`,{sessionId:a});let o=yield*h(a);return yield*u.tryPromise({try:()=>c.prompt({sessionId:a,prompt:[{type:`text`,text:e}]}),catch:e=>new Fa({cause:e})}).pipe(u.tap(()=>u.logDebug(`ACP prompt completed`)),u.tap(()=>b.end(o)),f.run(n,a,{startImmediately:!0})),w.fromQueue(o)},w.unwrap)}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer));static layerCodex=this.layer.pipe(m.provide(Ha.layerCodex));static layerClaude=this.layer.pipe(m.provide(Ha.layerClaude))},Wa=class e extends C.Service()(`@expect/Agent`){static layerAcp=m.effect(e)(u.gen(function*(){let t=yield*Ua;return e.of({createSession:e=>t.createSession(e),stream:e=>t.stream({cwd:e.cwd,sessionId:_.map(e.sessionId,e=>e),prompt:e.prompt,mcpEnv:e.mcpEnv})})})).pipe(m.provide(Ua.layer));static layerCodex=e.layerAcp.pipe(m.provide(Ha.layerCodex));static layerClaude=e.layerAcp.pipe(m.provide(Ha.layerClaude));static layerFor=t=>t===`claude`?e.layerClaude:e.layerCodex;static layerTest=t=>m.effect(e,u.gen(function*(){let n=yield*p.FileSystem,r=S.decodeSync(ln);return e.of({stream:()=>n.stream(t).pipe(w.decodeText(),w.splitLines,w.map(e=>r(JSON.parse(e))),w.orDie),createSession:()=>u.die(`createSession not supported for test layer`)})})).pipe(m.provide(ye.layer))};const Ga=[`claude`,`codex`,`cursor`],Ka=process.platform===`win32`?`where`:`which`,qa=e=>{try{return ce(`${Ka} ${e}`,{stdio:`pipe`}),!0}catch{return!1}},Ja=()=>Ga.filter(qa),Ya=12e3,Xa=e=>e?[`Saved flow guidance:`,`You are replaying a previously saved flow. Follow these steps as guidance, but adapt if the UI has changed.`,`Saved flow title: ${e.title}`,`Saved flow request: ${e.userInstruction}`,``,...e.steps.flatMap((e,t)=>[`Step ${t+1}: ${e.title}`,`Instruction: ${e.instruction}`,`Expected: ${e.expectedOutcome}`,``])]:[],Za=e=>{switch(e){case`Commit`:return[`- Start narrow and prove the selected commit's intended change works first.`,`- Treat the selected commit and its touched files as the primary testing hypothesis.`,`- After the primary flow, test 2-4 adjacent flows that could regress from the same change. Think about what else touches the same components, routes, or data.`,`- For UI changes, verify related views that render the same data or share the same components.`];case`WorkingTree`:return[`- Start with the exact user-requested flow against the local in-progress changes.`,`- After the primary flow, test related flows that exercise the same code paths — aim for 2-3 follow-ups.`,`- Pay extra attention to partially-implemented features: check that incomplete states don't break existing behavior.`];case`Changes`:return[`- Treat committed and uncommitted work as one body of change.`,`- Cover the requested flow first, then the highest-risk adjacent flows.`,`- Test 2-4 follow-up flows, prioritizing paths that share components or data with the changed files.`,`- If the changes touch shared utilities or layouts, verify multiple pages that use them.`];default:return[`- This is a branch-level review — be thorough. The goal is to catch regressions before merge, not to do a quick spot-check.`,`- Cover the requested flow first, then systematically test each area affected by the changed files.`,`- Aim for 5-8 total tested flows. Derive them from the changed files: each changed route, component, or data path should get its own verification.`,`- Test cross-cutting concerns: if shared components, layouts, or utilities changed, verify them on multiple pages that consume them.`,`- Include at least one negative/edge-case flow (e.g. invalid input, empty state, unauthorized access, broken link) relevant to the changes.`,`- Do not stop after the happy path passes. The value of a branch review is catching what the developer might have missed.`]}},Qa=e=>{if(!e||e.totalCount===0)return[];let t=[`Test coverage of changed files: ${e.percent}% (${e.coveredCount}/${e.totalCount} files have tests)`],n=e.entries.filter(e=>e.covered),r=e.entries.filter(e=>!e.covered);for(let e of n)t.push(` [covered] ${e.path} (tested by: ${e.testFiles.slice(0,3).join(`, `)})`);for(let e of r)t.push(` [no test] ${e.path}`);return r.length>0&&t.push(`Prioritize browser-testing files WITHOUT existing test coverage.`),t.push(``),t},$a=e=>{let t=e.browserMcpServerName??`browser`,n=e.changedFiles.slice(0,12),r=e.recentCommits.slice(0,5),i=e.diffPreview||``,a=i.length>Ya?i.slice(0,Ya)+`
11
- ... (truncated)`:i;return[`You are executing a browser regression test directly from repository context.`,`You have browser tools via the MCP server named "${t}":`,``,`1. open — Launch a browser and navigate to a URL.`,`2. playwright — Execute Playwright code in Node. Globals: page (Page), context (BrowserContext), browser (Browser), ref(id) (resolves a snapshot ref like 'e4' to a Playwright Locator). Supports await. Return a value to get it back as JSON.`,`3. screenshot — Capture page state. Set mode: 'snapshot' (ARIA accessibility tree, default and preferred), 'screenshot' (PNG image), or 'annotated' (PNG with numbered labels on interactive elements).`,`4. console_logs — Get browser console messages. Filter by type ('error', 'warning', 'log'). Use after navigation or interactions to catch errors.`,`5. network_requests — Get captured network requests. Filter by method, URL substring, or resource type ('xhr', 'fetch', 'document').`,`6. close — Close the browser and end the session.`,``,`Strongly prefer screenshot with mode 'snapshot' for observing page state — the ARIA tree is fast, cheap, and sufficient for almost all assertions.`,`Only use mode 'screenshot' or 'annotated' when you need to verify something purely visual (layout, colors, images) that the accessibility tree cannot capture.`,`After each step, check console_logs with type 'error' to catch unexpected errors.`,``,`Snapshot-driven workflow:`,`1. Call screenshot with mode 'snapshot' to get the ARIA tree with refs.`,`2. Read the tree to find your target elements. Every interactive element has a ref like [ref=e4].`,`3. Use ref() in one playwright call to perform multiple actions using the refs from the snapshot — fill forms, click buttons, wait, and return results all in one block.`,`4. Only take a new snapshot when the page structure has changed significantly (navigation, modal open, new content loaded) and you need fresh refs.`,``,`Example snapshot tree:`,` - navigation`,` - link "Home" [ref=e1]`,` - link "About" [ref=e2]`,` - main`,` - heading "Welcome"`,` - textbox "Email" [ref=e3]`,` - button "Submit" [ref=e4]`,``,`Acting on refs — use ref() to get a Locator directly from the snapshot ref ID:`,` await ref('e3').fill('test@example.com');`,` await ref('e4').click();`,` await ref('e1').click();`,``,`Always snapshot first, then use ref() to act. Never guess CSS selectors.`,``,`Batch as many actions as possible into a single playwright call to minimize round trips:`,` playwright: await ref('e3').fill('test@example.com'); await ref('e5').fill('secret'); await ref('e6').click(); await page.waitForLoadState('networkidle'); return await page.innerText('.result');`,` playwright: await ref('e1').click(); await page.waitForURL('**/about');`,` playwright: return { url: page.url(), title: await page.title() };`,``,`Execution strategy:`,`- First master the primary flow the developer asked for. Verify it thoroughly before moving on.`,`- Once the primary flow passes, test additional related flows suggested by the changed files and route context. The scope strategy below specifies how many — follow it.`,`- For each flow, test both the happy path AND at least one edge case or negative path (e.g. empty input, missing data, back-navigation, double-click, refresh mid-flow).`,`- Use the same browser session throughout unless the app forces you into a different path.`,`- Execution style is assertion-first: navigate, act, validate, recover once, then fail with evidence if still blocked.`,`- Create your own step structure while executing. Use stable sequential IDs like step-01, step-02, step-03.`,`- Take your time. A thorough run that catches real issues is more valuable than a fast run that misses them. Do not rush to RUN_COMPLETED.`,``,`Assertion depth — do not just confirm the page loaded. For each step, verify that the action produced the expected state change:`,`- Before acting, note what should change. After acting, confirm it actually changed.`,`- Check at least two independent signals per step (e.g. URL changed AND new content appeared, or item was added AND count updated).`,`- Verify absence when relevant: after a delete, the item is gone; after dismissing a modal, it no longer appears in the tree.`,`- Use playwright to return structured evidence rather than eyeballing snapshots: return { url: page.url(), title: await page.title(), visible: await ref('e5').isVisible() };`,`- If the changed files suggest specific behavior (e.g. a validation rule, a redirect, a computed value), test that specific behavior rather than just the surrounding UI.`,``,`Before and after each step, emit these exact status lines on their own lines:`,`STEP_START|<step-id>|<step-title>`,`STEP_DONE|<step-id>|<short-summary>`,`ASSERTION_FAILED|<step-id>|<why-it-failed>`,`STEP_SKIPPED|<step-id>|<reason-it-was-skipped>`,`RUN_COMPLETED|passed|<final-summary>`,`RUN_COMPLETED|failed|<final-summary>`,``,`Use STEP_SKIPPED when a step cannot be executed due to missing prerequisites (e.g. test credentials not available, required test data missing, auth-blocked). Never use STEP_DONE for steps that were not actually tested.`,``,`Allowed failure categories: app-bug, env-issue, auth-blocked, missing-test-data, selector-drift, agent-misread.`,`When a step fails, gather structured evidence before emitting ASSERTION_FAILED:`,`- Call screenshot with mode 'snapshot' to capture the ARIA tree.`,`- Use playwright to gather diagnostics: return { url: page.url(), title: await page.title(), text: await page.innerText('body').then(t => t.slice(0, 500)) };`,`- Only take a visual screenshot if the failure might be layout/rendering related.`,`- Summarize the failure category and the most important evidence inside <why-it-failed>.`,``,`Stability heuristics:`,`- After navigation or major UI changes, use playwright to wait for the page to settle (e.g. await page.waitForLoadState('networkidle')).`,`- Use screenshot with mode 'snapshot' to inspect the accessibility tree before interactions that depend on current UI state.`,`- Avoid interacting while the UI is visibly loading or transitioning.`,`- Confirm you reached the expected page or route before continuing.`,`- When waiting for page changes (navigation, content loading, animations), prefer short incremental waits (1-3 seconds) with snapshot checks in between rather than a single long wait. For example, instead of waiting 10 seconds: wait 2s, take a snapshot, check if ready, if not wait 2s more and snapshot again. This lets you proceed as soon as the page is ready.`,``,`Recovery policy for each blocked step:`,`- Take a new snapshot to re-inspect the page and get fresh refs.`,`- Use playwright with ref() to scroll the target into view or retry the interaction once.`,`- If still blocked, classify the blocker with one allowed failure category and include that classification in ASSERTION_FAILED.`,``,`Avoid rabbit holes:`,`- Do not repeat the same failing action more than once without new evidence such as a fresh snapshot, a different ref, a changed page state, or a clear new hypothesis.`,`- If four attempts fail or progress stalls, stop acting and report what you observed, what blocked progress, and the most likely next step.`,`- Prefer gathering evidence over brute force. If the page is confusing, use screenshot with mode 'snapshot', playwright for console or network diagnostics, or a visual screenshot to understand it before trying more actions.`,`- If you encounter a blocker such as login, passkey/manual user interaction, permissions, captchas, destructive confirmations, missing data, or an unexpected state, stop and report it instead of improvising repeated actions.`,`- Do not get stuck in wait-action-wait loops. Every retry should be justified by something newly observed.`,``,`Before emitting RUN_COMPLETED, call the close tool exactly once so the browser session flushes the video to disk.`,``,`Environment:`,`- Base URL: ${e.baseUrl??`not provided`}`,`- Headed mode preference: ${e.isHeadless?`headless`:`headed`}`,`- Reuse browser cookies: ${e.requiresCookies?`yes`:`no`}`,``,`Testing target context:`,`- Scope: ${e.scope}`,`- Current branch: ${e.currentBranch}`,`- Main branch: ${e.mainBranch??`unknown`}`,``,`Developer request:`,e.userInstruction,``,...Xa(e.savedFlow),`Project learnings from previous runs:`,e.learnings?.trim()||`No learnings yet.`,``,`Changed files:`,n.length>0?n.map(e=>`- [${e.status}] ${e.path}`).join(`
12
- `):`- No changed files detected`,``,...Qa(e.testCoverage),`Recent commits:`,r.length>0?r.map(e=>`- ${e.shortHash} ${e.subject}`).join(`
13
- `):`- No recent commits available`,``,`Diff preview:`,a||`No diff preview available`,``,`Scope strategy:`,...Za(e.scope)].join(`
14
- `)};var eo=n(((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`:``)}})),to=n(((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=eo(),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})),no=n(((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=to()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),ro=n(((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)}})),io=n(((t,n)=>{let r=e(`os`),i=e(`tty`),a=ro(),{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 n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.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:n;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:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),ao=n(((t,n)=>{let r=e(`tty`),i=e(`util`);t.init=d,t.log=c,t.formatArgs=o,t.save=l,t.load=u,t.useColors=a,t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let e=io();e&&(e.stderr||e).level>=2&&(t.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{}t.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 a(){return`colors`in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
10
+ `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}Symbol.asyncDispose;var ja=class{#e;constructor(e,t){let n=e(this);this.#e=new Ma(async(e,t)=>{switch(e){case ir.fs_write_text_file:{let e=Oa.parse(t);return n.writeTextFile?.(e)}case ir.fs_read_text_file:{let e=Ti.parse(t);return n.readTextFile?.(e)}case ir.session_request_permission:{let e=_a.parse(t);return n.requestPermission(e)}case ir.terminal_create:{let e=xi.parse(t);return n.createTerminal?.(e)}case ir.terminal_output:{let e=ea.parse(t);return n.terminalOutput?.(e)}case ir.terminal_release:{let e=Ei.parse(t);return await n.releaseTerminal?.(e)??{}}case ir.terminal_wait_for_exit:{let e=Ea.parse(t);return n.waitForTerminalExit?.(e)}case ir.terminal_kill:{let e=Ci.parse(t);return await n.killTerminal?.(e)??{}}default:if(n.extMethod)return n.extMethod(e,t);throw Na.methodNotFound(e)}},async(e,t)=>{switch(e){case ir.session_update:{let e=Ta.parse(t);return n.sessionUpdate(e)}default:if(n.extNotification)return n.extNotification(e,t);throw Na.methodNotFound(e)}},t)}async initialize(e){return await this.#e.sendRequest(rr.initialize,e)}async newSession(e){return await this.#e.sendRequest(rr.session_new,e)}async loadSession(e){return await this.#e.sendRequest(rr.session_load,e)??{}}async unstable_forkSession(e){return await this.#e.sendRequest(rr.session_fork,e)}async listSessions(e){return await this.#e.sendRequest(rr.session_list,e)}async unstable_resumeSession(e){return await this.#e.sendRequest(rr.session_resume,e)}async unstable_closeSession(e){return await this.#e.sendRequest(rr.session_close,e)}async setSessionMode(e){return await this.#e.sendRequest(rr.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.#e.sendRequest(rr.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.#e.sendRequest(rr.session_set_config_option,e)}async authenticate(e){return await this.#e.sendRequest(rr.authenticate,e)??{}}async prompt(e){return await this.#e.sendRequest(rr.session_prompt,e)}async cancel(e){return await this.#e.sendNotification(rr.session_cancel,e)}async extMethod(e,t){return await this.#e.sendRequest(e,t)}async extNotification(e,t){return await this.#e.sendNotification(e,t)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},Ma=class{#e=new Map;#t=0;#n;#r;#i;#a=Promise.resolve();#o=new AbortController;#s;constructor(e,t,n){this.#n=e,this.#r=t,this.#i=n,this.#s=new Promise(e=>{this.#o.signal.addEventListener(`abort`,()=>e())}),this.#c()}get signal(){return this.#o.signal}get closed(){return this.#s}async#c(){let e=this.#i.readable.getReader();try{for(;;){let{value:t,done:n}=await e.read();if(n)break;if(t)try{this.#l(t)}catch(e){console.error(`Unexpected error during message processing:`,t,e),`id`in t&&t.id!==void 0&&this.#p({jsonrpc:`2.0`,id:t.id,error:{code:-32700,message:`Parse error`}})}}}finally{e.releaseLock(),this.#o.abort()}}async#l(e){if(`method`in e&&`id`in e){let t=await this.#u(e.method,e.params);`error`in t&&console.error(`Error handling request`,e,t.error),await this.#p({jsonrpc:`2.0`,id:e.id,...t})}else if(`method`in e){let t=await this.#d(e.method,e.params);`error`in t&&console.error(`Error handling notification`,e,t.error)}else `id`in e?this.#f(e):console.error(`Invalid message`,{message:e})}async#u(e,t){try{return{result:await this.#n(e,t)??null}}catch(e){if(e instanceof Na)return e.toResult();if(e instanceof _e.ZodError)return Na.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return Na.internalError(t?JSON.parse(t):{}).toResult()}catch{return Na.internalError({details:t}).toResult()}}}async#d(e,t){try{return await this.#r(e,t),{result:null}}catch(e){if(e instanceof Na)return e.toResult();if(e instanceof _e.ZodError)return Na.invalidParams(e.format()).toResult();let t;(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)&&(t=e.message);try{return Na.internalError(t?JSON.parse(t):{}).toResult()}catch{return Na.internalError({details:t}).toResult()}}}#f(e){let t=this.#e.get(e.id);t?(`result`in e?t.resolve(e.result):`error`in e&&t.reject(e.error),this.#e.delete(e.id)):console.error(`Got response to unknown request`,e.id)}async sendRequest(e,t){let n=this.#t++,r=new Promise((e,t)=>{this.#e.set(n,{resolve:e,reject:t})});return await this.#p({jsonrpc:`2.0`,id:n,method:e,params:t}),r}async sendNotification(e,t){await this.#p({jsonrpc:`2.0`,method:e,params:t})}async#p(e){return this.#a=this.#a.then(async()=>{let t=this.#i.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{console.error(`ACP write error:`,e)}),this.#a}},Na=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};const Pa=v.compose(v.isObject,v.compose(v.hasProperty(`message`),v.Struct({message:v.isString}))),Fa=S.String.pipe(S.brand(`SessionId`));var Ia=class extends S.ErrorClass(`AcpStreamError`)({_tag:S.tag(`AcpStreamError`),cause:S.Unknown}){displayName=`An unexpected error occurred while streaming`;message=`Streaming failed: ${this.cause}`},La=class extends S.ErrorClass(`AcpProviderNotInstalledError`)({_tag:S.tag(`AcpProviderNotInstalledError`),provider:dn}){displayName=`${ee.capitalize(this.provider)} is not installed`;message=g.value(this.provider).pipe(g.when(`claude`,()=>"Claude Code is not installed. Install it from https://code.claude.com/docs/en/overview#native-install-recommended, or use codex agent with `expect -a codex`."),g.when(`codex`,()=>"Codex CLI is not installed. Install it with `npm install -g @openai/codex`, or use Claude Code by removing the `--agent codex` option."),g.orElse(()=>`Your coding agent CLI is not installed. Please install it and then re-run expect.`))},Ra=class extends S.ErrorClass(`AcpProviderUnauthenticatedError`)({_tag:S.tag(`AcpProviderUnauthenticatedError`),provider:dn}){displayName=`Your ${this.provider} agent is not authenticated`;message=g.value(this.provider).pipe(g.when(`claude`,()=>"Please log in using `claude login`, and then re-run expect."),g.when(`codex`,()=>"Please log in using `codex login`, and then re-run expect."),g.orElse(()=>`Please sign in to your coding agent, and then re-run expect.`))},za=class extends S.ErrorClass(`AcpProviderUsageLimitError`)({_tag:S.tag(`AcpProviderUsageLimitError`),provider:dn}){displayName=`Your ${this.provider} agent has exceeded its usage limits`;message=`Usage limits exceeded for ${this.provider}. Please check your plan and billing.`},Ba=class extends S.ErrorClass(`AcpSessionCreateError`)({_tag:S.tag(`AcpSessionCreateError`),cause:S.Unknown}){displayName=`Creating a chat session failed`;message=`Creating session failed: ${s.pretty(s.fail(this.cause))}`},Va=class extends S.ErrorClass(`AcpConnectionInitError`)({_tag:S.tag(`AcpConnectionInitError`),cause:S.Unknown}){message=`Init connection failed: ${this.cause}`},Ha=class extends S.ErrorClass(`AcpAdapterNotFoundError`)({_tag:S.tag(`AcpAdapterNotFoundError`),packageName:S.String,cause:S.Unknown}){message=`ACP adapter not found: ${this.packageName}. Error: ${s.pretty(s.fail(this.cause))}`},Ua=class e extends C.Service()(`@expect/AcpAdapter`){static layerCodex=m.effect(e)(u.try({try:()=>{let t=a(typeof __filename<`u`?__filename:import.meta.url).resolve(`@zed-industries/codex-acp/bin/codex-acp.js`);return e.of({provider:`codex`,bin:process.execPath,args:[t],env:{}})},catch:e=>new Ha({packageName:`@zed-industries/codex-acp`,cause:e})}));static layerClaude=m.effect(e)(u.gen(function*(){let t=yield*ye.ChildProcessSpawner,n=S.Struct({loggedIn:S.Boolean});return yield*ve.make(`claude`,[`auth`,`status`]).pipe(t.string,u.flatMap(S.decodeEffect(S.fromJsonString(n))),u.flatMap(({loggedIn:e})=>e?u.void:new Ra({provider:`claude`}).asEffect()),u.catchReason(`PlatformError`,`NotFound`,()=>new La({provider:`claude`}).asEffect())),yield*u.try({try:()=>{let t=a(typeof __filename<`u`?__filename:import.meta.url).resolve(`@zed-industries/claude-agent-acp/dist/index.js`);return e.of({provider:`claude`,bin:process.execPath,args:[t],env:{}})},catch:e=>new Ha({packageName:`@zed-industries/claude-agent-acp`,cause:e})})})).pipe(m.provide(be.layer))},Wa=class extends C.Service()(`@expect/AcpClient`,{make:u.gen(function*(){let e=yield*Ua;yield*u.annotateLogsScoped({adapter:e.args[0]}),yield*u.logInfo(`Initializing AcpClient`);let t=yield*ye.ChildProcessSpawner,n=yield*f.make(),r=yield*b.unbounded(),i=new Map,a={requestPermission:e=>Promise.resolve({outcome:{outcome:`selected`,optionId:e.options.find(e=>e.kind===`allow_always`||e.kind===`allow_once`)?.optionId??e.options[0].optionId}}),sessionUpdate:async({sessionId:e,update:t})=>{let n=i.get(Fa.makeUnsafe(e));if(n===void 0)return console.warn(`updates queue not found for session ${e}`);let r=S.decodeUnknownSync(un)(t);b.offerUnsafe(n,r)}},o=yield*ve.make(e.bin,e.args,{env:e.env}).pipe(t.spawn);yield*u.annotateLogsScoped({pid:o.pid}),yield*u.logDebug(`ACP adapter subprocess spawned`),yield*w.fromQueue(r).pipe(w.run(o.stdin),u.forkScoped);let s=w.toReadableStream(o.stdout),c=new ja(e=>a,Aa(new WritableStream({write:e=>void b.offerUnsafe(r,e)}),s)),l=he(new URL(`./browser-mcp.js`,import.meta.url)),d=e=>[{command:process.execPath,args:[l],env:[...e],name:`browser`}],p=yield*u.tryPromise({try:()=>c.initialize({protocolVersion:1}),catch:e=>new Va({cause:e})});yield*u.logInfo(`ACP connection initialized`,{capabilities:p.agentCapabilities});let m=u.fn(`AcpClient.createSession`)(function*(t,n=[]){yield*u.annotateCurrentSpan({cwd:t});let r=d(n);return yield*u.tryPromise({try:()=>c.newSession({cwd:t,mcpServers:r}),catch:t=>{let n=Pa(t)?t.message:String(t);return[`authentication`].some(e=>n.toLowerCase().includes(e))?new Ra({provider:e.provider}):[`out of usage`,`limits exceeded`,`usage exceeded`].some(e=>n.toLowerCase().includes(e))?new za({provider:e.provider}):new Ba({cause:t})}}).pipe(u.map(({sessionId:e})=>Fa.makeUnsafe(e)),u.tap(e=>u.gen(function*(){let t=yield*b.unbounded();i.set(e,t),yield*u.logInfo(`ACP session created`,{sessionId:e})})))}),h=u.fn(`AcpClient.getQueueBySessionId`)(function*(e){if(!i.has(e))return yield*u.die(`Session ${e} not initialized, did you forget to call createSession?`);let t=yield*b.unbounded();return i.set(e,t),t});return{createSession:m,stream:u.fn(`AcpClient.stream`)(function*({prompt:e,sessionId:t,cwd:r,mcpEnv:i=[]}){let a=_.isSome(t)?t.value:yield*m(r,i);yield*u.logDebug(`ACP stream starting`,{sessionId:a});let o=yield*h(a);return yield*u.tryPromise({try:()=>c.prompt({sessionId:a,prompt:[{type:`text`,text:e}]}),catch:e=>new Ia({cause:e})}).pipe(u.tap(()=>u.logDebug(`ACP prompt completed`)),u.tap(()=>b.end(o)),f.run(n,a,{startImmediately:!0})),w.fromQueue(o)},w.unwrap)}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer));static layerCodex=this.layer.pipe(m.provide(Ua.layerCodex));static layerClaude=this.layer.pipe(m.provide(Ua.layerClaude))},Ga=class e extends C.Service()(`@expect/Agent`){static layerAcp=m.effect(e)(u.gen(function*(){let t=yield*Wa;return e.of({createSession:e=>t.createSession(e),stream:e=>t.stream({cwd:e.cwd,sessionId:_.map(e.sessionId,e=>e),prompt:e.prompt,mcpEnv:e.mcpEnv})})})).pipe(m.provide(Wa.layer));static layerCodex=e.layerAcp.pipe(m.provide(Ua.layerCodex));static layerClaude=e.layerAcp.pipe(m.provide(Ua.layerClaude));static layerFor=t=>t===`claude`?e.layerClaude:e.layerCodex;static layerTest=t=>m.effect(e,u.gen(function*(){let n=yield*p.FileSystem,r=S.decodeSync(un);return e.of({stream:()=>n.stream(t).pipe(w.decodeText(),w.splitLines,w.map(e=>r(JSON.parse(e))),w.orDie),createSession:()=>u.die(`createSession not supported for test layer`)})})).pipe(m.provide(be.layer))};const Ka=[`claude`,`codex`,`cursor`],qa=process.platform===`win32`?`where`:`which`,Ja=e=>{try{return le(`${qa} ${e}`,{stdio:`pipe`}),!0}catch{return!1}},Ya=()=>Ka.filter(Ja),Xa=12e3,Za=e=>e?[`Saved flow guidance:`,`You are replaying a previously saved flow. Follow these steps as guidance, but adapt if the UI has changed.`,`Saved flow title: ${e.title}`,`Saved flow request: ${e.userInstruction}`,``,...e.steps.flatMap((e,t)=>[`Step ${t+1}: ${e.title}`,`Instruction: ${e.instruction}`,`Expected: ${e.expectedOutcome}`,``])]:[],Qa=e=>{switch(e){case`Commit`:return[`- Start narrow and prove the selected commit's intended change works first.`,`- Treat the selected commit and its touched files as the primary testing hypothesis.`,`- After the primary flow, test 2-4 adjacent flows that could regress from the same change. Think about what else touches the same components, routes, or data.`,`- For UI changes, verify related views that render the same data or share the same components.`];case`WorkingTree`:return[`- Start with the exact user-requested flow against the local in-progress changes.`,`- After the primary flow, test related flows that exercise the same code paths — aim for 2-3 follow-ups.`,`- Pay extra attention to partially-implemented features: check that incomplete states don't break existing behavior.`];case`Changes`:return[`- Treat committed and uncommitted work as one body of change.`,`- Cover the requested flow first, then the highest-risk adjacent flows.`,`- Test 2-4 follow-up flows, prioritizing paths that share components or data with the changed files.`,`- If the changes touch shared utilities or layouts, verify multiple pages that use them.`];default:return[`- This is a branch-level review — be thorough. The goal is to catch regressions before merge, not to do a quick spot-check.`,`- Cover the requested flow first, then systematically test each area affected by the changed files.`,`- Aim for 5-8 total tested flows. Derive them from the changed files: each changed route, component, or data path should get its own verification.`,`- Test cross-cutting concerns: if shared components, layouts, or utilities changed, verify them on multiple pages that consume them.`,`- Include at least one negative/edge-case flow (e.g. invalid input, empty state, unauthorized access, broken link) relevant to the changes.`,`- Do not stop after the happy path passes. The value of a branch review is catching what the developer might have missed.`]}},$a=e=>{if(!e||e.totalCount===0)return[];let t=[`Test coverage of changed files: ${e.percent}% (${e.coveredCount}/${e.totalCount} files have tests)`],n=e.entries.filter(e=>e.covered),r=e.entries.filter(e=>!e.covered);for(let e of n)t.push(` [covered] ${e.path} (tested by: ${e.testFiles.slice(0,3).join(`, `)})`);for(let e of r)t.push(` [no test] ${e.path}`);return r.length>0&&t.push(`Prioritize browser-testing files WITHOUT existing test coverage.`),t.push(``),t},eo=e=>{let t=e.browserMcpServerName??`browser`,n=e.changedFiles.slice(0,12),r=e.recentCommits.slice(0,5),i=e.diffPreview||``,a=i.length>Xa?i.slice(0,Xa)+`
11
+ ... (truncated)`:i;return[`You are executing a browser regression test directly from repository context.`,`You have browser tools via the MCP server named "${t}":`,``,`1. open — Launch a browser and navigate to a URL.`,`2. playwright — Execute Playwright code in Node. Globals: page (Page), context (BrowserContext), browser (Browser), ref(id) (resolves a snapshot ref like 'e4' to a Playwright Locator). Supports await. Return a value to get it back as JSON.`,`3. screenshot — Capture page state. Set mode: 'snapshot' (ARIA accessibility tree, default and preferred), 'screenshot' (PNG image), or 'annotated' (PNG with numbered labels on interactive elements).`,`4. console_logs — Get browser console messages. Filter by type ('error', 'warning', 'log'). Use after navigation or interactions to catch errors.`,`5. network_requests — Get captured network requests. Filter by method, URL substring, or resource type ('xhr', 'fetch', 'document').`,`6. close — Close the browser and end the session.`,``,`Strongly prefer screenshot with mode 'snapshot' for observing page state — the ARIA tree is fast, cheap, and sufficient for almost all assertions.`,`Only use mode 'screenshot' or 'annotated' when you need to verify something purely visual (layout, colors, images) that the accessibility tree cannot capture.`,`After each step, check console_logs with type 'error' to catch unexpected errors.`,``,`Snapshot-driven workflow:`,`1. Call screenshot with mode 'snapshot' to get the ARIA tree with refs.`,`2. Read the tree to find your target elements. Every interactive element has a ref like [ref=e4].`,`3. Use ref() in one playwright call to perform multiple actions using the refs from the snapshot — fill forms, click buttons, wait, and return results all in one block.`,`4. Only take a new snapshot when the page structure has changed significantly (navigation, modal open, new content loaded) and you need fresh refs.`,``,`Example snapshot tree:`,` - navigation`,` - link "Home" [ref=e1]`,` - link "About" [ref=e2]`,` - main`,` - heading "Welcome"`,` - textbox "Email" [ref=e3]`,` - button "Submit" [ref=e4]`,``,`Acting on refs — use ref() to get a Locator directly from the snapshot ref ID:`,` await ref('e3').fill('test@example.com');`,` await ref('e4').click();`,` await ref('e1').click();`,``,`Always snapshot first, then use ref() to act. Never guess CSS selectors.`,``,`Batch as many actions as possible into a single playwright call to minimize round trips:`,` playwright: await ref('e3').fill('test@example.com'); await ref('e5').fill('secret'); await ref('e6').click(); await page.waitForLoadState('networkidle'); return await page.innerText('.result');`,` playwright: await ref('e1').click(); await page.waitForURL('**/about');`,` playwright: return { url: page.url(), title: await page.title() };`,``,`Execution strategy:`,`- First master the primary flow the developer asked for. Verify it thoroughly before moving on.`,`- Once the primary flow passes, test additional related flows suggested by the changed files and route context. The scope strategy below specifies how many — follow it.`,`- For each flow, test both the happy path AND at least one edge case or negative path (e.g. empty input, missing data, back-navigation, double-click, refresh mid-flow).`,`- Use the same browser session throughout unless the app forces you into a different path.`,`- Execution style is assertion-first: navigate, act, validate, recover once, then fail with evidence if still blocked.`,`- Create your own step structure while executing. Use stable sequential IDs like step-01, step-02, step-03.`,`- Take your time. A thorough run that catches real issues is more valuable than a fast run that misses them. Do not rush to RUN_COMPLETED.`,``,`Assertion depth — do not just confirm the page loaded. For each step, verify that the action produced the expected state change:`,`- Before acting, note what should change. After acting, confirm it actually changed.`,`- Check at least two independent signals per step (e.g. URL changed AND new content appeared, or item was added AND count updated).`,`- Verify absence when relevant: after a delete, the item is gone; after dismissing a modal, it no longer appears in the tree.`,`- Use playwright to return structured evidence rather than eyeballing snapshots: return { url: page.url(), title: await page.title(), visible: await ref('e5').isVisible() };`,`- If the changed files suggest specific behavior (e.g. a validation rule, a redirect, a computed value), test that specific behavior rather than just the surrounding UI.`,``,`Before and after each step, emit these exact status lines on their own lines:`,`STEP_START|<step-id>|<step-title>`,`STEP_DONE|<step-id>|<short-summary>`,`ASSERTION_FAILED|<step-id>|<why-it-failed>`,`STEP_SKIPPED|<step-id>|<reason-it-was-skipped>`,`RUN_COMPLETED|passed|<final-summary>`,`RUN_COMPLETED|failed|<final-summary>`,``,`Use STEP_SKIPPED when a step cannot be executed due to missing prerequisites (e.g. test credentials not available, required test data missing, auth-blocked). Never use STEP_DONE for steps that were not actually tested.`,``,`Allowed failure categories: app-bug, env-issue, auth-blocked, missing-test-data, selector-drift, agent-misread.`,`When a step fails, gather structured evidence before emitting ASSERTION_FAILED:`,`- Call screenshot with mode 'snapshot' to capture the ARIA tree.`,`- Use playwright to gather diagnostics: return { url: page.url(), title: await page.title(), text: await page.innerText('body').then(t => t.slice(0, 500)) };`,`- Only take a visual screenshot if the failure might be layout/rendering related.`,`- Summarize the failure category and the most important evidence inside <why-it-failed>.`,``,`Stability heuristics:`,`- After navigation or major UI changes, use playwright to wait for the page to settle (e.g. await page.waitForLoadState('networkidle')).`,`- Use screenshot with mode 'snapshot' to inspect the accessibility tree before interactions that depend on current UI state.`,`- Avoid interacting while the UI is visibly loading or transitioning.`,`- Confirm you reached the expected page or route before continuing.`,`- When waiting for page changes (navigation, content loading, animations), prefer short incremental waits (1-3 seconds) with snapshot checks in between rather than a single long wait. For example, instead of waiting 10 seconds: wait 2s, take a snapshot, check if ready, if not wait 2s more and snapshot again. This lets you proceed as soon as the page is ready.`,``,`Recovery policy for each blocked step:`,`- Take a new snapshot to re-inspect the page and get fresh refs.`,`- Use playwright with ref() to scroll the target into view or retry the interaction once.`,`- If still blocked, classify the blocker with one allowed failure category and include that classification in ASSERTION_FAILED.`,``,`Avoid rabbit holes:`,`- Do not repeat the same failing action more than once without new evidence such as a fresh snapshot, a different ref, a changed page state, or a clear new hypothesis.`,`- If four attempts fail or progress stalls, stop acting and report what you observed, what blocked progress, and the most likely next step.`,`- Prefer gathering evidence over brute force. If the page is confusing, use screenshot with mode 'snapshot', playwright for console or network diagnostics, or a visual screenshot to understand it before trying more actions.`,`- If you encounter a blocker such as login, passkey/manual user interaction, permissions, captchas, destructive confirmations, missing data, or an unexpected state, stop and report it instead of improvising repeated actions.`,`- Do not get stuck in wait-action-wait loops. Every retry should be justified by something newly observed.`,``,`Before emitting RUN_COMPLETED, call the close tool exactly once so the browser session flushes the video to disk.`,``,`Environment:`,`- Base URL: ${e.baseUrl??`not provided`}`,`- Headed mode preference: ${e.isHeadless?`headless`:`headed`}`,`- Reuse browser cookies: ${e.requiresCookies?`yes`:`no`}`,``,`Testing target context:`,`- Scope: ${e.scope}`,`- Current branch: ${e.currentBranch}`,`- Main branch: ${e.mainBranch??`unknown`}`,``,`Developer request:`,e.userInstruction,``,...Za(e.savedFlow),`Project learnings from previous runs:`,e.learnings?.trim()||`No learnings yet.`,``,`Changed files:`,n.length>0?n.map(e=>`- [${e.status}] ${e.path}`).join(`
12
+ `):`- No changed files detected`,``,...$a(e.testCoverage),`Recent commits:`,r.length>0?r.map(e=>`- ${e.shortHash} ${e.subject}`).join(`
13
+ `):`- No recent commits available`,``,`Diff preview:`,a||`No diff preview available`,``,`Scope strategy:`,...Qa(e.scope)].join(`
14
+ `)};var to=n(((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`:``)}})),no=n(((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=to(),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})),ro=n(((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=no()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),io=n(((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)}})),ao=n(((t,n)=>{let r=e(`os`),i=e(`tty`),a=io(),{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 n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.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:n;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:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),oo=n(((t,n)=>{let r=e(`tty`),i=e(`util`);t.init=d,t.log=c,t.formatArgs=o,t.save=l,t.load=u,t.useColors=a,t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{let e=ao();e&&(e.stderr||e).level>=2&&(t.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{}t.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 a(){return`colors`in t.inspectOpts?!!t.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
15
15
  `).join(`
16
16
  `+a),e.push(i+`m+`+n.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+t+` `+e[0]}function s(){return t.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...e){return process.stderr.write(i.formatWithOptions(t.inspectOpts,...e)+`
17
- `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(e){e.inspectOpts={};let n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]}n.exports=to()(t);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
18
- `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),oo=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=no():t.exports=ao()})),so=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0});let r=e(`fs`),i=n(oo()).default(`@kwsites/file-exists`);function a(e,t,n){i(`checking %s`,e);try{let a=r.statSync(e);return a.isFile()&&t?(i(`[OK] path represents a file`),!0):a.isDirectory()&&n?(i(`[OK] path represents a directory`),!0):(i(`[FAIL] path represents something other than a file or directory`),!1)}catch(e){if(e.code===`ENOENT`)return i(`[FAIL] path is not accessible: %o`,e),!1;throw i(`[FATAL] %o`,e),e}}function o(e,n=t.READABLE){return a(e,(n&t.FILE)>0,(n&t.FOLDER)>0)}t.exists=o,t.FILE=1,t.FOLDER=2,t.READABLE=t.FILE+t.FOLDER})),co=n((e=>{function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,`__esModule`,{value:!0}),t(so())})),lo=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDeferred=e.deferred=void 0;function t(){let e,t,n=`pending`;return{promise:new Promise((n,r)=>{e=n,t=r}),done(t){n===`pending`&&(n=`resolved`,e(t))},fail(e){n===`pending`&&(n=`rejected`,t(e))},get fulfilled(){return n!==`pending`},get status(){return n}}}e.deferred=t,e.createDeferred=t})),uo=co(),fo=t(oo(),1),po=lo(),mo=Object.defineProperty,ho=Object.getOwnPropertyDescriptor,go=Object.getOwnPropertyNames,_o=Object.prototype.hasOwnProperty,Y=(e,t)=>function(){return e&&(t=(0,e[go(e)[0]])(e=0)),t},vo=(e,t)=>function(){return t||(0,e[go(e)[0]])((t={exports:{}}).exports,t),t.exports},yo=(e,t)=>{for(var n in t)mo(e,n,{get:t[n],enumerable:!0})},bo=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of go(t))!_o.call(e,i)&&i!==n&&mo(e,i,{get:()=>t[i],enumerable:!(r=ho(t,i))||r.enumerable});return e},xo=e=>bo(mo({},`__esModule`,{value:!0}),e);function So(...e){let t=new String(e);return To.set(t,e),t}function Co(e){return e instanceof String&&To.has(e)}function wo(e){return To.get(e)||[]}var To,Eo=Y({"src/lib/args/pathspec.ts"(){To=new WeakMap}}),Do,Oo=Y({"src/lib/errors/git-error.ts"(){Do=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),ko,Ao=Y({"src/lib/errors/git-response-error.ts"(){Oo(),ko=class extends Do{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),jo,Mo=Y({"src/lib/errors/task-configuration-error.ts"(){Oo(),jo=class extends Do{constructor(e){super(void 0,e)}}}});function No(e){return typeof e==`function`?e:ts}function Po(e){return typeof e==`function`&&e!==ts}function Fo(e,t){let n=e.indexOf(t);return n<=0?[e,``]:[e.substr(0,n),e.substr(n+1)]}function Io(e,t=0){return Ro(e)&&e.length>t?e[t]:void 0}function Lo(e,t=0){if(Ro(e)&&e.length>t)return e[e.length-1-t]}function Ro(e){return fs(e)}function zo(e=``,t=!0,n=`
19
- `){return e.split(n).reduce((e,n)=>{let r=t?n.trim():n;return r&&e.push(r),e},[])}function Bo(e,t){return zo(e,!0).map(e=>t(e))}function Vo(e){return(0,uo.exists)(e,uo.FOLDER)}function Ho(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function Uo(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function Wo(e,t){if(Array.isArray(e)){let n=e.indexOf(t);n>=0&&e.splice(n,1)}else e.delete(t);return t}function Go(e){return Array.isArray(e)?e:[e]}function Ko(e){return e.replace(/[\s-]+(.)/g,(e,t)=>t.toUpperCase())}function qo(e){return Go(e).map(e=>e instanceof String?e:String(e))}function Jo(e,t=0){if(e==null)return t;let n=parseInt(e,10);return Number.isNaN(n)?t:n}function Yo(e,t){let n=[];for(let r=0,i=e.length;r<i;r++)n.push(t,e[r]);return n}function Xo(e){return(Array.isArray(e)?Te.concat(e):e).toString(`utf-8`)}function Zo(e,t){let n={};return t.forEach(t=>{e[t]!==void 0&&(n[t]=e[t])}),n}function Qo(e=0){return new Promise(t=>setTimeout(t,e))}function $o(e){if(e!==!1)return e}var es,ts,ns,rs=Y({"src/lib/utils/util.ts"(){ps(),es=`\0`,ts=()=>{},ns=Object.prototype.toString.call.bind(Object.prototype.toString)}});function is(e,t,n){return t(e)?e:arguments.length>2?n:void 0}function as(e,t){let n=Co(e)?`string`:typeof e;return/number|string|boolean/.test(n)&&(!t||!t.includes(n))}function os(e){return!!e&&ns(e)===`[object Object]`}function ss(e){return typeof e==`function`}var cs,ls,us,ds,fs,ps=Y({"src/lib/utils/argument-filters.ts"(){Eo(),rs(),cs=e=>Array.isArray(e),ls=e=>typeof e==`number`,us=e=>typeof e==`string`||Co(e),ds=e=>us(e)||Array.isArray(e)&&e.every(us),fs=e=>e==null||`number|boolean|function`.includes(typeof e)?!1:typeof e.length==`number`}}),ms,hs=Y({"src/lib/utils/exit-codes.ts"(){ms=(e=>(e[e.SUCCESS=0]=`SUCCESS`,e[e.ERROR=1]=`ERROR`,e[e.NOT_FOUND=-2]=`NOT_FOUND`,e[e.UNCLEAN=128]=`UNCLEAN`,e))(ms||{})}}),gs,_s=Y({"src/lib/utils/git-output-streams.ts"(){gs=class e{constructor(e,t){this.stdOut=e,this.stdErr=t}asStrings(){return new e(this.stdOut.toString(`utf8`),this.stdErr.toString(`utf8`))}}}});function vs(){throw Error(`LineParser:useMatches not implemented`)}var X,ys,bs=Y({"src/lib/utils/line-parser.ts"(){X=class{constructor(e,t){this.matches=[],this.useMatches=vs,this.parse=(e,t)=>(this.resetMatches(),this._regExp.every((t,n)=>this.addMatch(t,n,e(n)))?this.useMatches(t,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,n){let r=n&&e.exec(n);return r&&this.pushMatch(t,r),!!r}pushMatch(e,t){this.matches.push(...t.slice(1))}},ys=class extends X{addMatch(e,t,n){return/^remote:\s/.test(String(n))&&super.addMatch(e,t,n)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}});function xs(...e){let t=process.cwd(),n=Object.assign({baseDir:t,...Ss},...e.filter(e=>typeof e==`object`&&e));return n.baseDir=n.baseDir||t,n.trimmed=n.trimmed===!0,n}var Ss,Cs=Y({"src/lib/utils/simple-git-options.ts"(){Ss={binary:`git`,maxConcurrentProcesses:5,config:[],trimmed:!1}}});function ws(e,t=[]){return os(e)?Object.keys(e).reduce((t,n)=>{let r=e[n];if(Co(r))t.push(r);else if(as(r,[`boolean`]))t.push(n+`=`+r);else if(Array.isArray(r))for(let e of r)as(e,[`string`,`number`])||t.push(n+`=`+e);else t.push(n);return t},t):t}function Ts(e,t=0,n=!1){let r=[];for(let n=0,i=t<0?e.length:t;n<i;n++)`string|number`.includes(typeof e[n])&&r.push(String(e[n]));return ws(Ds(e),r),n||r.push(...Es(e)),r}function Es(e){return qo(is(Lo(e,typeof Lo(e)==`function`?1:0),cs,[]))}function Ds(e){return is(Lo(e,ss(Lo(e))?1:0),os)}function Os(e,t=!0){let n=No(Lo(e));return t||Po(n)?n:void 0}var ks=Y({"src/lib/utils/task-options.ts"(){ps(),rs(),Eo()}});function As(e,t){return e(t.stdOut,t.stdErr)}function js(e,t,n,r=!0){return Go(n).forEach(n=>{for(let i=zo(n,r),a=0,o=i.length;a<o;a++){let n=(e=0)=>{if(!(a+e>=o))return i[a+e]};t.some(({parse:t})=>t(n,e))}}),e}var Ms=Y({"src/lib/utils/task-parser.ts"(){rs()}}),Ns={};yo(Ns,{ExitCodes:()=>ms,GitOutputStreams:()=>gs,LineParser:()=>X,NOOP:()=>ts,NULL:()=>es,RemoteLineParser:()=>ys,append:()=>Ho,appendTaskOptions:()=>ws,asArray:()=>Go,asCamelCase:()=>Ko,asFunction:()=>No,asNumber:()=>Jo,asStringArray:()=>qo,bufferToString:()=>Xo,callTaskParser:()=>As,createInstanceConfig:()=>xs,delay:()=>Qo,filterArray:()=>cs,filterFunction:()=>ss,filterHasLength:()=>fs,filterNumber:()=>ls,filterPlainObject:()=>os,filterPrimitives:()=>as,filterString:()=>us,filterStringOrStringArray:()=>ds,filterType:()=>is,first:()=>Io,folderExists:()=>Vo,forEachLineWithContent:()=>Bo,getTrailingOptions:()=>Ts,including:()=>Uo,isUserFunction:()=>Po,last:()=>Lo,objectToString:()=>ns,orVoid:()=>$o,parseStringResponse:()=>js,pick:()=>Zo,prefixedArray:()=>Yo,remove:()=>Wo,splitOn:()=>Fo,toLinesWithContent:()=>zo,trailingFunctionArgument:()=>Os,trailingOptionsArgument:()=>Ds});var Z=Y({"src/lib/utils/index.ts"(){ps(),hs(),_s(),bs(),Cs(),ks(),Ms(),rs()}}),Ps={};yo(Ps,{CheckRepoActions:()=>zs,checkIsBareRepoTask:()=>Ls,checkIsRepoRootTask:()=>Is,checkIsRepoTask:()=>Fs});function Fs(e){switch(e){case`bare`:return Ls();case`root`:return Is()}return{commands:[`rev-parse`,`--is-inside-work-tree`],format:`utf-8`,onError:Bs,parser:Vs}}function Is(){return{commands:[`rev-parse`,`--git-dir`],format:`utf-8`,onError:Bs,parser(e){return/^\.(git)?$/.test(e.trim())}}}function Ls(){return{commands:[`rev-parse`,`--is-bare-repository`],format:`utf-8`,onError:Bs,parser:Vs}}function Rs(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}var zs,Bs,Vs,Hs=Y({"src/lib/tasks/check-is-repo.ts"(){Z(),zs=(e=>(e.BARE=`bare`,e.IN_TREE=`tree`,e.IS_REPO_ROOT=`root`,e))(zs||{}),Bs=({exitCode:e},t,n,r)=>{if(e===128&&Rs(t))return n(Buffer.from(`false`));r(t)},Vs=e=>e.trim()===`true`}});function Us(e,t){let n=new Ws(e),r=e?Ks:Gs;return zo(t).forEach(e=>{let t=e.replace(r,``);n.paths.push(t),(qs.test(t)?n.folders:n.files).push(t)}),n}var Ws,Gs,Ks,qs,Js=Y({"src/lib/responses/CleanSummary.ts"(){Z(),Ws=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},Gs=/^[a-z]+\s*/i,Ks=/^[a-z]+\s+[a-z]+\s*/i,qs=/\/$/}}),Ys={};yo(Ys,{EMPTY_COMMANDS:()=>nc,adhocExecTask:()=>Xs,configurationErrorTask:()=>Zs,isBufferTask:()=>ec,isEmptyTask:()=>tc,straightThroughBufferTask:()=>$s,straightThroughStringTask:()=>Qs});function Xs(e){return{commands:nc,format:`empty`,parser:e}}function Zs(e){return{commands:nc,format:`empty`,parser(){throw typeof e==`string`?new jo(e):e}}}function Qs(e,t=!1){return{commands:e,format:`utf-8`,parser(e){return t?String(e).trim():e}}}function $s(e){return{commands:e,format:`buffer`,parser(e){return e}}}function ec(e){return e.format===`buffer`}function tc(e){return e.format===`empty`||!e.commands.length}var nc,rc=Y({"src/lib/tasks/task.ts"(){Mo(),nc=[]}}),ic={};yo(ic,{CONFIG_ERROR_INTERACTIVE_MODE:()=>fc,CONFIG_ERROR_MODE_REQUIRED:()=>pc,CONFIG_ERROR_UNKNOWN_OPTION:()=>mc,CleanOptions:()=>hc,cleanTask:()=>oc,cleanWithOptionsTask:()=>ac,isCleanOptionsArray:()=>sc});function ac(e,t){let{cleanMode:n,options:r,valid:i}=cc(e);return n?i.options?(r.push(...t),r.some(dc)?Zs(fc):oc(n,r)):Zs(mc+JSON.stringify(e)):Zs(pc)}function oc(e,t){return{commands:[`clean`,`-${e}`,...t],format:`utf-8`,parser(t){return Us(e===`n`,t)}}}function sc(e){return Array.isArray(e)&&e.every(e=>gc.has(e))}function cc(e){let t,n=[],r={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,``).split(``).forEach(e=>{lc(e)?(t=e,r.cleanMode=!0):r.options=r.options&&uc(n[n.length]=`-${e}`)}),{cleanMode:t,options:n,valid:r}}function lc(e){return e===`f`||e===`n`}function uc(e){return/^-[a-z]$/i.test(e)&&gc.has(e.charAt(1))}function dc(e){return/^-[^\-]/.test(e)?e.indexOf(`i`)>0:e===`--interactive`}var fc,pc,mc,hc,gc,_c=Y({"src/lib/tasks/clean.ts"(){Js(),Z(),rc(),fc=`Git clean interactive mode is not supported`,pc=`Git clean mode parameter ("n" or "f") is required`,mc=`Git clean unknown option found in: `,hc=(e=>(e.DRY_RUN=`n`,e.FORCE=`f`,e.IGNORED_INCLUDED=`x`,e.IGNORED_ONLY=`X`,e.EXCLUDING=`e`,e.QUIET=`q`,e.RECURSIVE=`d`,e))(hc||{}),gc=new Set([`i`,...qo(Object.values(hc))])}});function vc(e){let t=new Sc;for(let n of xc(e))t.addValue(n.file,String(n.key),n.value);return t}function yc(e,t){let n=null,r=[],i=new Map;for(let a of xc(e,t))a.key===t&&(r.push(n=a.value),i.has(a.file)||i.set(a.file,[]),i.get(a.file).push(n));return{key:t,paths:Array.from(i.keys()),scopes:i,value:n,values:r}}function bc(e){return e.replace(/^(file):/,``)}function*xc(e,t=null){let n=e.split(`\0`);for(let e=0,r=n.length-1;e<r;){let r=bc(n[e++]),i=n[e++],a=t;if(i.includes(`
20
- `)){let e=Fo(i,`
21
- `);a=e[0],i=e[1]}yield{file:r,key:a,value:i}}}var Sc,Cc=Y({"src/lib/responses/ConfigList.ts"(){Z(),Sc=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{}),this._all}addFile(e){if(!(e in this.values)){let t=Lo(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,n){let r=this.addFile(e);Object.hasOwn(r,t)?Array.isArray(r[t])?r[t].push(n):r[t]=[r[t],n]:r[t]=n,this._all=void 0}}}});function wc(e,t){return typeof e==`string`&&Object.hasOwn(kc,e)?e:t}function Tc(e,t,n,r){let i=[`config`,`--${r}`];return n&&i.push(`--add`),i.push(e,t),{commands:i,format:`utf-8`,parser(e){return e}}}function Ec(e,t){let n=[`config`,`--null`,`--show-origin`,`--get-all`,e];return t&&n.splice(1,0,`--${t}`),{commands:n,format:`utf-8`,parser(t){return yc(t,e)}}}function Dc(e){let t=[`config`,`--list`,`--show-origin`,`--null`];return e&&t.push(`--${e}`),{commands:t,format:`utf-8`,parser(e){return vc(e)}}}function Oc(){return{addConfig(e,t,...n){return this._runTask(Tc(e,t,n[0]===!0,wc(n[1],`local`)),Os(arguments))},getConfig(e,t){return this._runTask(Ec(e,wc(t,void 0)),Os(arguments))},listConfig(...e){return this._runTask(Dc(wc(e[0],void 0)),Os(arguments))}}}var kc,Ac=Y({"src/lib/tasks/config.ts"(){Cc(),Z(),kc=(e=>(e.system=`system`,e.global=`global`,e.local=`local`,e.worktree=`worktree`,e))(kc||{})}});function jc(e){return Nc.has(e)}var Mc,Nc,Pc=Y({"src/lib/tasks/diff-name-status.ts"(){Mc=(e=>(e.ADDED=`A`,e.COPIED=`C`,e.DELETED=`D`,e.MODIFIED=`M`,e.RENAMED=`R`,e.CHANGED=`T`,e.UNMERGED=`U`,e.UNKNOWN=`X`,e.BROKEN=`B`,e))(Mc||{}),Nc=new Set(Object.values(Mc))}});function Fc(...e){return new Vc().param(...e)}function Ic(e){let t=new Set,n={};return Bo(e,e=>{let[r,i,a]=e.split(es);t.add(r),(n[r]=n[r]||[]).push({line:Jo(i),path:r,preview:a})}),{paths:t,results:n}}function Lc(){return{grep(e){let t=Os(arguments),n=Ts(arguments);for(let e of Rc)if(n.includes(e))return this._runTask(Zs(`git.grep: use of "${e}" is not supported.`),t);typeof e==`string`&&(e=Fc().param(e));let r=[`grep`,`--null`,`-n`,`--full-name`,...n,...e];return this._runTask({commands:r,format:`utf-8`,parser(e){return Ic(e)}},t)}}}var Rc,zc,Bc,Vc,Hc=Y({"src/lib/tasks/grep.ts"(){Z(),rc(),Rc=[`-h`],zc=Symbol(`grepQuery`),Vc=class{constructor(){this[Bc]=[]}*[(Bc=zc,Symbol.iterator)](){for(let e of this[zc])yield e}and(...e){return e.length&&this[zc].push(`--and`,`(`,...Yo(e,`-e`),`)`),this}param(...e){return this[zc].push(...Yo(e,`-e`)),this}}}}),Uc={};yo(Uc,{ResetMode:()=>qc,getResetMode:()=>Gc,resetTask:()=>Wc});function Wc(e,t){let n=[`reset`];return Kc(e)&&n.push(`--${e}`),n.push(...t),Qs(n)}function Gc(e){if(Kc(e))return e;switch(typeof e){case`string`:case`undefined`:return`soft`}}function Kc(e){return typeof e==`string`&&Jc.includes(e)}var qc,Jc,Yc=Y({"src/lib/tasks/reset.ts"(){Z(),rc(),qc=(e=>(e.MIXED=`mixed`,e.SOFT=`soft`,e.HARD=`hard`,e.MERGE=`merge`,e.KEEP=`keep`,e))(qc||{}),Jc=qo(Object.values(qc))}});function Xc(){return(0,fo.default)(`simple-git`)}function Zc(e,t,n){return!t||!String(t).replace(/\s*/,``)?n?(t,...r)=>{e(t,...r),n(t,...r)}:e:(r,...i)=>{e(`%s ${r}`,t,...i),n&&n(r,...i)}}function Qc(e,t,{namespace:n}){if(typeof e==`string`)return e;let r=t&&t.namespace||``;return r.startsWith(n)?r.substr(n.length+1):r||n}function $c(e,t,n,r=Xc()){let i=e&&`[${e}]`||``,a=[],o=typeof t==`string`?r.extend(t):t,s=Qc(is(t,us),o,r);return l(n);function c(t,n){return Ho(a,$c(e,s.replace(/^[^:]+/,t),n,r))}function l(t){let n=t&&`[${t}]`||``,a=o&&Zc(o,n)||ts,s=Zc(r,`${i} ${n}`,a);return Object.assign(o?a:s,{label:e,sibling:c,info:s,step:l})}}var el=Y({"src/lib/git-logger.ts"(){Z(),fo.default.formatters.L=e=>String(fs(e)?e.length:`-`),fo.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString(`utf8`):ns(e)}}),tl,nl=Y({"src/lib/runners/tasks-pending-queue.ts"(){Oo(),el(),tl=class e{constructor(e=`GitExecutor`){this.logLabel=e,this._queue=new Map}withProgress(e){return this._queue.get(e)}createProgress(t){let n=e.getName(t.commands[0]);return{task:t,logger:$c(this.logLabel,n),name:n}}push(e){let t=this.createProgress(e);return t.logger(`Adding task to the queue, commands = %o`,e.commands),this._queue.set(e,t),t}fatal(e){for(let[t,{logger:n}]of Array.from(this._queue.entries()))t===e.task?(n.info(`Failed %o`,e),n(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`)):n.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`,e.message),this.complete(t);if(this._queue.size!==0)throw Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(e){this.withProgress(e)&&this._queue.delete(e)}attempt(e){let t=this.withProgress(e);if(!t)throw new Do(void 0,`TasksPendingQueue: attempt called for an unknown task`);return t.logger(`Starting task`),t}static getName(t=`empty`){return`task:${t}:${++e.counter}`}static{this.counter=0}}}});function rl(e,t){return{method:Io(e.commands)||``,commands:t}}function il(e,t){return n=>{t(`[ERROR] child process exception %o`,n),e.push(Buffer.from(String(n.stack),`ascii`))}}function al(e,t,n,r){return i=>{n(`%s received %L bytes`,t,i),r(`%B`,i),e.push(i)}}var ol,sl=Y({"src/lib/runners/git-executor-chain.ts"(){Oo(),rc(),Z(),nl(),ol=class{constructor(e,t,n){this._executor=e,this._scheduler=t,this._plugins=n,this._chain=Promise.resolve(),this._queue=new tl}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){let t=await this._scheduler.next(),n=()=>this._queue.complete(e);try{let{logger:t}=this._queue.attempt(e);return await(tc(e)?this.attemptEmptyTask(e,t):this.attemptRemoteTask(e,t))}catch(t){throw this.onFatalException(e,t)}finally{n(),t()}}onFatalException(e,t){let n=t instanceof Do?Object.assign(t,{task:e}):new Do(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(n),n}async attemptRemoteTask(e,t){let n=this._plugins.exec(`spawn.binary`,``,rl(e,e.commands)),r=this._plugins.exec(`spawn.args`,[...e.commands],rl(e,e.commands)),i=await this.gitResponse(e,n,r,this.outputHandler,t.step(`SPAWN`)),a=await this.handleTaskData(e,r,i,t.step(`HANDLE`));return t(`passing response to task's parser as a %s`,e.format),ec(e)?As(e.parser,a):As(e.parser,a.asStrings())}async attemptEmptyTask(e,t){return t(`empty task bypassing child process to call to task's parser`),e.parser(this)}handleTaskData(e,t,n,r){let{exitCode:i,rejection:a,stdOut:o,stdErr:s}=n;return new Promise((c,l)=>{r(`Preparing to handle process response exitCode=%d stdOut=`,i);let{error:u}=this._plugins.exec(`task.error`,{error:a},{...rl(e,t),...n});if(u&&e.onError)return r.info(`exitCode=%s handling with custom error handler`),e.onError(n,u,e=>{r.info(`custom error handler treated as success`),r(`custom error returned a %s`,ns(e)),c(new gs(Array.isArray(e)?Buffer.concat(e):e,Buffer.concat(s)))},l);if(u)return r.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`,i,s.length,a),l(u);r.info(`retrieving task output complete`),c(new gs(Buffer.concat(o),Buffer.concat(s)))})}async gitResponse(e,t,n,r,i){let a=i.sibling(`output`),o=this._plugins.exec(`spawn.options`,{cwd:this.cwd,env:this.env,windowsHide:!0},rl(e,e.commands));return new Promise(s=>{let c=[],l=[];i.info(`%s %o`,t,n),i(`%O`,o);let u=this._beforeSpawn(e,n);if(u)return s({stdOut:c,stdErr:l,exitCode:9901,rejection:u});this._plugins.exec(`spawn.before`,void 0,{...rl(e,n),kill(e){u=e||u}});let d=De(t,n,o);d.stdout.on(`data`,al(c,`stdOut`,i,a.step(`stdOut`))),d.stderr.on(`data`,al(l,`stdErr`,i,a.step(`stdErr`))),d.on(`error`,il(l,i)),r&&(i(`Passing child process stdOut/stdErr to custom outputHandler`),r(t,d.stdout,d.stderr,[...n])),this._plugins.exec(`spawn.after`,void 0,{...rl(e,n),spawned:d,close(e,t){s({stdOut:c,stdErr:l,exitCode:e,rejection:u||t})},kill(e){d.killed||(u=e,d.kill(`SIGINT`))}})})}_beforeSpawn(e,t){let n;return this._plugins.exec(`spawn.before`,void 0,{...rl(e,t),kill(e){n=e||n}}),n}}}}),cl={};yo(cl,{GitExecutor:()=>ll});var ll,ul=Y({"src/lib/runners/git-executor.ts"(){sl(),ll=class{constructor(e,t,n){this.cwd=e,this._scheduler=t,this._plugins=n,this._chain=new ol(this,this._scheduler,this._plugins)}chain(){return new ol(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function dl(e,t,n=ts){t.then(e=>{n(null,e)},t=>{t?.task===e&&n(t instanceof ko?fl(t):t,void 0)})}function fl(e){let t=e=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${e} should be GitResponseError.git.${e}, this will no longer be available in version 3`),t=ts};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(n,{}));function n(n,r){return r in e||(n[r]={enumerable:!1,configurable:!1,get(){return t(r),e.git[r]}}),n}}var pl=Y({"src/lib/task-callback.ts"(){Ao(),Z()}});function ml(e,t){return Xs(n=>{if(!Vo(e))throw Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||n).cwd=e})}var hl=Y({"src/lib/tasks/change-working-directory.ts"(){Z(),rc()}});function gl(e){let t=[`checkout`,...e];return t[1]===`-b`&&t.includes(`-B`)&&(t[1]=Wo(t,`-B`)),Qs(t)}function _l(){return{checkout(){return this._runTask(gl(Ts(arguments,1)),Os(arguments))},checkoutBranch(e,t){return this._runTask(gl([`-b`,e,t,...Ts(arguments)]),Os(arguments))},checkoutLocalBranch(e){return this._runTask(gl([`-b`,e,...Ts(arguments)]),Os(arguments))}}}var vl=Y({"src/lib/tasks/checkout.ts"(){Z(),rc()}});function yl(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function bl(){return{countObjects(){return this._runTask({commands:[`count-objects`,`--verbose`],format:`utf-8`,parser(e){return js(yl(),[xl],e)}})}}}var xl,Sl=Y({"src/lib/tasks/count-objects.ts"(){Z(),xl=new X(/([a-z-]+): (\d+)$/,(e,[t,n])=>{let r=Ko(t);Object.hasOwn(e,r)&&(e[r]=Jo(n))})}});function Cl(e){return js({author:null,branch:``,commit:``,root:!1,summary:{changes:0,insertions:0,deletions:0}},wl,e)}var wl,Tl=Y({"src/lib/parsers/parse-commit.ts"(){Z(),wl=[new X(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,n,r])=>{e.branch=t,e.commit=r,e.root=!!n}),new X(/\s*Author:\s(.+)/i,(e,[t])=>{let n=t.split(`<`),r=n.pop();!r||!r.includes(`@`)||(e.author={email:r.substr(0,r.length-1),name:n.join(`<`).trim()})}),new X(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(n,10)||0,e.summary.deletions=parseInt(r,10)||0}),new X(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0;let i=parseInt(n,10)||0;r===`-`?e.summary.deletions=i:r===`+`&&(e.summary.insertions=i)})]}});function El(e,t,n){return{commands:[`-c`,`core.abbrev=40`,`commit`,...Yo(e,`-m`),...t,...n],format:`utf-8`,parser:Cl}}function Dl(){return{commit(t,...n){let r=Os(arguments),i=e(t)||El(Go(t),Go(is(n[0],ds,[])),[...qo(is(n[1],cs,[])),...Ts(arguments,0,!0)]);return this._runTask(i,r)}};function e(e){return!ds(e)&&Zs(`git.commit: requires the commit message to be supplied as a string/string[]`)}}var Ol=Y({"src/lib/tasks/commit.ts"(){Tl(),Z(),rc()}});function kl(){return{firstCommit(){return this._runTask(Qs([`rev-list`,`--max-parents=0`,`HEAD`],!0),Os(arguments))}}}var Al=Y({"src/lib/tasks/first-commit.ts"(){Z(),rc()}});function jl(e,t){let n=[`hash-object`,e];return t&&n.push(`-w`),Qs(n,!0)}var Ml=Y({"src/lib/tasks/hash-object.ts"(){rc()}});function Nl(e,t,n){let r=String(n).trim(),i;if(i=Fl.exec(r))return new Pl(e,t,!1,i[1]);if(i=Il.exec(r))return new Pl(e,t,!0,i[1]);let a=``,o=r.split(` `);for(;o.length;)if(o.shift()===`in`){a=o.join(` `);break}return new Pl(e,t,/^re/i.test(r),a)}var Pl,Fl,Il,Ll=Y({"src/lib/responses/InitSummary.ts"(){Pl=class{constructor(e,t,n,r){this.bare=e,this.path=t,this.existing=n,this.gitDir=r}},Fl=/^Init.+ repository in (.+)$/,Il=/^Rein.+ in (.+)$/}});function Rl(e){return e.includes(Bl)}function zl(e=!1,t,n){let r=[`init`,...n];return e&&!Rl(r)&&r.splice(1,0,Bl),{commands:r,format:`utf-8`,parser(e){return Nl(r.includes(`--bare`),t,e)}}}var Bl,Vl=Y({"src/lib/tasks/init.ts"(){Ll(),Bl=`--bare`}});function Hl(e){for(let t=0;t<e.length;t++){let n=Wl.exec(e[t]);if(n)return`--${n[1]}`}return``}function Ul(e){return Wl.test(e)}var Wl,Gl=Y({"src/lib/args/log-format.ts"(){Wl=/^--(stat|numstat|name-only|name-status)(=|$)/}}),Kl,ql=Y({"src/lib/responses/DiffSummary.ts"(){Kl=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function Jl(e=``){let t=$l[e];return e=>js(new Kl,t,e,!1)}var Yl,Xl,Zl,Ql,$l,eu=Y({"src/lib/parsers/parse-diff-summary.ts"(){Gl(),ql(),Pc(),Z(),Yl=[new X(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,n,r=``])=>{e.files.push({file:t.trim(),changes:Jo(n),insertions:r.replace(/[^+]/g,``).length,deletions:r.replace(/[^-]/g,``).length,binary:!1})}),new X(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,n,r])=>{e.files.push({file:t.trim(),before:Jo(n),after:Jo(r),binary:!0})}),new X(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,n])=>{let r=/(\d+) i/.exec(n),i=/(\d+) d/.exec(n);e.changed=Jo(t),e.insertions=Jo(r?.[1]),e.deletions=Jo(i?.[1])})],Xl=[new X(/(\d+)\t(\d+)\t(.+)$/,(e,[t,n,r])=>{let i=Jo(t),a=Jo(n);e.changed++,e.insertions+=i,e.deletions+=a,e.files.push({file:r,changes:i+a,insertions:i,deletions:a,binary:!1})}),new X(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],Zl=[new X(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],Ql=[new X(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,n,r,i,a])=>{e.changed++,e.files.push({file:a??r,changes:0,insertions:0,deletions:0,binary:!1,status:$o(jc(t)&&t),from:$o(!!a&&r!==a&&r),similarity:Jo(n)})})],$l={"":Yl,"--stat":Yl,"--numstat":Xl,"--name-status":Ql,"--name-only":Zl}}});function tu(e,t){return t.reduce((t,n,r)=>(t[n]=e[r]||``,t),Object.create({diff:null}))}function nu(e=au,t=ou,n=``){let r=Jl(n);return function(n){let i=zo(n.trim(),!1,ru).map(function(n){let i=n.split(iu),a=tu(i[0].split(e),t);return i.length>1&&i[1].trim()&&(a.diff=r(i[1])),a});return{all:i,latest:i.length&&i[0]||null,total:i.length}}}var ru,iu,au,ou,su=Y({"src/lib/parsers/parse-list-log-summary.ts"(){Z(),eu(),Gl(),ru=`òòòòòò `,iu=` òò`,au=` ò `,ou=[`hash`,`date`,`message`,`refs`,`author_name`,`author_email`]}}),cu={};yo(cu,{diffSummaryTask:()=>lu,validateLogFormatConfig:()=>uu});function lu(e){let t=Hl(e),n=[`diff`];return t===``&&(t=`--stat`,n.push(`--stat=4096`)),n.push(...e),uu(n)||{commands:n,format:`utf-8`,parser:Jl(t)}}function uu(e){let t=e.filter(Ul);if(t.length>1)return Zs(`Summary flags are mutually exclusive - pick one of ${t.join(`,`)}`);if(t.length&&e.includes(`-z`))return Zs(`Summary flag ${t} parsing is not compatible with null termination option '-z'`)}var du=Y({"src/lib/tasks/diff.ts"(){Gl(),eu(),rc()}});function fu(e,t){let n=[],r=[];return Object.keys(e).forEach(t=>{n.push(t),r.push(String(e[t]))}),[n,r.join(t)]}function pu(e){return Object.keys(e).reduce((t,n)=>(n in _u||(t[n]=e[n]),t),{})}function mu(e={},t=[]){let n=is(e.splitter,us,au),[r,i]=fu(os(e.format)?e.format:{hash:`%H`,date:e.strictDate===!1?`%ai`:`%aI`,message:`%s`,refs:`%D`,body:e.multiLine?`%B`:`%b`,author_name:e.mailMap===!1?`%an`:`%aN`,author_email:e.mailMap===!1?`%ae`:`%aE`},n),a=[],o=[`--pretty=format:${ru}${i}${iu}`,...t],s=e.n||e[`max-count`]||e.maxCount;if(s&&o.push(`--max-count=${s}`),e.from||e.to){let t=e.symmetric===!1?`..`:`...`;a.push(`${e.from||``}${t}${e.to||``}`)}return us(e.file)&&o.push(`--follow`,So(e.file)),ws(pu(e),o),{fields:r,splitter:n,commands:[...o,...a]}}function hu(e,t,n){let r=nu(e,t,Hl(n));return{commands:[`log`,...n],format:`utf-8`,parser:r}}function gu(){return{log(...n){let r=Os(arguments),i=mu(Ds(arguments),qo(is(arguments[0],cs,[]))),a=t(...n)||uu(i.commands)||e(i);return this._runTask(a,r)}};function e(e){return hu(e.splitter,e.fields,e.commands)}function t(e,t){return us(e)&&us(t)&&Zs(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`)}}var _u,vu=Y({"src/lib/tasks/log.ts"(){Gl(),Eo(),su(),Z(),rc(),du(),_u=(e=>(e[e[`--pretty`]=0]=`--pretty`,e[e[`max-count`]=1]=`max-count`,e[e.maxCount=2]=`maxCount`,e[e.n=3]=`n`,e[e.file=4]=`file`,e[e.format=5]=`format`,e[e.from=6]=`from`,e[e.to=7]=`to`,e[e.splitter=8]=`splitter`,e[e.symmetric=9]=`symmetric`,e[e.mailMap=10]=`mailMap`,e[e.multiLine=11]=`multiLine`,e[e.strictDate=12]=`strictDate`,e))(_u||{})}}),yu,bu,xu=Y({"src/lib/responses/MergeSummary.ts"(){yu=class{constructor(e,t=null,n){this.reason=e,this.file=t,this.meta=n}toString(){return`${this.file}:${this.reason}`}},bu=class{constructor(){this.conflicts=[],this.merges=[],this.result=`success`}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(`, `)}`:`OK`}}}}),Su,Cu,wu=Y({"src/lib/responses/PullSummary.ts"(){Su=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},Cu=class{constructor(){this.remote=``,this.hash={local:``,remote:``},this.branch={local:``,remote:``},this.message=``}toString(){return this.message}}}});function Tu(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function Eu(e){let t=/^\s*(\d+)/.exec(e),n=/delta (\d+)/i.exec(e);return{count:Jo(t&&t[1]||`0`),delta:Jo(n&&n[1]||`0`)}}var Du,Ou=Y({"src/lib/parsers/parse-remote-objects.ts"(){Z(),Du=[new ys(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,n])=>{let r=t.toLowerCase(),i=Tu(e.remoteMessages);Object.assign(i,{[r]:Jo(n)})}),new ys(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,n])=>{let r=t.toLowerCase(),i=Tu(e.remoteMessages);Object.assign(i,{[r]:Jo(n)})}),new ys(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,n,r])=>{let i=Tu(e.remoteMessages);i.total=Eu(t),i.reused=Eu(n),i.packReused=Jo(r)})]}});function ku(e,t){return js({remoteMessages:new ju},Au,t)}var Au,ju,Mu=Y({"src/lib/parsers/parse-remote-messages.ts"(){Z(),Ou(),Au=[new ys(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...Du,new ys([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new ys([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,n,r])=>{e.remoteMessages.vulnerabilities={count:Jo(t),summary:n,url:r}})],ju=class{constructor(){this.all=[]}}}});function Nu(e,t){let n=js(new Cu,Ru,[e,t]);return n.message&&n}var Pu,Fu,Iu,Lu,Ru,zu,Bu,Vu=Y({"src/lib/parsers/parse-pull.ts"(){wu(),Z(),Mu(),Pu=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,Fu=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,Iu=/^(create|delete) mode \d+ (.+)/,Lu=[new X(Pu,(e,[t,n,r])=>{e.files.push(t),n&&(e.insertions[t]=n.length),r&&(e.deletions[t]=r.length)}),new X(Fu,(e,[t,,n,,r])=>n!==void 0||r!==void 0?(e.summary.changes=+t||0,e.summary.insertions=+n||0,e.summary.deletions=+r||0,!0):!1),new X(Iu,(e,[t,n])=>{Ho(e.files,n),Ho(t===`create`?e.created:e.deleted,n)})],Ru=[new X(/^from\s(.+)$/i,(e,[t])=>void(e.remote=t)),new X(/^fatal:\s(.+)$/,(e,[t])=>void(e.message=t)),new X(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,n,r,i])=>{e.branch.local=r,e.hash.local=t,e.branch.remote=i,e.hash.remote=n})],zu=(e,t)=>js(new Su,Lu,[e,t]),Bu=(e,t)=>Object.assign(new Su,zu(e,t),ku(e,t))}}),Hu,Uu,Wu,Gu=Y({"src/lib/parsers/parse-merge.ts"(){xu(),Z(),Vu(),Hu=[new X(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new X(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,n])=>{e.conflicts.push(new yu(t,n))}),new X(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,n,r])=>{e.conflicts.push(new yu(t,n,{deleteRef:r}))}),new X(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new yu(t,null))}),new X(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],Uu=(e,t)=>Object.assign(Wu(e,t),Bu(e,t)),Wu=e=>js(new bu,Hu,e)}});function Ku(e){return e.length?{commands:[`merge`,...e],format:`utf-8`,parser(e,t){let n=Uu(e,t);if(n.failed)throw new ko(n);return n}}:Zs(`Git.merge requires at least one option`)}var qu=Y({"src/lib/tasks/merge.ts"(){Ao(),Gu(),rc()}});function Ju(e,t,n){let r=n.includes(`deleted`),i=n.includes(`tag`)||/^refs\/tags/.test(e),a=!n.includes(`new`);return{deleted:r,tag:i,branch:!i,new:!a,alreadyUpdated:a,local:e,remote:t}}var Yu,Xu,Zu,Qu=Y({"src/lib/parsers/parse-push.ts"(){Z(),Mu(),Yu=[new X(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new X(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new X(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,n,r])=>{e.pushed.push(Ju(t,n,r))}),new X(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,n,r])=>{e.branch={...e.branch||{},local:t,remote:n,remoteName:r}}),new X(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,n,r,i])=>{e.update={head:{local:t,remote:n},hash:{from:r,to:i}}})],Xu=(e,t)=>{let n=Zu(e,t),r=ku(e,t);return{...n,...r}},Zu=(e,t)=>js({pushed:[]},Yu,[e,t])}}),$u={};yo($u,{pushTagsTask:()=>ed,pushTask:()=>td});function ed(e={},t){return Ho(t,`--tags`),td(e,t)}function td(e={},t){let n=[`push`,...t];return e.branch&&n.splice(1,0,e.branch),e.remote&&n.splice(1,0,e.remote),Wo(n,`-v`),Ho(n,`--verbose`),Ho(n,`--porcelain`),{commands:n,format:`utf-8`,parser:Xu}}var nd=Y({"src/lib/tasks/push.ts"(){Qu(),Z()}});function rd(){return{showBuffer(){let e=[`show`,...Ts(arguments,1)];return e.includes(`--binary`)||e.splice(1,0,`--binary`),this._runTask($s(e),Os(arguments))},show(){let e=[`show`,...Ts(arguments,1)];return this._runTask(Qs(e),Os(arguments))}}}var id=Y({"src/lib/tasks/show.ts"(){Z(),rc()}}),ad,od,sd=Y({"src/lib/responses/FileStatusSummary.ts"(){ad=/^(.+)\0(.+)$/,od=class{constructor(e,t,n){if(this.path=e,this.index=t,this.working_dir=n,t===`R`||n===`R`){let t=ad.exec(e)||[null,e,e];this.from=t[2]||``,this.path=t[1]||``}}}}});function cd(e){let[t,n]=e.split(es);return{from:n||t,to:t}}function ld(e,t,n){return[`${e}${t}`,n]}function ud(e,...t){return t.map(t=>ld(e,t,(e,t)=>e.conflicted.push(t)))}function dd(e,t){let n=t.trim();switch(` `){case n.charAt(2):return r(n.charAt(0),n.charAt(1),n.slice(3));case n.charAt(1):return r(` `,n.charAt(0),n.slice(2));default:return}function r(t,n,r){let i=`${t}${n}`,a=pd.get(i);a&&a(e,r),i!==`##`&&i!==`!!`&&e.files.push(new od(r,t,n))}}var fd,pd,md,hd=Y({"src/lib/responses/StatusSummary.ts"(){Z(),sd(),fd=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},pd=new Map([ld(` `,`A`,(e,t)=>e.created.push(t)),ld(` `,`D`,(e,t)=>e.deleted.push(t)),ld(` `,`M`,(e,t)=>e.modified.push(t)),ld(`A`,` `,(e,t)=>{e.created.push(t),e.staged.push(t)}),ld(`A`,`M`,(e,t)=>{e.created.push(t),e.staged.push(t),e.modified.push(t)}),ld(`D`,` `,(e,t)=>{e.deleted.push(t),e.staged.push(t)}),ld(`M`,` `,(e,t)=>{e.modified.push(t),e.staged.push(t)}),ld(`M`,`M`,(e,t)=>{e.modified.push(t),e.staged.push(t)}),ld(`R`,` `,(e,t)=>{e.renamed.push(cd(t))}),ld(`R`,`M`,(e,t)=>{let n=cd(t);e.renamed.push(n),e.modified.push(n.to)}),ld(`!`,`!`,(e,t)=>{(e.ignored=e.ignored||[]).push(t)}),ld(`?`,`?`,(e,t)=>e.not_added.push(t)),...ud(`A`,`A`,`U`),...ud(`D`,`D`,`U`),...ud(`U`,`A`,`D`,`U`),[`##`,(e,t)=>{let n=/ahead (\d+)/,r=/behind (\d+)/,i=/^(.+?(?=(?:\.{3}|\s|$)))/,a=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/,s=n.exec(t);e.ahead=s&&+s[1]||0,s=r.exec(t),e.behind=s&&+s[1]||0,s=i.exec(t),e.current=is(s?.[1],us,null),s=a.exec(t),e.tracking=is(s?.[1],us,null),s=o.exec(t),s&&(e.current=is(s?.[1],us,e.current)),e.detached=/\(no branch\)/.test(t)}]]),md=function(e){let t=e.split(es),n=new fd;for(let e=0,r=t.length;e<r;){let r=t[e++].trim();r&&(r.charAt(0)===`R`&&(r+=es+(t[e++]||``)),dd(n,r))}return n}}});function gd(e){return{format:`utf-8`,commands:[`status`,`--porcelain`,`-b`,`-u`,`--null`,...e.filter(e=>!_d.includes(e))],parser(e){return md(e)}}}var _d,vd=Y({"src/lib/tasks/status.ts"(){hd(),_d=[`--null`,`-z`]}});function yd(e=0,t=0,n=0,r=``,i=!0){return Object.defineProperty({major:e,minor:t,patch:n,agent:r,installed:i},`toString`,{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function bd(){return yd(0,0,0,``,!1)}function xd(){return{version(){return this._runTask({commands:[`--version`],format:`utf-8`,parser:Sd,onError(e,t,n,r){if(e.exitCode===-2)return n(Buffer.from(Cd));r(t)}})}}}function Sd(e){return e===Cd?bd():js(yd(0,0,0,e),wd,e)}var Cd,wd,Td=Y({"src/lib/tasks/version.ts"(){Z(),Cd=`installed=false`,wd=[new X(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,n,r,i=``])=>{Object.assign(e,yd(Jo(t),Jo(n),Jo(r),i))}),new X(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,n,r,i=``])=>{Object.assign(e,yd(Jo(t),Jo(n),r,i))})]}});function Ed(e,t,n,...r){return us(n)?t(n,is(r[0],us),Ts(arguments)):Zs(`git.${e}() requires a string 'repoPath'`)}function Dd(){return{clone(e,...t){return this._runTask(Ed(`clone`,Od,is(e,us),...t),Os(arguments))},mirror(e,...t){return this._runTask(Ed(`mirror`,kd,is(e,us),...t),Os(arguments))}}}var Od,kd,Ad=Y({"src/lib/tasks/clone.ts"(){rc(),Z(),Eo(),Od=(e,t,n)=>{let r=[`clone`,...n];return us(e)&&r.push(So(e)),us(t)&&r.push(So(t)),Qs(r)},kd=(e,t,n)=>(Ho(n,`--mirror`),Od(e,t,n))}}),jd={};yo(jd,{SimpleGitApi:()=>Md});var Md,Nd=Y({"src/lib/simple-git-api.ts"(){pl(),hl(),vl(),Sl(),Ol(),Ac(),Al(),Hc(),Ml(),Vl(),vu(),qu(),nd(),id(),vd(),rc(),Td(),Z(),Ad(),Md=class{constructor(e){this._executor=e}_runTask(e,t){let n=this._executor.chain(),r=n.push(e);return t&&dl(e,r,t),Object.create(this,{then:{value:r.then.bind(r)},catch:{value:r.catch.bind(r)},_executor:{value:n}})}add(e){return this._runTask(Qs([`add`,...Go(e)]),Os(arguments))}cwd(e){let t=Os(arguments);return typeof e==`string`?this._runTask(ml(e,this._executor),t):typeof e?.path==`string`?this._runTask(ml(e.path,e.root&&this._executor||void 0),t):this._runTask(Zs(`Git.cwd: workingDirectory must be supplied as a string`),t)}hashObject(e,t){return this._runTask(jl(e,t===!0),Os(arguments))}init(e){return this._runTask(zl(e===!0,this._executor.cwd,Ts(arguments)),Os(arguments))}merge(){return this._runTask(Ku(Ts(arguments)),Os(arguments))}mergeFromTo(e,t){return us(e)&&us(t)?this._runTask(Ku([e,t,...Ts(arguments)]),Os(arguments,!1)):this._runTask(Zs(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`))}outputHandler(e){return this._executor.outputHandler=e,this}push(){let e=td({remote:is(arguments[0],us),branch:is(arguments[1],us)},Ts(arguments));return this._runTask(e,Os(arguments))}stash(){return this._runTask(Qs([`stash`,...Ts(arguments)]),Os(arguments))}status(){return this._runTask(gd(Ts(arguments)),Os(arguments))}},Object.assign(Md.prototype,_l(),Dd(),Dl(),Oc(),bl(),kl(),Lc(),gu(),rd(),xd())}}),Pd={};yo(Pd,{Scheduler:()=>Id});var Fd,Id,Ld=Y({"src/lib/runners/scheduler.ts"(){Z(),el(),Fd=(()=>{let e=0;return()=>{e++;let{promise:t,done:n}=(0,po.createDeferred)();return{promise:t,done:n,id:e}}})(),Id=class{constructor(e=2){this.concurrency=e,this.logger=$c(``,`scheduler`),this.pending=[],this.running=[],this.logger(`Constructed, concurrency=%s`,e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger(`Schedule attempt ignored, pending=%s running=%s concurrency=%s`,this.pending.length,this.running.length,this.concurrency);return}let e=Ho(this.running,this.pending.shift());this.logger(`Attempting id=%s`,e.id),e.done(()=>{this.logger(`Completing id=`,e.id),Wo(this.running,e),this.schedule()})}next(){let{promise:e,id:t}=Ho(this.pending,Fd());return this.logger(`Scheduling id=%s`,t),this.schedule(),e}}}}),Rd={};yo(Rd,{applyPatchTask:()=>zd});function zd(e,t){return Qs([`apply`,...t,...e])}var Bd=Y({"src/lib/tasks/apply-patch.ts"(){rc()}});function Vd(e,t){return{branch:e,hash:t,success:!0}}function Hd(e){return{branch:e,hash:null,success:!1}}var Ud,Wd=Y({"src/lib/responses/BranchDeleteSummary.ts"(){Ud=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function Gd(e,t){return t===1&&qd.test(e)}var Kd,qd,Jd,Yd,Xd=Y({"src/lib/parsers/parse-branch-delete.ts"(){Wd(),Z(),Kd=/(\S+)\s+\(\S+\s([^)]+)\)/,qd=/^error[^']+'([^']+)'/m,Jd=[new X(Kd,(e,[t,n])=>{let r=Vd(t,n);e.all.push(r),e.branches[t]=r}),new X(qd,(e,[t])=>{let n=Hd(t);e.errors.push(n),e.all.push(n),e.branches[t]=n})],Yd=(e,t)=>js(new Ud,Jd,[e,t])}}),Zd,Qd=Y({"src/lib/responses/BranchSummary.ts"(){Zd=class{constructor(){this.all=[],this.branches={},this.current=``,this.detached=!1}push(e,t,n,r,i){e===`*`&&(this.detached=t,this.current=n),this.all.push(n),this.branches[n]={current:e===`*`,linkedWorkTree:e===`+`,name:n,commit:r,label:i}}}}});function $d(e){return e?e.charAt(0):``}function ef(e,t=!1){return js(new Zd,t?[nf]:tf,e)}var tf,nf,rf=Y({"src/lib/parsers/parse-branch.ts"(){Qd(),Z(),tf=[new X(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,n,r,i])=>{e.push($d(t),!0,n,r,i)}),new X(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,n,r,i])=>{e.push($d(t),!1,n,r,i)})],nf=new X(/^(\S+)$/s,(e,[t])=>{e.push(`*`,!1,t,``,``)})}}),af={};yo(af,{branchLocalTask:()=>cf,branchTask:()=>sf,containsDeleteBranchCommand:()=>of,deleteBranchTask:()=>uf,deleteBranchesTask:()=>lf});function of(e){let t=[`-d`,`-D`,`--delete`];return e.some(e=>t.includes(e))}function sf(e){let t=of(e),n=e.includes(`--show-current`),r=[`branch`,...e];return r.length===1&&r.push(`-a`),r.includes(`-v`)||r.splice(1,0,`-v`),{format:`utf-8`,commands:r,parser(e,r){return t?Yd(e,r).all[0]:ef(e,n)}}}function cf(){return{format:`utf-8`,commands:[`branch`,`-v`],parser(e){return ef(e)}}}function lf(e,t=!1){return{format:`utf-8`,commands:[`branch`,`-v`,t?`-D`:`-d`,...e],parser(e,t){return Yd(e,t)},onError({exitCode:e,stdOut:t},n,r,i){if(!Gd(String(n),e))return i(n);r(t)}}}function uf(e,t=!1){let n={format:`utf-8`,commands:[`branch`,`-v`,t?`-D`:`-d`,e],parser(t,n){return Yd(t,n).branches[e]},onError({exitCode:e,stdErr:t,stdOut:r},i,a,o){if(!Gd(String(i),e))return o(i);throw new ko(n.parser(Xo(r),Xo(t)),String(i))}};return n}var df=Y({"src/lib/tasks/branch.ts"(){Ao(),Xd(),rf(),Z()}});function ff(e){let t=e.trim().replace(/^["']|["']$/g,``);return t&&fe(t)}var pf,mf=Y({"src/lib/responses/CheckIgnore.ts"(){pf=e=>e.split(/\n/g).map(ff).filter(Boolean)}}),hf={};yo(hf,{checkIgnoreTask:()=>gf});function gf(e){return{commands:[`check-ignore`,...e],format:`utf-8`,parser:pf}}var _f=Y({"src/lib/tasks/check-ignore.ts"(){mf()}});function vf(e,t){return js({raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]},yf,[e,t])}var yf,bf=Y({"src/lib/parsers/parse-fetch.ts"(){Z(),yf=[new X(/From (.+)$/,(e,[t])=>{e.remote=t}),new X(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.branches.push({name:t,tracking:n})}),new X(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.tags.push({name:t,tracking:n})}),new X(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new X(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,n,r,i])=>{e.updated.push({name:r,tracking:i,to:n,from:t})})]}}),xf={};yo(xf,{fetchTask:()=>Cf});function Sf(e){return/^--upload-pack(=|$)/.test(e)}function Cf(e,t,n){let r=[`fetch`,...n];return e&&t&&r.push(e,t),r.find(Sf)?Zs(`git.fetch: potential exploit argument blocked.`):{commands:r,format:`utf-8`,parser:vf}}var wf=Y({"src/lib/tasks/fetch.ts"(){bf(),rc()}});function Tf(e){return js({moves:[]},Ef,e)}var Ef,Df=Y({"src/lib/parsers/parse-move.ts"(){Z(),Ef=[new X(/^Renaming (.+) to (.+)$/,(e,[t,n])=>{e.moves.push({from:t,to:n})})]}}),Of={};yo(Of,{moveTask:()=>kf});function kf(e,t){return{commands:[`mv`,`-v`,...Go(e),t],format:`utf-8`,parser:Tf}}var Af=Y({"src/lib/tasks/move.ts"(){Df(),Z()}}),jf={};yo(jf,{pullTask:()=>Mf});function Mf(e,t,n){let r=[`pull`,...n];return e&&t&&r.splice(1,0,e,t),{commands:r,format:`utf-8`,parser(e,t){return Bu(e,t)},onError(e,t,n,r){let i=Nu(Xo(e.stdOut),Xo(e.stdErr));if(i)return r(new ko(i));r(t)}}}var Nf=Y({"src/lib/tasks/pull.ts"(){Ao(),Vu(),Z()}});function Pf(e){let t={};return If(e,([e])=>t[e]={name:e}),Object.values(t)}function Ff(e){let t={};return If(e,([e,n,r])=>{Object.hasOwn(t,e)||(t[e]={name:e,refs:{fetch:``,push:``}}),r&&n&&(t[e].refs[r.replace(/[^a-z]/g,``)]=n)}),Object.values(t)}function If(e,t){Bo(e,e=>t(e.split(/\s+/)))}var Lf=Y({"src/lib/responses/GetRemoteSummary.ts"(){Z()}}),Rf={};yo(Rf,{addRemoteTask:()=>zf,getRemotesTask:()=>Bf,listRemotesTask:()=>Vf,remoteTask:()=>Hf,removeRemoteTask:()=>Uf});function zf(e,t,n){return Qs([`remote`,`add`,...n,e,t])}function Bf(e){let t=[`remote`];return e&&t.push(`-v`),{commands:t,format:`utf-8`,parser:e?Ff:Pf}}function Vf(e){let t=[...e];return t[0]!==`ls-remote`&&t.unshift(`ls-remote`),Qs(t)}function Hf(e){let t=[...e];return t[0]!==`remote`&&t.unshift(`remote`),Qs(t)}function Uf(e){return Qs([`remote`,`remove`,e])}var Wf=Y({"src/lib/tasks/remote.ts"(){Lf(),rc()}}),Gf={};yo(Gf,{stashListTask:()=>Kf});function Kf(e={},t){let n=mu(e),r=[`stash`,`list`,...n.commands,...t],i=nu(n.splitter,n.fields,Hl(r));return uu(r)||{commands:r,format:`utf-8`,parser:i}}var qf=Y({"src/lib/tasks/stash-list.ts"(){Gl(),su(),du(),vu()}}),Jf={};yo(Jf,{addSubModuleTask:()=>Yf,initSubModuleTask:()=>Xf,subModuleTask:()=>Zf,updateSubModuleTask:()=>Qf});function Yf(e,t){return Zf([`add`,e,t])}function Xf(e){return Zf([`init`,...e])}function Zf(e){let t=[...e];return t[0]!==`submodule`&&t.unshift(`submodule`),Qs(t)}function Qf(e){return Zf([`update`,...e])}var $f=Y({"src/lib/tasks/sub-module.ts"(){rc()}});function ep(e,t){let n=Number.isNaN(e);return n===Number.isNaN(t)?n?tp(e,t):0:n?1:-1}function tp(e,t){return e===t?0:e>t?1:-1}function np(e){return e.trim()}function rp(e){return typeof e==`string`&&parseInt(e.replace(/^\D+/g,``),10)||0}var ip,ap,op=Y({"src/lib/responses/TagList.ts"(){ip=class{constructor(e,t){this.all=e,this.latest=t}},ap=function(e,t=!1){let n=e.split(`
22
- `).map(np).filter(Boolean);t||n.sort(function(e,t){let n=e.split(`.`),r=t.split(`.`);if(n.length===1||r.length===1)return ep(rp(n[0]),rp(r[0]));for(let e=0,t=Math.max(n.length,r.length);e<t;e++){let t=tp(rp(n[e]),rp(r[e]));if(t)return t}return 0});let r=t?n[0]:[...n].reverse().find(e=>e.indexOf(`.`)>=0);return new ip(n,r)}}}),sp={};yo(sp,{addAnnotatedTagTask:()=>up,addTagTask:()=>lp,tagListTask:()=>cp});function cp(e=[]){let t=e.some(e=>/^--sort=/.test(e));return{format:`utf-8`,commands:[`tag`,`-l`,...e],parser(e){return ap(e,t)}}}function lp(e){return{format:`utf-8`,commands:[`tag`,e],parser(){return{name:e}}}}function up(e,t){return{format:`utf-8`,commands:[`tag`,`-a`,`-m`,t,e],parser(){return{name:e}}}}var dp=Y({"src/lib/tasks/tag.ts"(){op()}}),fp=vo({"src/git.js"(e,t){var{GitExecutor:n}=(ul(),xo(cl)),{SimpleGitApi:r}=(Nd(),xo(jd)),{Scheduler:i}=(Ld(),xo(Pd)),{adhocExecTask:a,configurationErrorTask:o}=(rc(),xo(Ys)),{asArray:s,filterArray:c,filterPrimitives:l,filterString:u,filterStringOrStringArray:d,filterType:f,getTrailingOptions:p,trailingFunctionArgument:m,trailingOptionsArgument:h}=(Z(),xo(Ns)),{applyPatchTask:g}=(Bd(),xo(Rd)),{branchTask:_,branchLocalTask:v,deleteBranchesTask:y,deleteBranchTask:b}=(df(),xo(af)),{checkIgnoreTask:x}=(_f(),xo(hf)),{checkIsRepoTask:S}=(Hs(),xo(Ps)),{cleanWithOptionsTask:C,isCleanOptionsArray:w}=(_c(),xo(ic)),{diffSummaryTask:ee}=(du(),xo(cu)),{fetchTask:T}=(wf(),xo(xf)),{moveTask:E}=(Af(),xo(Of)),{pullTask:D}=(Nf(),xo(jf)),{pushTagsTask:O}=(nd(),xo($u)),{addRemoteTask:k,getRemotesTask:A,listRemotesTask:te,remoteTask:ne,removeRemoteTask:j}=(Wf(),xo(Rf)),{getResetMode:M,resetTask:N}=(Yc(),xo(Uc)),{stashListTask:P}=(qf(),xo(Gf)),{addSubModuleTask:re,initSubModuleTask:ie,subModuleTask:ae,updateSubModuleTask:F}=($f(),xo(Jf)),{addAnnotatedTagTask:oe,addTagTask:I,tagListTask:L}=(dp(),xo(sp)),{straightThroughBufferTask:R,straightThroughStringTask:z}=(rc(),xo(Ys));function B(e,t){this._plugins=t,this._executor=new n(e.baseDir,new i(e.maxConcurrentProcesses),t),this._trimmed=e.trimmed}(B.prototype=Object.create(r.prototype)).constructor=B,B.prototype.customBinary=function(e){return this._plugins.reconfigure(`binary`,e),this},B.prototype.env=function(e,t){return arguments.length===1&&typeof e==`object`?this._executor.env=e:(this._executor.env=this._executor.env||{})[e]=t,this},B.prototype.stashList=function(e){return this._runTask(P(h(arguments)||{},c(e)&&e||[]),m(arguments))},B.prototype.mv=function(e,t){return this._runTask(E(e,t),m(arguments))},B.prototype.checkoutLatestTag=function(e){var t=this;return this.pull(function(){t.tags(function(n,r){t.checkout(r.latest,e)})})},B.prototype.pull=function(e,t,n,r){return this._runTask(D(f(e,u),f(t,u),p(arguments)),m(arguments))},B.prototype.fetch=function(e,t){return this._runTask(T(f(e,u),f(t,u),p(arguments)),m(arguments))},B.prototype.silent=function(e){return this._runTask(a(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},B.prototype.tags=function(e,t){return this._runTask(L(p(arguments)),m(arguments))},B.prototype.rebase=function(){return this._runTask(z([`rebase`,...p(arguments)]),m(arguments))},B.prototype.reset=function(e){return this._runTask(N(M(e),p(arguments)),m(arguments))},B.prototype.revert=function(e){let t=m(arguments);return typeof e==`string`?this._runTask(z([`revert`,...p(arguments,0,!0),e]),t):this._runTask(o(`Commit must be a string`),t)},B.prototype.addTag=function(e){let t=typeof e==`string`?I(e):o(`Git.addTag requires a tag name`);return this._runTask(t,m(arguments))},B.prototype.addAnnotatedTag=function(e,t){return this._runTask(oe(e,t),m(arguments))},B.prototype.deleteLocalBranch=function(e,t,n){return this._runTask(b(e,typeof t==`boolean`?t:!1),m(arguments))},B.prototype.deleteLocalBranches=function(e,t,n){return this._runTask(y(e,typeof t==`boolean`?t:!1),m(arguments))},B.prototype.branch=function(e,t){return this._runTask(_(p(arguments)),m(arguments))},B.prototype.branchLocal=function(e){return this._runTask(v(),m(arguments))},B.prototype.raw=function(e){let t=!Array.isArray(e),n=[].slice.call(t?arguments:e,0);for(let e=0;e<n.length&&t;e++)if(!l(n[e])){n.splice(e,n.length-e);break}n.push(...p(arguments,0,!0));var r=m(arguments);return n.length?this._runTask(z(n,this._trimmed),r):this._runTask(o(`Raw: must supply one or more command to execute`),r)},B.prototype.submoduleAdd=function(e,t,n){return this._runTask(re(e,t),m(arguments))},B.prototype.submoduleUpdate=function(e,t){return this._runTask(F(p(arguments,!0)),m(arguments))},B.prototype.submoduleInit=function(e,t){return this._runTask(ie(p(arguments,!0)),m(arguments))},B.prototype.subModule=function(e,t){return this._runTask(ae(p(arguments)),m(arguments))},B.prototype.listRemote=function(){return this._runTask(te(p(arguments)),m(arguments))},B.prototype.addRemote=function(e,t,n){return this._runTask(k(e,t,p(arguments)),m(arguments))},B.prototype.removeRemote=function(e,t){return this._runTask(j(e),m(arguments))},B.prototype.getRemotes=function(e,t){return this._runTask(A(e===!0),m(arguments))},B.prototype.remote=function(e,t){return this._runTask(ne(p(arguments)),m(arguments))},B.prototype.tag=function(e,t){let n=p(arguments);return n[0]!==`tag`&&n.unshift(`tag`),this._runTask(z(n),m(arguments))},B.prototype.updateServerInfo=function(e){return this._runTask(z([`update-server-info`]),m(arguments))},B.prototype.pushTags=function(e,t){let n=O({remote:f(e,u)},p(arguments));return this._runTask(n,m(arguments))},B.prototype.rm=function(e){return this._runTask(z([`rm`,`-f`,...s(e)]),m(arguments))},B.prototype.rmKeepLocal=function(e){return this._runTask(z([`rm`,`--cached`,...s(e)]),m(arguments))},B.prototype.catFile=function(e,t){return this._catFile(`utf-8`,arguments)},B.prototype.binaryCatFile=function(){return this._catFile(`buffer`,arguments)},B.prototype._catFile=function(e,t){var n=m(t),r=[`cat-file`],i=t[0];if(typeof i==`string`)return this._runTask(o(`Git.catFile: options must be supplied as an array of strings`),n);Array.isArray(i)&&r.push.apply(r,i);let a=e===`buffer`?R(r):z(r);return this._runTask(a,n)},B.prototype.diff=function(e,t){let n=u(e)?o(`git.diff: supplying options as a single string is no longer supported, switch to an array of strings`):z([`diff`,...p(arguments)]);return this._runTask(n,m(arguments))},B.prototype.diffSummary=function(){return this._runTask(ee(p(arguments,1)),m(arguments))},B.prototype.applyPatch=function(e){let t=d(e)?g(s(e),p([].slice.call(arguments,1))):o(`git.applyPatch requires one or more string patches as the first argument`);return this._runTask(t,m(arguments))},B.prototype.revparse=function(){let e=[`rev-parse`,...p(arguments,!0)];return this._runTask(z(e,!0),m(arguments))},B.prototype.clean=function(e,t,n){let r=w(e),i=r&&e.join(``)||f(e,u)||``,a=p([].slice.call(arguments,r?1:0));return this._runTask(C(i,a),m(arguments))},B.prototype.exec=function(e){return this._runTask({commands:[],format:`utf-8`,parser(){typeof e==`function`&&e()}})},B.prototype.clearQueue=function(){return this._runTask(a(()=>console.warn(`simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.`)))},B.prototype.checkIgnore=function(e,t){return this._runTask(x(s(f(e,d,[]))),m(arguments))},B.prototype.checkIsRepo=function(e,t){return this._runTask(S(f(e,u)),m(arguments))},t.exports=B}});Eo(),Oo();var pp=class extends Do{constructor(e,t){super(void 0,t),this.config=e}};Oo(),Oo();var mp=class extends Do{constructor(e,t,n){super(e,n),this.task=e,this.plugin=t,Object.setPrototypeOf(this,new.target.prototype)}};Ao(),Mo(),Hs(),_c(),Ac(),Pc(),Hc(),Yc();function hp(e){if(e)return[{type:`spawn.before`,action(t,n){e.aborted&&n.kill(new mp(void 0,`abort`,`Abort already signaled`))}},{type:`spawn.after`,action(t,n){function r(){n.kill(new mp(void 0,`abort`,`Abort signal received`))}e.addEventListener(`abort`,r),n.spawned.on(`close`,()=>e.removeEventListener(`abort`,r))}}]}function gp(e){return typeof e==`string`&&e.trim().toLowerCase()===`-c`}function _p(e,t){if(typeof t!=`string`||!t.includes(e))return!1;let n=t.trim().replace(/\0/g,``);return/^(--no)?-{1,2}[\dlsqvnobucj]+(\s|$)/.test(n)}function vp(e,t,n=String(e)){let r=typeof e==`string`?RegExp(`\\s*${e}`,`i`):e;return function(e,i,a){if(e[t]!==!0&&gp(i)&&r.test(a))throw new mp(void 0,`unsafe`,`Configuring ${n} is not permitted without enabling ${t}`)}}var yp=[vp(/^\s*protocol(.[a-z]+)?.allow/i,`allowUnsafeProtocolOverride`,`protocol.allow`),vp(`core.sshCommand`,`allowUnsafeSshCommand`),vp(`core.gitProxy`,`allowUnsafeGitProxy`),vp(`core.hooksPath`,`allowUnsafeHooksPath`),vp(`diff.external`,`allowUnsafeDiffExternal`)];function bp(e,t){if(/^\s*--(upload|receive)-pack/.test(e))throw new mp(void 0,`unsafe`,`Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`);if(t===`clone`&&_p(`u`,e))throw new mp(void 0,`unsafe`,`Use of clone with option -u is not permitted without enabling allowUnsafePack`);if(t===`push`&&/^\s*--exec\b/.test(e))throw new mp(void 0,`unsafe`,`Use of push with option --exec is not permitted without enabling allowUnsafePack`)}function xp({allowUnsafePack:e=!1,...t}={}){return{type:`spawn.args`,action(n,r){return n.forEach((i,a)=>{let o=a<n.length?n[a+1]:``;e||bp(i,r.method),yp.forEach(e=>e(t,i,o))}),n}}}Z();function Sp(e){let t=Yo(e,`-c`);return{type:`spawn.args`,action(e){return[...t,...e]}}}Z();var Cp=(0,po.deferred)().promise;function wp({onClose:e=!0,onExit:t=50}={}){function n(){let n=-1,i={close:(0,po.deferred)(),closeTimeout:(0,po.deferred)(),exit:(0,po.deferred)(),exitTimeout:(0,po.deferred)()},a=Promise.race([e===!1?Cp:i.closeTimeout.promise,t===!1?Cp:i.exitTimeout.promise]);return r(e,i.close,i.closeTimeout),r(t,i.exit,i.exitTimeout),{close(e){n=e,i.close.done()},exit(e){n=e,i.exit.done()},get exitCode(){return n},result:a}}function r(e,t,n){e!==!1&&(e===!0?t.promise:t.promise.then(()=>Qo(e))).then(n.done)}return{type:`spawn.after`,async action(e,{spawned:t,close:r}){let i=n(),a=!0,o=()=>void(a=!1);t.stdout?.on(`data`,o),t.stderr?.on(`data`,o),t.on(`error`,o),t.on(`close`,e=>i.close(e)),t.on(`exit`,e=>i.exit(e));try{await i.result,a&&await Qo(50),r(i.exitCode)}catch(e){r(i.exitCode,e)}}}}Z();var Tp=`Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`,Ep=`Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;function Dp(e){return!e||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(e)}function Op(e,t){if(e.length<1||e.length>2)throw new mp(void 0,`binary`,Tp);if(e.some(Dp))if(t)console.warn(Ep);else throw new mp(void 0,`binary`,Ep);let[n,r]=e;return{binary:n,prefix:r}}function kp(e,t=[`git`],n=!1){let r=Op(Go(t),n);e.on(`binary`,e=>{r=Op(Go(e),n)}),e.append(`spawn.binary`,()=>r.binary),e.append(`spawn.args`,e=>r.prefix?[r.prefix,...e]:e)}Oo();function Ap(e){return!!(e.exitCode&&e.stdErr.length)}function jp(e){return Buffer.concat([...e.stdOut,...e.stdErr])}function Mp(e=!1,t=Ap,n=jp){return(r,i)=>!e&&r||!t(i)?r:n(i)}function Np(e){return{type:`task.error`,action(t,n){let r=e(t.error,{stdErr:n.stdErr,stdOut:n.stdOut,exitCode:n.exitCode});return Buffer.isBuffer(r)?{error:new Do(void 0,r.toString(`utf-8`))}:{error:r}}}}Z();var Pp=class{constructor(){this.plugins=new Set,this.events=new Oe}on(e,t){this.events.on(e,t)}reconfigure(e,t){this.events.emit(e,t)}append(e,t){let n=Ho(this.plugins,{type:e,action:t});return()=>this.plugins.delete(n)}add(e){let t=[];return Go(e).forEach(e=>e&&this.plugins.add(Ho(t,e))),()=>{t.forEach(e=>this.plugins.delete(e))}}exec(e,t,n){let r=t,i=Object.freeze(Object.create(n));for(let t of this.plugins)t.type===e&&(r=t.action(r,i));return r}};Z();function Fp(e){let t=`--progress`,n=[`checkout`,`clone`,`fetch`,`pull`,`push`];return[{type:`spawn.args`,action(e,r){return n.includes(r.method)?Uo(e,t):e}},{type:`spawn.after`,action(n,r){r.commands.includes(t)&&r.spawned.stderr?.on(`data`,t=>{let n=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(t.toString(`utf8`));n&&e({method:r.method,stage:Ip(n[1]),progress:Jo(n[2]),processed:Jo(n[3]),total:Jo(n[4])})})}}]}function Ip(e){return String(e.toLowerCase().split(` `,1))||`unknown`}Z();function Lp(e){let t=Zo(e,[`uid`,`gid`]);return{type:`spawn.options`,action(e){return{...t,...e}}}}function Rp({block:e,stdErr:t=!0,stdOut:n=!0}){if(e>0)return{type:`spawn.after`,action(r,i){let a;function o(){a&&clearTimeout(a),a=setTimeout(c,e)}function s(){i.spawned.stdout?.off(`data`,o),i.spawned.stderr?.off(`data`,o),i.spawned.off(`exit`,s),i.spawned.off(`close`,s),a&&clearTimeout(a)}function c(){s(),i.kill(new mp(void 0,`timeout`,`block timeout reached`))}n&&i.spawned.stdout?.on(`data`,o),t&&i.spawned.stderr?.on(`data`,o),i.spawned.on(`exit`,s),i.spawned.on(`close`,s),o()}}}Eo();function zp(){return{type:`spawn.args`,action(e){let t=[],n;function r(e){(n||=[]).push(...e)}for(let n=0;n<e.length;n++){let i=e[n];if(Co(i)){r(wo(i));continue}if(i===`--`){r(e.slice(n+1).flatMap(e=>Co(e)&&wo(e)||e));break}t.push(i)}return n?[...t,`--`,...n.map(String)]:t}}}Z();var Bp=fp();function Vp(e,t){let n=new Pp,r=xs(e&&(typeof e==`string`?{baseDir:e}:e)||{},t);if(!Vo(r.baseDir))throw new pp(r,`Cannot use simple-git on a directory that does not exist`);return Array.isArray(r.config)&&n.add(Sp(r.config)),n.add(xp(r.unsafe)),n.add(wp(r.completion)),r.abort&&n.add(hp(r.abort)),r.progress&&n.add(Fp(r.progress)),r.timeout&&n.add(Rp(r.timeout)),r.spawnOptions&&n.add(Lp(r.spawnOptions)),n.add(zp()),n.add(Np(Mp(!0))),r.errors&&n.add(Np(r.errors)),kp(n,r.binary,r.unsafe?.allowUnsafeCustomBinary),new Bp(r,n)}Ao();var Hp=Vp;const Up=`.expect`,Wp=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`,`.cts`,`.cjs`],Gp=new Set([`node_modules`,`dist`,`build`,`.git`,`.next`,`.turbo`,`coverage`,`.nyc_output`,`.cache`,`.repos`,`.specs`,`__snapshots__`,`__fixtures__`]);var Kp=class extends S.ErrorClass(`GitError`)({_tag:S.tag(`GitError`),operation:S.String,cause:S.Defect}){message=`Git error during "${this.operation}"`},qp=class extends S.ErrorClass(`FindRepoRootError`)({_tag:S.tag(`FindRepoRootError`),cause:S.Defect}){message=`Could not find git repository root`},Jp=class extends C.Service()(`@supervisor/GitRepoRoot`){},Yp=class e extends C.Service()(`@supervisor/Git`,{make:u.gen(function*(){let e=yield*p.FileSystem,t=e=>u.gen(function*(){let t=yield*Jp;return yield*u.tryPromise({try:()=>Hp(t).raw(e.args),catch:t=>new Kp({operation:e.operation,cause:t})}).pipe(u.map(e.trim?xe.trim:Se.identity))}),n=e=>u.tryPromise({try:()=>Hp(e).revparse([`--show-toplevel`]),catch:e=>new qp({cause:e})}).pipe(u.map(xe.trim)),r=e=>t=>u.gen(function*(){let r=yield*n(e);return yield*t.pipe(u.provideService(Jp,r))}),i=t({args:[`symbolic-ref`,`refs/remotes/origin/HEAD`],operation:`getting main branch`,trim:!0}).pipe(u.map(e=>e.replace(`refs/remotes/origin/`,``)),u.catchTag(`GitError`,()=>t({args:[`revparse`,`--verify`,`origin/main`],operation:`getting main branch (origin/main)`,trim:!0}).pipe(u.as(`main`))),u.catchTag(`GitError`,()=>t({args:[`rev-parse`,`--verify`,`main`],operation:`getting main branch (main)`,trim:!0}).pipe(u.as(`main`))),u.catchTag(`GitError`,()=>u.succeed(`main`))),a=t({args:[`rev-parse`,`--abbrev-ref`,`HEAD`],operation:`getting current branch`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(`HEAD`))),o=t({args:[`rev-parse`,`--is-inside-work-tree`],operation:`checking if inside work tree`,trim:!0}).pipe(u.map(e=>e===`true`),u.catchTag(`GitError`,()=>u.succeed(!1))),s=e=>{let[t,n,r]=e.split(` `);return new dn({relativePath:r??``,added:Number.parseInt(t??`0`,10)||0,removed:Number.parseInt(n??`0`,10)||0})},c=u.fn(`Git.getFileStats`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`diff`,`HEAD`,`--numstat`],operation:`getting working tree file stats`}).pipe(u.map(xe.split(`
23
- `)),u.map(be.map(xe.trim)),u.map(be.filter(xe.isNonEmpty)),u.map(be.map(s)),u.catchTag(`GitError`,()=>u.succeed([]))):yield*t({args:[`diff`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`,`--numstat`],operation:`getting file stats`}).pipe(u.map(xe.split(`
24
- `)),u.map(be.map(xe.trim)),u.map(be.filter(xe.isNonEmpty)),u.map(be.map(s)),u.catchTag(`GitError`,()=>u.succeed([])))}),l=e=>e===`A`?`A`:e===`D`?`D`:e===`R`?`R`:e===`C`?`C`:e===`?`?`?`:`M`,d=u.fn(`Git.getChangedFiles`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`status`,`--porcelain`],operation:`getting working tree changes`}).pipe(u.map(xe.split(`
25
- `)),u.map(be.filter(xe.isNonEmpty)),u.map(be.map(e=>{let t=e.at(0)??`M`;return{path:e.slice(3).trim(),status:l(t)}})),u.catchTag(`GitError`,()=>u.succeed([]))):yield*t({args:[`diff`,`--name-status`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`],operation:`getting changed files`,trim:!0}).pipe(u.map(xe.split(`
26
- `)),u.map(be.map(xe.trim)),u.map(be.filter(xe.isNonEmpty)),u.map(be.map(e=>{let t=e.split(` `),n=(t[0]??`M`).at(0)??`M`;return{path:(n===`R`||n===`C`?t[2]:t[1])??``,status:l(n)}})),u.catchTag(`GitError`,()=>u.succeed([])))}),f=u.fn(`Git.getDiffPreview`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`diff`,`HEAD`],operation:`getting diff preview`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``))):yield*t({args:[`diff`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`],operation:`getting diff preview`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)))}),m=u.fn(`Git.getRecentCommits`)(function*(e){return yield*t({args:[`log`,`--format=%H %h %s`,e],operation:`getting recent commits`,trim:!0}).pipe(u.map(xe.split(`
27
- `)),u.map(be.map(xe.trim)),u.map(be.filter(xe.isNonEmpty)),u.map(be.map(e=>{let[t,n,...r]=e.split(` `);return{hash:t??``,shortHash:n??``,subject:r.join(` `)}})),u.catchTag(`GitError`,()=>u.succeed([])))}),h=u.fn(`Git.getCommitSummary`)(function*(e){return yield*t({args:[`log`,`-1`,`--format=%H %h %s`,e],operation:`getting commit summary`,trim:!0}).pipe(u.map(e=>{let[t,n,...r]=e.split(` `);if(!(!t||!n))return{hash:t,shortHash:n,subject:r.join(` `)}}),u.catchTag(`GitError`,()=>u.succeed(void 0)))}),g=u.fn(`Git.computeFingerprint`)(function*(){let e=yield*t({args:[`rev-parse`,`HEAD`],operation:`getting HEAD for fingerprint`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)));if(!e)return;let n=yield*t({args:[`diff`],operation:`getting unstaged diff for fingerprint`}).pipe(u.catchTag(`GitError`,()=>u.succeed(``))),r=yield*t({args:[`diff`,`--cached`],operation:`getting staged diff for fingerprint`}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)));return Ce.createHash(`sha256`).update(e).update(`\0`).update(n).update(`\0`).update(r).digest(`hex`)}),_=u.fn(`ensureStateDir`)(function*(t){let n=K.join(t,Up);yield*e.makeDirectory(n,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void));let r=K.join(n,`.gitignore`);return(yield*e.exists(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))||(yield*e.writeFileString(r,`*
28
- `).pipe(u.catchTag(`PlatformError`,()=>u.void))),n}),v=u.gen(function*(){let e=yield*_(yield*Jp);return K.join(e,`last-tested`)}),y=u.fn(`Git.loadSavedFingerprint`)(function*(){let t=yield*v;return yield*e.readFileString(t).pipe(u.map(xe.trim),u.catchTag(`PlatformError`,()=>u.succeed(void 0)))}),b=u.fn(`Git.saveTestedFingerprint`)(function*(){let t=yield*g();if(!t)return;let n=yield*v;yield*e.writeFileString(n,t)});return{withRepoRoot:r,getMainBranch:i,getCurrentBranch:a,isInsideWorkTree:o,getFileStats:c,getChangedFiles:d,getDiffPreview:f,getRecentCommits:m,getCommitSummary:h,getState:u.fn(`Git.getState`)(function*(){if(!(yield*o))return new fn({isGitRepo:!1,currentBranch:`HEAD`,mainBranch:void 0,isOnMain:!1,hasChangesFromMain:!1,hasUnstagedChanges:!1,hasBranchCommits:!1,branchCommitCount:0,fileStats:[],workingTreeFileStats:[],fingerprint:void 0,savedFingerprint:void 0});let[e,t,n,r]=yield*u.all([a,i,g(),y()],{concurrency:`unbounded`}),s=e===t,[l,d,f]=yield*u.all([c(hn.makeUnsafe({_tag:`Changes`,mainBranch:t})),c(hn.makeUnsafe({_tag:`WorkingTree`})),m(`${t}..HEAD`)],{concurrency:`unbounded`});return new fn({isGitRepo:!0,currentBranch:e,mainBranch:t,isOnMain:s,hasChangesFromMain:l.length>0,hasUnstagedChanges:d.length>0,hasBranchCommits:f.length>0,branchCommitCount:f.length,fileStats:l,workingTreeFileStats:d,fingerprint:n,savedFingerprint:r})}),computeFingerprint:g,saveTestedFingerprint:b}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer));static withRepoRoot=t=>{let n=m.effect(Jp)(u.tryPromise({try:()=>Hp(t).revparse([`--show-toplevel`]),catch:e=>new qp({cause:e})}).pipe(u.map(e=>e.trim())));return m.mergeAll(e.layer.pipe(m.provide(n)),n)}},Xp=class extends S.ErrorClass(`@supervisor/ExecutionError`)({_tag:S.tag(`ExecutionError`),reason:S.Union([Fa,za,La,Ra])}){displayName=this.reason.displayName??`Browser testing failed`;message=this.reason.message},Zp=class extends C.Service()(`@supervisor/Executor`,{make:u.gen(function*(){let e=yield*Wa,t=yield*Yp,n=u.fn(`Executor.gatherContext`)(function*(e){let n=yield*t.getCurrentBranch,r=yield*t.getMainBranch,i=yield*t.getChangedFiles(e),a=yield*t.getDiffPreview(e),o=e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:e._tag===`Commit`?`-1 ${e.hash}`:`HEAD~5..HEAD`,s=yield*t.getRecentCommits(o);return{currentBranch:n,mainBranch:r,changedFiles:i.slice(0,12),recentCommits:s.slice(0,5),diffPreview:a}});return{execute:u.fn(`Executor.execute`)(function*(t){let a=yield*n(t.changesFor),o=$a({userInstruction:t.instruction,scope:t.changesFor._tag,currentBranch:a.currentBranch,mainBranch:a.mainBranch,changedFiles:a.changedFiles,recentCommits:a.recentCommits,diffPreview:a.diffPreview,baseUrl:t.baseUrl,isHeadless:t.isHeadless,requiresCookies:t.requiresCookies,savedFlow:t.savedFlow,learnings:t.learnings,testCoverage:t.testCoverage}),s=mn.makeUnsafe(crypto.randomUUID()),c=K.join(process.cwd(),Up,`replays`,`${s}.ndjson`),l=new En({id:s,changesFor:t.changesFor,currentBranch:a.currentBranch,diffPreview:a.diffPreview,fileStats:[],instruction:t.instruction,baseUrl:t.baseUrl?_.some(t.baseUrl):_.none(),isHeadless:t.isHeadless,requiresCookies:t.requiresCookies,testCoverage:t.testCoverage?_.some(t.testCoverage):_.none(),title:t.instruction,rationale:`Direct execution`,steps:[]}),u=new Zn({...l,events:[new Dn({plan:l})]}),d=[{name:`EXPECT_REPLAY_OUTPUT_PATH`,value:c}];t.liveViewUrl&&d.push({name:i,value:t.liveViewUrl}),t.requiresCookies||d.push({name:r,value:`1`});let f=new tr({cwd:process.cwd(),sessionId:_.none(),prompt:o,systemPrompt:_.none(),mcpEnv:d});return e.stream(f).pipe(w.mapAccum(()=>u,(e,t)=>{let n=e.addEvent(t);return[n,[n]]}),w.mapError(e=>new Xp({reason:e})))},w.unwrap)}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer))},Qp=class extends C.Service()(`@supervisor/Reporter`,{make:u.gen(function*(){return{report:u.fn(`Reporter.report`)(function*(e){let t=e.events.filter(e=>e._tag===`StepFailed`),n=e.events.filter(e=>e._tag===`StepCompleted`),r=e.events.find(e=>e._tag===`RunFinished`),i=r?r.summary:t.length>0?`${t.length} step(s) failed, ${n.length} passed`:`${n.length} step(s) completed`,a=e.events.filter(e=>e._tag===`ToolResult`&&e.toolName.endsWith(`__screenshot`)&&!e.isError).map(e=>e._tag===`ToolResult`?e.result:``).filter(Boolean);return new Qn({...e,summary:i,screenshotPaths:a,pullRequest:_.none(),testCoverageReport:e.testCoverage})})}})}){static layer=m.effect(this)(this.make)};const $p=e=>{let t=[`format_version: ${e.formatVersion}`,`title: ${JSON.stringify(e.title)}`,`description: ${JSON.stringify(e.description)}`,`slug: ${JSON.stringify(e.slug)}`,`saved_target_scope: ${JSON.stringify(e.savedTargetScope)}`,`saved_target_display_name: ${JSON.stringify(e.savedTargetDisplayName)}`];return e.selectedCommit!==void 0&&t.push(`selected_commit: ${JSON.stringify(e.selectedCommit)}`),t.push(`flow: ${JSON.stringify(e.flow)}`),t.push(`environment: ${JSON.stringify(e.environment)}`),t.join(`
29
- `)},em=e=>`---\n${$p(e)}\n---\n`,tm=e=>e.startsWith(`"`)&&e.endsWith(`"`)?JSON.parse(e):e,nm=e=>v.isObject(e)&&typeof e.id==`string`&&typeof e.title==`string`&&typeof e.instruction==`string`&&typeof e.expectedOutcome==`string`,rm=e=>v.isObject(e)?{title:typeof e.title==`string`?e.title:``,userInstruction:typeof e.userInstruction==`string`?e.userInstruction:``,steps:Array.isArray(e.steps)?e.steps.filter(nm):[]}:{title:``,userInstruction:``,steps:[]},im=e=>v.isObject(e)?{baseUrl:typeof e.baseUrl==`string`?e.baseUrl:``,cookies:typeof e.cookies==`boolean`?e.cookies:!1}:{baseUrl:``,cookies:!1},am=e=>{let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)throw Error(`Invalid saved flow file: no frontmatter found`);let n=t[1],r=new Map;for(let e of n.split(`
30
- `)){if(e===`selected_commit: undefined`)continue;let t=e.indexOf(`: `);if(t===-1)continue;let n=e.slice(0,t),i=e.slice(t+2);r.set(n,i)}let i={formatVersion:Number(r.get(`format_version`)),title:tm(r.get(`title`)??``),description:tm(r.get(`description`)??``),slug:tm(r.get(`slug`)??``),savedTargetScope:tm(r.get(`saved_target_scope`)??``),savedTargetDisplayName:tm(r.get(`saved_target_display_name`)??``),flow:rm(JSON.parse(r.get(`flow`)??`{}`)),environment:im(JSON.parse(r.get(`environment`)??`{}`))},a=r.get(`selected_commit`);return a!==void 0&&(i.selectedCommit=tm(a)),i},om=u.fn(`ensureStateDir`)(function*(e,t){let n=K.join(t,Up);yield*e.makeDirectory(n,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void));let r=K.join(n,`.gitignore`);return(yield*e.exists(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))||(yield*e.writeFileString(r,`*
31
- `).pipe(u.catchTag(`PlatformError`,()=>u.void))),n}),sm=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60).replace(/-$/,``),cm=e=>({formatVersion:3,title:e.title,description:e.instruction.slice(0,120),slug:sm(e.title),savedTargetScope:e.changesFor._tag,savedTargetDisplayName:gn(e.changesFor),flow:{title:e.title,userInstruction:e.instruction,steps:e.steps.map(e=>{let t=_.getOrElse(e.summary,()=>``);return{id:e.id,title:e.title,instruction:e.instruction===e.title?t||e.title:e.instruction,expectedOutcome:e.expectedOutcome||t}})},environment:{baseUrl:_.getOrElse(e.baseUrl,()=>``),cookies:e.requiresCookies}});var lm=class extends C.Service()(`@supervisor/FlowStorage`,{make:u.gen(function*(){let e=yield*p.FileSystem,t=u.gen(function*(){let t=yield*om(e,yield*Jp);return K.join(t,`flows`)});return{save:u.fn(`FlowStorage.save`)(function*(n){let r=cm(n),i=yield*t,a=K.join(i,`${r.slug}.md`);return yield*e.makeDirectory(i,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void)),yield*e.writeFileString(a,em(r)),yield*u.logInfo(`Flow saved`,{slug:r.slug,stepCount:r.flow.steps.length,filePath:a}),r}),list:u.fn(`FlowStorage.list`)(function*(){let n=yield*t;if(!(yield*e.exists(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1)))))return[];let r=(yield*e.readDirectory(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed([])))).filter(e=>e.endsWith(`.md`)),i=[];for(let t of r){let r=yield*e.readFileString(K.join(n,t)).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(!r)continue;let a=yield*u.try({try:()=>am(r),catch:()=>({_tag:`FlowParseError`})}).pipe(u.catchTag(`FlowParseError`,()=>u.succeed(void 0)));a&&i.push(a)}return yield*u.logDebug(`Flows listed`,{count:i.length}),i})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer))};const um=(e,t)=>{try{return ce(`git checkout ${t}`,{cwd:e,encoding:`utf-8`,timeout:5e3,stdio:`pipe`}),!0}catch{return!1}};var dm=class extends S.ErrorClass(`GitHubCommandError`)({_tag:S.tag(`GitHubCommandError`),cause:S.String}){message=`GitHub CLI command failed: ${this.cause}`},fm=class extends C.Service()(`@supervisor/GitHub`,{make:u.gen(function*(){let e=yield*Pe,t=yield*ke,n=u.fn(`GitHub.runGhCommand`)(function*(t,n){return yield*e.string(_e.make(`gh`,n,{cwd:t})).pipe(u.timeout(15e3),u.catchTags({PlatformError:e=>u.fail(new dm({cause:e.message})),TimeoutError:()=>u.fail(new dm({cause:`command timed out`}))}),u.map(e=>e.trim()))}),r=u.fn(`GitHub.findPullRequest`)(function*(e,t){let r=yield*n(e,[`pr`,`list`,`--head`,g.value(t).pipe(g.when({_tag:`Branch`},e=>e.branchName),g.exhaustive),`--state`,`open`,`--limit`,`1`,`--json`,`number,url,title,headRefName`]);return yield*S.decodeEffect(S.fromJsonString(S.Array(Wn)))(r).pipe(u.map(o.head),u.catchTag(`SchemaError`,()=>u.succeed(_.none())))}),i=S.fromJsonString(S.Array(_n));return{findPullRequest:r,listPullRequests:u.fn(`GitHub.listPullRequests`)(function*(e){let t=yield*n(e,[`pr`,`list`,`--state`,`all`,`--json`,`number,headRefName,author,state,updatedAt`,`--limit`,`100`]).pipe(u.catchTag(`GitHubCommandError`,()=>u.succeed(`[]`)));return(yield*S.decodeEffect(i)(t).pipe(u.catchTag(`SchemaError`,u.die))).map(e=>new yn({name:e.headRefName,author:e.author.login,prNumber:e.number,prStatus:e.state===`OPEN`?`open`:e.state===`MERGED`||e.state===`CLOSED`?`merged`:null,updatedAt:e.updatedAt}))}),addComment:u.fn(`GitHub.addComment`)(function*(e,r,i){yield*u.scoped(u.gen(function*(){let a=de(yield*t.makeTempDirectoryScoped({prefix:`expect-comment-`}),`pull-request-comment.md`);yield*t.writeFileString(a,i),yield*n(e,[`pr`,`comment`,String(r.number),`--body-file`,a])}))})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer))};const pm=e=>K.join(Ae.homedir(),Up,`${e}.json`),mm=new Map,hm={getItem:async e=>{try{let t=await Ie.readFile(pm(e),`utf-8`);return mm.set(e,t),t}catch{return null}},setItem:async(e,t)=>{if(mm.get(e)===t)return;mm.set(e,t);let n=pm(e);await Ie.mkdir(K.dirname(n),{recursive:!0}),await Ie.writeFile(n,t,`utf-8`)},removeItem:async e=>{mm.delete(e);try{await Ie.unlink(pm(e))}catch{}}},gm=e=>K.join(process.cwd(),Up,`${e}.json`),_m=new Map,vm={getItem:async e=>{try{let t=await Ie.readFile(gm(e),`utf-8`);return _m.set(e,t),t}catch{return null}},setItem:async(e,t)=>{if(_m.get(e)===t)return;_m.set(e,t);let n=gm(e);await Ie.mkdir(K.dirname(n),{recursive:!0}),await Ie.writeFile(n,t,`utf-8`)},removeItem:async e=>{_m.delete(e);try{await Ie.unlink(gm(e))}catch{}}},ym=[/from\s+["']([^"']+)["']/g,/import\s*\(\s*["']([^"']+)["']\s*\)/g,/require\s*\(\s*["']([^"']+)["']\s*\)/g],bm=/\.(?:test|spec|e2e)\.(?:ts|tsx|js|jsx|mts|mjs|cts|cjs)$/,xm=/(?:^|[/\\])(?:__tests?__|tests?)[/\\]/,Sm=/\.(?:ts|tsx|js|jsx|mts|mjs|cts|cjs)$/,Cm=e=>{let t=K.extname(e).toLowerCase();return Wp.includes(t)},wm=e=>e.split(/[/\\]/).some(e=>Gp.has(e)),Tm=e=>!!(bm.test(e)||xm.test(e)&&Sm.test(e)),Em=e=>{let t=[];for(let n of ym){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];e&&t.push(e)}}return t},Dm=(e,t)=>{let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(n.has(t))continue;n.add(t);let i=e.get(t);if(i)for(let e of i)n.has(e)||r.push(e)}return n.delete(t),n},Om=e=>u.tryPromise({try:()=>new Promise(t=>{se(`git`,[`ls-files`,`--cached`,`--others`,`--exclude-standard`],{cwd:e,maxBuffer:10*1024*1024},(e,n)=>{if(e){t([]);return}t(n.split(`
32
- `).map(e=>e.trim()).filter(e=>e.length>0))})}),catch:()=>[]}),km=async e=>{try{let{ResolverFactory:t}=await import(`oxc-resolver`);return new t({tsconfig:{configFile:K.join(e,`tsconfig.json`),references:`auto`},extensions:[...Wp],mainFields:[`module`,`main`],conditionNames:[`import`,`require`,`default`]})}catch{return}},Am=(e,t,n)=>{try{return e.sync(t,n).path??void 0}catch{return}},jm=(e,t,n)=>u.gen(function*(){let r=t.filter(e=>Cm(e)&&!wm(e)),i=yield*u.promise(()=>km(e));if(!i)return new Map;let a=new Map;return yield*u.forEach(r,t=>u.gen(function*(){let r=K.join(e,t),o=yield*n.readFileString(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(!o)return;let s=Em(o),c=new Set;for(let t of s)if(t.startsWith(`.`)||t.startsWith(`@`)||t.startsWith(`~`)){let n=Am(i,K.dirname(r),t);if(n){let t=K.relative(e,n);wm(t)||c.add(t)}}c.size>0&&a.set(t,c)}),{concurrency:50}),a}),Mm=e=>e.filter(e=>!wm(e)&&Tm(e)).slice(0,200);var Nm=class extends C.Service()(`@supervisor/TestCoverage`,{make:u.gen(function*(){let e=yield*p.FileSystem;return{analyze:u.fn(`TestCoverage.analyze`)(function*(t){yield*u.annotateCurrentSpan({changedFileCount:t.length});let n=yield*Jp,r=yield*Om(n),i=Mm(r),a=yield*jm(n,r,e),o=new Map;for(let e of i){let t=Dm(a,e);t.add(e);for(let n of t){let t=o.get(n)??[];t.push(e),o.set(n,t)}}let s=t.filter(e=>Sm.test(e.path)&&!Tm(e.path)&&e.status!==`D`),c=s.map(e=>{let t=o.get(e.path)??[];return{path:e.path,testFiles:t,covered:t.length>0}}),l=c.filter(e=>e.covered).length,d=s.length,f=d>0?Math.round(l/d*100):100;return yield*u.logInfo(`Test coverage analyzed`,{coveredCount:l,totalCount:d,percent:f,testFileCount:i.length,graphEdgeCount:a.size}),{entries:c,coveredCount:l,totalCount:d,percent:f}})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(ye.layer))};const Pm=e=>e.pipe(u.provide(fm.layer)),Fm=async e=>{let t=[];if(e.hasUntestedChanges&&t.push(Gn.makeUnsafe({_tag:`WorkingTree`})),e.mainBranch){let n=process.cwd(),r=await u.runPromise(u.gen(function*(){return yield*(yield*Yp).getRecentCommits(`${e.mainBranch}..HEAD`)}).pipe(u.provide(Yp.withRepoRoot(n))));for(let e of r)t.push(Gn.makeUnsafe({_tag:`Commit`,hash:e.hash,shortHash:e.shortHash,subject:e.subject}))}return t},Im=e=>u.runPromise(Pm(fm.use(t=>t.listPullRequests(e)))),Lm=async e=>{let t=await Im(process.cwd()),n=t.filter(e=>e.prNumber!==null&&e.prStatus===`open`).map(e=>Gn.makeUnsafe({_tag:`PullRequest`,branch:e})),r=t.filter(e=>e.prNumber!==null&&e.prStatus===`merged`).slice(0,5).map(e=>Gn.makeUnsafe({_tag:`PullRequest`,branch:e})),i=t.filter(t=>t.name!==e.currentBranch&&t.prNumber===null).map(e=>Gn.makeUnsafe({_tag:`Branch`,branch:e}));return[...n,...r,...i]},Rm=(e,t)=>e._tag===`WorkingTree`&&t&&!t.isOnMain?t.currentBranch:Jn(e),zm=(e,t)=>{if(e._tag===`WorkingTree`&&t){let e=[];if(t.fileStats.length>0){let n=t.fileStats.reduce((e,t)=>e+t.added,0),r=t.fileStats.reduce((e,t)=>e+t.removed,0),i=t.fileStats.length,a=[];n>0&&a.push(`+${n}`),r>0&&a.push(`-${r}`),a.length>0?e.push(`${a.join(` `)} in ${i} file${i===1?``:`s`}`):e.push(`${i} file${i===1?``:`s`}`)}if(t.branchCommitCount>0&&e.push(`${t.branchCommitCount} commit${t.branchCommitCount===1?``:`s`}`),e.length>0)return e.join(`, `)}return Yn(e)},Bm=(e,t)=>e._tag===`WorkingTree`?Rm(e,t):Xn(e),Vm=(e,t,n)=>{if(!t)return[...e];let r=t.toLowerCase();return e.filter(e=>(e._tag===`WorkingTree`?`local changes ${n?.currentBranch??``}`:qn(e)).toLowerCase().includes(r))},Hm=()=>P({queryKey:[`remote-branches`],queryFn:()=>Im(process.cwd())}),Um=e=>{let t=re(10);if(t[0]!==`19aae044389a98cd743b540aea8d28df87ba20582cdcc28d3b06005d495ed4de`){for(let e=0;e<10;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`19aae044389a98cd743b540aea8d28df87ba20582cdcc28d3b06005d495ed4de`}let{message:n}=e,r=Nt(),i;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=H(Le,{type:`dots`}),t[1]=i):i=t[1];let a;t[2]===r.SELECTION?a=t[3]:(a=H(O,{color:r.SELECTION,children:i}),t[2]=r.SELECTION,t[3]=a);let o;t[4]===n?o=t[5]:(o=n?U(O,{children:[` `,n]}):null,t[4]=n,t[5]=o);let s;return t[6]!==r.DIM||t[7]!==a||t[8]!==o?(s=U(O,{color:r.DIM,children:[a,o]}),t[6]=r.DIM,t[7]=a,t[8]=o,t[9]=s):s=t[9],s},Wm=(e,t)=>{let n=Math.max(0,t-ze(e));return e+` `.repeat(n)},Gm=({itemCount:e,visibleCount:t,initialIndex:n})=>{let[r,i]=R(n??0),a=L(e);return a.current!==e&&(a.current=e,i(t=>Math.min(t,Math.max(0,e-1)))),{highlightedIndex:r,setHighlightedIndex:i,scrollOffset:I(()=>{if(e<=t)return 0;let n=Math.floor(t/2),i=e-t;return Math.min(i,Math.max(0,r-n))},[e,t,r]),handleNavigation:ae((t,n)=>n.downArrow||t===`j`||n.ctrl&&t===`n`?(i(t=>Math.min(e-1,t+1)),!0):n.upArrow||t===`k`||n.ctrl&&t===`p`?(i(e=>Math.max(0,e-1)),!0):!1,[e])}},Km=/(?:https?:\/\/|localhost[:/]|[\w-]+\.[\w-]+\.[\w]+|[\w-]+\.(com|org|net|io|dev|app|co|me|ai))\S*/i,qm=e=>Km.test(e),Jm=Ve.taggedEnum(),Ym=e=>qm(e.instruction)?Jm.Testing(e):Jm.PortPicker(e),Xm=Be(e=>({screen:Jm.Main(),previousScreen:Jm.Main(),navigateTo:t=>e(e=>({screen:t,previousScreen:e.screen})),setScreen:t=>e({screen:t})})),Zm=new j({defaultOptions:{queries:{staleTime:1/0,retry:!1}}}),Qm=e=>{let t=re(18);if(t[0]!==`ebd3be31f5201c04dd238bf1bd9d32bf671ecbefa6ad88d45037fbe949e8bb0c`){for(let e=0;e<18;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`ebd3be31f5201c04dd238bf1bd9d32bf671ecbefa6ad88d45037fbe949e8bb0c`}let{title:n,subtitle:r,showDivider:i}=e,a=i===void 0?!0:i,[o]=At(),s,c,l;t[1]!==r||t[2]!==n?(l=n.toUpperCase(),s=r?` │ ${r}`:``,c=ze(l),t[1]=r,t[2]=n,t[3]=s,t[4]=c,t[5]=l):(s=t[3],c=t[4],l=t[5]);let u=c+ze(s),d=a?Math.max(0,o-u-3):0,f;t[6]===l?f=t[7]:(f=H(O,{bold:!0,color:J.text,children:l}),t[6]=l,t[7]=f);let p;t[8]!==r||t[9]!==s?(p=r?H(O,{color:J.textMuted,children:s}):null,t[8]=r,t[9]=s,t[10]=p):p=t[10];let m;t[11]!==d||t[12]!==a?(m=a?U(O,{color:J.border,children:[` `,`─`.repeat(d)]}):null,t[11]=d,t[12]=a,t[13]=m):m=t[13];let h;return t[14]!==f||t[15]!==p||t[16]!==m?(h=U(O,{children:[f,p,m]}),t[14]=f,t[15]=p,t[16]=m,t[17]=h):h=t[17],h},$m=()=>{let e=re(39);if(e[0]!==`155bac1331928275f0977c44c5021af2a99f257236d72aa818a512bae62664a8`){for(let t=0;t<39;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`155bac1331928275f0977c44c5021af2a99f257236d72aa818a512bae62664a8`}let[t]=At(),n=Xm(eh),r=Nt(),[i,a]=R(null),[o,s]=R(``),[c,l]=R(`recent`),[u,d]=R(!1),[f,p]=R(void 0),{data:m,isLoading:h}=Hm(),g=m===void 0?[]:m,_=yn.filterBranches(g,c,o),{highlightedIndex:v,setHighlightedIndex:y,scrollOffset:b,handleNavigation:x}=Gm({itemCount:_.length,visibleCount:15}),S=t-2-32-16-2,C=_.slice(b,b+15),w;e[1]===y?w=e[2]:(w=e=>{s(Dt(e)),y(0)},e[1]=y,e[2]=w);let ee=w,T;e[3]===n?T=e[4]:(T=e=>{um(process.cwd(),e)?(p(void 0),Zm.invalidateQueries({queryKey:[`git-state`]}),n(Jm.Main())):p(`Could not checkout "${e}". You may have uncommitted changes or the branch may not exist locally.`)},e[3]=n,e[4]=T);let D=T,k;e[5]!==c||e[6]!==y?(k=e=>{l(vn[(vn.indexOf(c)+e+vn.length)%vn.length]),y(0)},e[5]=c,e[6]=y,e[7]=k):k=e[7];let A=k;te((e,t)=>{if(u){t.escape&&d(!1);return}if(!x(e,t)){if(t.rightArrow&&A(1),t.leftArrow&&A(-1),t.return){let e=_[v];e&&(p(void 0),D(e.name))}e===`/`&&d(!0)}});let ne;e[8]!==i||e[9]!==D?(ne=(e,t)=>{i&&(e.toLowerCase()===`y`&&(p(void 0),D(i.name),a(null)),(e.toLowerCase()===`n`||t.escape)&&a(null))},e[8]=i,e[9]=D,e[10]=ne):ne=e[10];let j=i!==null,M;e[11]===j?M=e[12]:(M={isActive:j},e[11]=j,e[12]=M),te(ne,M);let N=E,P=`${_.length} branches`,ie;e[13]===P?ie=e[14]:(ie=H(E,{paddingX:1,children:H(Qm,{title:`Select a PR or branch to test`,subtitle:P})}),e[13]=P,e[14]=ie);let ae;e[15]!==r||e[16]!==c||e[17]!==y?(ae=vn.map((e,t)=>{let n=e===c,i=t<vn.length-1?` · `:``,a={recent:r.CYAN,all:r.TEXT,open:r.GREEN,draft:r.DIM,merged:r.PURPLE,"no-pr":r.YELLOW};return U(E,{children:[H(It,{fullWidth:!1,onClick:()=>{l(e),y(0)},children:H(O,{color:n?a[e]:r.DIM,children:n?`[${e}]`:e})}),H(O,{color:r.DIM,children:i})]},e)}),e[15]=r,e[16]=c,e[17]=y,e[18]=ae):ae=e[18];let F;e[19]===ae?F=e[20]:(F=H(E,{marginTop:1,paddingX:1,children:ae}),e[19]=ae,e[20]=F);let oe=h?H(E,{marginTop:1,paddingX:1,children:H(Um,{message:`Fetching PRs...`})}):U(E,{marginTop:1,flexDirection:`column`,height:15,overflow:`hidden`,paddingX:1,children:[C.map((e,t)=>{let n=t+b,i=n===v;return U(It,{onClick:()=>{y(n),D(e.name)},children:[H(O,{color:i?r.PRIMARY:r.DIM,children:i?`${W.pointer} `:` `}),H(O,{color:i?r.PRIMARY:r.DIM,bold:i,children:Wm(Re(e.name,31),32)}),H(O,{color:r.CYAN,children:Wm(Re(e.author||`—`,15),16)}),e.prNumber&&e.prStatus?H(O,{color:e.prStatus===`open`?r.GREEN:e.prStatus===`merged`?r.PURPLE:r.DIM,children:Re(`#${e.prNumber} ${e.prStatus}`,S)}):H(O,{color:r.DIM,children:`—`})]},e.name)}),_.length===0&&H(O,{color:r.DIM,children:`No matching branches`})]}),I;e[21]!==r||e[22]!==f?(I=f?H(E,{marginTop:1,paddingX:1,children:H(O,{color:r.RED,children:f})}):null,e[21]=r,e[22]=f,e[23]=I):I=e[23];let L;e[24]!==r||e[25]!==i?(L=i?U(Pt,{color:r.YELLOW,marginTop:1,children:[U(O,{color:r.YELLOW,bold:!0,children:[`Switch to `,i.name,`?`]}),U(O,{color:r.DIM,children:[`Press `,H(O,{color:r.PRIMARY,children:`y`}),` to continue or`,` `,H(O,{color:r.PRIMARY,children:`n`}),` to cancel.`]})]}):null,e[24]=r,e[25]=i,e[26]=L):L=e[26];let z;e[27]!==ee||e[28]!==u||e[29]!==o?(z=H(E,{paddingX:1,children:H(Ut,{isSearching:u,query:o,onChange:ee})}),e[27]=ee,e[28]=u,e[29]=o,e[30]=z):z=e[30];let B;return e[31]!==N||e[32]!==ie||e[33]!==F||e[34]!==oe||e[35]!==I||e[36]!==L||e[37]!==z?(B=U(N,{flexDirection:`column`,width:`100%`,paddingY:1,children:[ie,F,oe,I,L,z]}),e[31]=N,e[32]=ie,e[33]=F,e[34]=oe,e[35]=I,e[36]=L,e[37]=z,e[38]=B):B=e[38],B};function eh(e){return e.setScreen}const th=ue.join(process.cwd(),`.expect`,`logs.md`),nh=h.formatLogFmt.pipe(h.toFile(th)),rh=m.effectDiscard(u.gen(function*(){let e=yield*p.FileSystem;yield*e.makeDirectory(ue.dirname(th),{recursive:!0}),yield*e.writeFileString(ue.join(ue.dirname(th),`.gitignore`),`*
33
- `)})),ih=m.mergeAll(rh,h.layer([nh])).pipe(m.provide(He.layer));var ah=n(((t,n)=>{(function(r,i){typeof t==`object`&&typeof n==`object`?n.exports=i(e(`child_process`),e(`crypto`)):typeof define==`function`&&define.amd?define([`child_process`,`crypto`],i):typeof t==`object`?t[`electron-machine-id`]=i(e(`child_process`),e(`crypto`)):r[`electron-machine-id`]=i(r.child_process,r.crypto)})(t,function(t,n){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p=``,t(0)}([function(e,t,n){e.exports=n(34)},function(e,t,n){var r=n(29)(`wks`),i=n(33),a=n(2).Symbol,o=typeof a==`function`,s=e.exports=function(e){return r[e]||(r[e]=o&&a[e]||(o?a:i)(`Symbol.`+e))};s.store=r},function(e,t){var n=e.exports=typeof window<`u`&&window.Math==Math?window:typeof self<`u`&&self.Math==Math?self:Function(`return this`)();typeof __g==`number`&&(__g=n)},function(e,t,n){var r=n(9);e.exports=function(e){if(!r(e))throw TypeError(e+` is not an object!`);return e}},function(e,t,n){e.exports=!n(24)(function(){return Object.defineProperty({},`a`,{get:function(){return 7}}).a!=7})},function(e,t,n){var r=n(12),i=n(17);e.exports=n(4)?function(e,t,n){return r.f(e,t,i(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){var n=e.exports={version:`2.4.0`};typeof __e==`number`&&(__e=n)},function(e,t,n){var r=n(14);e.exports=function(e,t,n){if(r(e),t===void 0)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t){e.exports=function(e){return typeof e==`object`?e!==null:typeof e==`function`}},function(e,t){e.exports={}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(3),i=n(26),a=n(32),o=Object.defineProperty;t.f=n(4)?Object.defineProperty:function(e,t,n){if(r(e),t=a(t,!0),r(n),i)try{return o(e,t,n)}catch{}if(`get`in n||`set`in n)throw TypeError(`Accessors not supported!`);return`value`in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(42),i=n(15);e.exports=function(e){return r(i(e))}},function(e,t){e.exports=function(e){if(typeof e!=`function`)throw TypeError(e+` is not a function!`);return e}},function(e,t){e.exports=function(e){if(e==null)throw TypeError(`Can't call method on `+e);return e}},function(e,t,n){var r=n(9),i=n(2).document,a=r(i)&&r(i.createElement);e.exports=function(e){return a?i.createElement(e):{}}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(12).f,i=n(8),a=n(1)(`toStringTag`);e.exports=function(e,t,n){e&&!i(e=n?e:e.prototype,a)&&r(e,a,{configurable:!0,value:t})}},function(e,t,n){var r=n(29)(`keys`),i=n(33);e.exports=function(e){return r[e]||(r[e]=i(e))}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(11),i=n(1)(`toStringTag`),a=r(function(){return arguments}())==`Arguments`,o=function(e,t){try{return e[t]}catch{}};e.exports=function(e){var t,n,s;return e===void 0?`Undefined`:e===null?`Null`:typeof(n=o(t=Object(e),i))==`string`?n:a?r(t):(s=r(t))==`Object`&&typeof t.callee==`function`?`Arguments`:s}},function(e,t){e.exports=`constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf`.split(`,`)},function(e,t,n){var r=n(2),i=n(6),a=n(7),o=n(5),s=`prototype`,c=function(e,t,n){var l,u,d,f=e&c.F,p=e&c.G,m=e&c.S,h=e&c.P,g=e&c.B,_=e&c.W,v=p?i:i[t]||(i[t]={}),y=v[s],b=p?r:m?r[t]:(r[t]||{})[s];for(l in p&&(n=t),n)u=!f&&b&&b[l]!==void 0,u&&l in v||(d=u?b[l]:n[l],v[l]=p&&typeof b[l]!=`function`?n[l]:g&&u?a(d,r):_&&b[l]==d?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[s]=e[s],t}(d):h&&typeof d==`function`?a(Function.call,d):d,h&&((v.virtual||={})[l]=d,e&c.R&&y&&!y[l]&&o(y,l,d)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t){e.exports=function(e){try{return!!e()}catch{return!0}}},function(e,t,n){e.exports=n(2).document&&document.documentElement},function(e,t,n){e.exports=!n(4)&&!n(24)(function(){return Object.defineProperty(n(16)(`div`),`a`,{get:function(){return 7}}).a!=7})},function(e,t,n){var r=n(28),i=n(23),a=n(57),o=n(5),s=n(8),c=n(10),l=n(45),u=n(18),d=n(52),f=n(1)(`iterator`),p=!([].keys&&`next`in[].keys()),m=`@@iterator`,h=`keys`,g=`values`,_=function(){return this};e.exports=function(e,t,n,v,y,b,x){l(n,t,v);var S,C,w,ee=function(e){if(!p&&e in O)return O[e];switch(e){case h:return function(){return new n(this,e)};case g:return function(){return new n(this,e)}}return function(){return new n(this,e)}},T=t+` Iterator`,E=y==g,D=!1,O=e.prototype,k=O[f]||O[m]||y&&O[y],A=k||ee(y),te=y?E?ee(`entries`):A:void 0,ne=t==`Array`&&O.entries||k;if(ne&&(w=d(ne.call(new e)),w!==Object.prototype&&(u(w,T,!0),r||s(w,f)||o(w,f,_))),E&&k&&k.name!==g&&(D=!0,A=function(){return k.call(this)}),r&&!x||!p&&!D&&O[f]||o(O,f,A),c[t]=A,c[T]=_,y)if(S={values:E?A:ee(g),keys:b?A:ee(h),entries:te},x)for(C in S)C in O||a(O,C,S[C]);else i(i.P+i.F*(p||D),t,S);return S}},function(e,t){e.exports=!0},function(e,t,n){var r=n(2),i=`__core-js_shared__`,a=r[i]||(r[i]={});e.exports=function(e){return a[e]||(a[e]={})}},function(e,t,n){var r,i,a,o=n(7),s=n(41),c=n(25),l=n(16),u=n(2),d=u.process,f=u.setImmediate,p=u.clearImmediate,m=u.MessageChannel,h=0,g={},_=`onreadystatechange`,v=function(){var e=+this;if(g.hasOwnProperty(e)){var t=g[e];delete g[e],t()}},y=function(e){v.call(e.data)};f&&p||(f=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return g[++h]=function(){s(typeof e==`function`?e:Function(e),t)},r(h),h},p=function(e){delete g[e]},n(11)(d)==`process`?r=function(e){d.nextTick(o(v,e,1))}:m?(i=new m,a=i.port2,i.port1.onmessage=y,r=o(a.postMessage,a,1)):u.addEventListener&&typeof postMessage==`function`&&!u.importScripts?(r=function(e){u.postMessage(e+``,`*`)},u.addEventListener(`message`,y,!1)):r=_ in l(`script`)?function(e){c.appendChild(l(`script`))[_]=function(){c.removeChild(this),v.call(e)}}:function(e){setTimeout(o(v,e,1),0)}),e.exports={set:f,clear:p}},function(e,t,n){var r=n(20),i=Math.min;e.exports=function(e){return e>0?i(r(e),9007199254740991):0}},function(e,t,n){var r=n(9);e.exports=function(e,t){if(!r(e))return e;var n,i;if(t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e))||typeof(n=e.valueOf)==`function`&&!r(i=n.call(e))||!t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e)))return i;throw TypeError(`Can't convert object to primitive value`)}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return`Symbol(${e===void 0?``:e})_${(++n+r).toString(36)}`}},function(e,t,n){function r(e){return e&&e.__esModule?e:{default:e}}function i(){return process.platform===`win32`?process.arch===`ia32`&&process.env.hasOwnProperty(`PROCESSOR_ARCHITEW6432`)?`mixed`:`native`:``}function a(e){return(0,d.createHash)(`sha256`).update(e).digest(`hex`)}function o(e){switch(f){case`darwin`:return e.split(`IOPlatformUUID`)[1].split(`
34
- `)[0].replace(/\=|\s+|\"/gi,``).toLowerCase();case`win32`:return e.toString().split(`REG_SZ`)[1].replace(/\r+|\n+|\s+/gi,``).toLowerCase();case`linux`:return e.toString().replace(/\r+|\n+|\s+/gi,``).toLowerCase();case`freebsd`:return e.toString().replace(/\r+|\n+|\s+/gi,``).toLowerCase();default:throw Error(`Unsupported platform: `+process.platform)}}function s(e){var t=o((0,u.execSync)(p[f]).toString());return e?t:a(t)}function c(e){return new l.default(function(t,n){return(0,u.exec)(p[f],{},function(r,i,s){if(r)return n(Error(`Error while obtaining machine id: `+r.stack));var c=o(i.toString());return t(e?c:a(c))})})}Object.defineProperty(t,`__esModule`,{value:!0});var l=r(n(35));t.machineIdSync=s,t.machineId=c;var u=n(70),d=n(71),f=process.platform,p={darwin:`ioreg -rd1 -c IOPlatformExpertDevice`,win32:{native:`%windir%\\System32`,mixed:`%windir%\\sysnative\\cmd.exe /c %windir%\\System32`}[i()]+`\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`,linux:`( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :`,freebsd:`kenv -q smbios.system.uuid || sysctl -n kern.hostuuid`}},function(e,t,n){e.exports={default:n(36),__esModule:!0}},function(e,t,n){n(66),n(68),n(69),n(67),e.exports=n(6).Promise},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||r!==void 0&&r in e)throw TypeError(n+`: incorrect invocation!`);return e}},function(e,t,n){var r=n(13),i=n(31),a=n(62);e.exports=function(e){return function(t,n,o){var s,c=r(t),l=i(c.length),u=a(o,l);if(e&&n!=n){for(;l>u;)if(s=c[u++],s!=s)return!0}else for(;l>u;u++)if((e||u in c)&&c[u]===n)return e||u||0;return!e&&-1}}},function(e,t,n){var r=n(7),i=n(44),a=n(43),o=n(3),s=n(31),c=n(64),l={},u={},t=e.exports=function(e,t,n,d,f){var p,m,h,g,_=f?function(){return e}:c(e),v=r(n,d,t?2:1),y=0;if(typeof _!=`function`)throw TypeError(e+` is not iterable!`);if(a(_)){for(p=s(e.length);p>y;y++)if(g=t?v(o(m=e[y])[0],m[1]):v(e[y]),g===l||g===u)return g}else for(h=_.call(e);!(m=h.next()).done;)if(g=i(h,v,m.value,t),g===l||g===u)return g};t.BREAK=l,t.RETURN=u},function(e,t){e.exports=function(e,t,n){var r=n===void 0;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(11);e.exports=Object(`z`).propertyIsEnumerable(0)?Object:function(e){return r(e)==`String`?e.split(``):Object(e)}},function(e,t,n){var r=n(10),i=n(1)(`iterator`),a=Array.prototype;e.exports=function(e){return e!==void 0&&(r.Array===e||a[i]===e)}},function(e,t,n){var r=n(3);e.exports=function(e,t,n,i){try{return i?t(r(n)[0],n[1]):t(n)}catch(t){var a=e.return;throw a!==void 0&&r(a.call(e)),t}}},function(e,t,n){var r=n(49),i=n(17),a=n(18),o={};n(5)(o,n(1)(`iterator`),function(){return this}),e.exports=function(e,t,n){e.prototype=r(o,{next:i(1,n)}),a(e,t+` Iterator`)}},function(e,t,n){var r=n(1)(`iterator`),i=!1;try{var a=[7][r]();a.return=function(){i=!0},Array.from(a,function(){throw 2})}catch{}e.exports=function(e,t){if(!t&&!i)return!1;var n=!1;try{var a=[7],o=a[r]();o.next=function(){return{done:n=!0}},a[r]=function(){return o},e(a)}catch{}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(2),i=n(30).set,a=r.MutationObserver||r.WebKitMutationObserver,o=r.process,s=r.Promise,c=n(11)(o)==`process`;e.exports=function(){var e,t,n,l=function(){var r,i;for(c&&(r=o.domain)&&r.exit();e;){i=e.fn,e=e.next;try{i()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(c)n=function(){o.nextTick(l)};else if(a){var u=!0,d=document.createTextNode(``);new a(l).observe(d,{characterData:!0}),n=function(){d.data=u=!u}}else if(s&&s.resolve){var f=s.resolve();n=function(){f.then(l)}}else n=function(){i.call(r,l)};return function(r){var i={fn:r,next:void 0};t&&(t.next=i),e||(e=i,n()),t=i}}},function(e,t,n){var r=n(3),i=n(50),a=n(22),o=n(19)(`IE_PROTO`),s=function(){},c=`prototype`,l=function(){var e,t=n(16)(`iframe`),r=a.length,i=`>`;for(t.style.display=`none`,n(25).appendChild(t),t.src=`javascript:`,e=t.contentWindow.document,e.open(),e.write(`<script>document.F=Object<\/script`+i),e.close(),l=e.F;r--;)delete l[c][a[r]];return l()};e.exports=Object.create||function(e,t){var n;return e===null?n=l():(s[c]=r(e),n=new s,s[c]=null,n[o]=e),t===void 0?n:i(n,t)}},function(e,t,n){var r=n(12),i=n(3),a=n(54);e.exports=n(4)?Object.defineProperties:function(e,t){i(e);for(var n,o=a(t),s=o.length,c=0;s>c;)r.f(e,n=o[c++],t[n]);return e}},function(e,t,n){var r=n(55),i=n(17),a=n(13),o=n(32),s=n(8),c=n(26),l=Object.getOwnPropertyDescriptor;t.f=n(4)?l:function(e,t){if(e=a(e),t=o(t,!0),c)try{return l(e,t)}catch{}if(s(e,t))return i(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(8),i=n(63),a=n(19)(`IE_PROTO`),o=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=i(e),r(e,a)?e[a]:typeof e.constructor==`function`&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?o:null}},function(e,t,n){var r=n(8),i=n(13),a=n(39)(!1),o=n(19)(`IE_PROTO`);e.exports=function(e,t){var n,s=i(e),c=0,l=[];for(n in s)n!=o&&r(s,n)&&l.push(n);for(;t.length>c;)r(s,n=t[c++])&&(~a(l,n)||l.push(n));return l}},function(e,t,n){var r=n(53),i=n(22);e.exports=Object.keys||function(e){return r(e,i)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(5);e.exports=function(e,t,n){for(var i in t)n&&e[i]?e[i]=t[i]:r(e,i,t[i]);return e}},function(e,t,n){e.exports=n(5)},function(e,t,n){var r=n(9),i=n(3),a=function(e,t){if(i(e),!r(t)&&t!==null)throw TypeError(t+`: can't set as prototype!`)};e.exports={set:Object.setPrototypeOf||(`__proto__`in{}?function(e,t,r){try{r=n(7)(Function.call,n(51).f(Object.prototype,`__proto__`).set,2),r(e,[]),t=!(e instanceof Array)}catch{t=!0}return function(e,n){return a(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:a}},function(e,t,n){var r=n(2),i=n(6),a=n(12),o=n(4),s=n(1)(`species`);e.exports=function(e){var t=typeof i[e]==`function`?i[e]:r[e];o&&t&&!t[s]&&a.f(t,s,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(3),i=n(14),a=n(1)(`species`);e.exports=function(e,t){var n,o=r(e).constructor;return o===void 0||(n=r(o)[a])==null?t:i(n)}},function(e,t,n){var r=n(20),i=n(15);e.exports=function(e){return function(t,n){var a,o,s=String(i(t)),c=r(n),l=s.length;return c<0||c>=l?e?``:void 0:(a=s.charCodeAt(c),a<55296||a>56319||c+1===l||(o=s.charCodeAt(c+1))<56320||o>57343?e?s.charAt(c):a:e?s.slice(c,c+2):(a-55296<<10)+(o-56320)+65536)}}},function(e,t,n){var r=n(20),i=Math.max,a=Math.min;e.exports=function(e,t){return e=r(e),e<0?i(e+t,0):a(e,t)}},function(e,t,n){var r=n(15);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(21),i=n(1)(`iterator`),a=n(10);e.exports=n(6).getIteratorMethod=function(e){if(e!=null)return e[i]||e[`@@iterator`]||a[r(e)]}},function(e,t,n){var r=n(37),i=n(47),a=n(10),o=n(13);e.exports=n(27)(Array,`Array`,function(e,t){this._t=o(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,i(1)):t==`keys`?i(0,n):t==`values`?i(0,e[n]):i(0,[n,e[n]])},`values`),a.Arguments=a.Array,r(`keys`),r(`values`),r(`entries`)},function(e,t){},function(e,t,n){var r,i,a,o=n(28),s=n(2),c=n(7),l=n(21),u=n(23),d=n(9),f=(n(3),n(14)),p=n(38),m=n(40),h=(n(58).set,n(60)),g=n(30).set,_=n(48)(),v=`Promise`,y=s.TypeError,b=s.process,x=s[v],b=s.process,S=l(b)==`process`,C=function(){},w=!!function(){try{var e=x.resolve(1),t=(e.constructor={})[n(1)(`species`)]=function(e){e(C,C)};return(S||typeof PromiseRejectionEvent==`function`)&&e.then(C)instanceof t}catch{}}(),ee=function(e,t){return e===t||e===x&&t===a},T=function(e){var t;return!(!d(e)||typeof(t=e.then)!=`function`)&&t},E=function(e){return ee(x,e)?new D(e):new i(e)},D=i=function(e){var t,n;this.promise=new e(function(e,r){if(t!==void 0||n!==void 0)throw y(`Bad Promise constructor`);t=e,n=r}),this.resolve=f(t),this.reject=f(n)},O=function(e){try{e()}catch(e){return{error:e}}},k=function(e,t){if(!e._n){e._n=!0;var n=e._c;_(function(){for(var r=e._v,i=e._s==1,a=0,o=function(t){var n,a,o=i?t.ok:t.fail,s=t.resolve,c=t.reject,l=t.domain;try{o?(i||(e._h==2&&ne(e),e._h=1),o===!0?n=r:(l&&l.enter(),n=o(r),l&&l.exit()),n===t.promise?c(y(`Promise-chain cycle`)):(a=T(n))?a.call(n,s,c):s(n)):c(r)}catch(e){c(e)}};n.length>a;)o(n[a++]);e._c=[],e._n=!1,t&&!e._h&&A(e)})}},A=function(e){g.call(s,function(){var t,n,r,i=e._v;if(te(e)&&(t=O(function(){S?b.emit(`unhandledRejection`,i,e):(n=s.onunhandledrejection)?n({promise:e,reason:i}):(r=s.console)&&r.error&&r.error(`Unhandled promise rejection`,i)}),e._h=S||te(e)?2:1),e._a=void 0,t)throw t.error})},te=function(e){if(e._h==1)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!te(t.promise))return!1;return!0},ne=function(e){g.call(s,function(){var t;S?b.emit(`rejectionHandled`,e):(t=s.onrejectionhandled)&&t({promise:e,reason:e._v})})},j=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||=t._c.slice(),k(t,!0))},M=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw y(`Promise can't be resolved itself`);(t=T(e))?_(function(){var r={_w:n,_d:!1};try{t.call(e,c(M,r,1),c(j,r,1))}catch(e){j.call(r,e)}}):(n._v=e,n._s=1,k(n,!1))}catch(e){j.call({_w:n,_d:!1},e)}}};w||(x=function(e){p(this,x,v,`_h`),f(e),r.call(this);try{e(c(M,this,1),c(j,this,1))}catch(e){j.call(this,e)}},r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(56)(x.prototype,{then:function(e,t){var n=E(h(this,x));return n.ok=typeof e!=`function`||e,n.fail=typeof t==`function`&&t,n.domain=S?b.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&k(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),D=function(){var e=new r;this.promise=e,this.resolve=c(M,e,1),this.reject=c(j,e,1)}),u(u.G+u.W+u.F*!w,{Promise:x}),n(18)(x,v),n(59)(v),a=n(6)[v],u(u.S+u.F*!w,v,{reject:function(e){var t=E(this),n=t.reject;return n(e),t.promise}}),u(u.S+u.F*(o||!w),v,{resolve:function(e){if(e instanceof x&&ee(e.constructor,this))return e;var t=E(this),n=t.resolve;return n(e),t.promise}}),u(u.S+u.F*!(w&&n(46)(function(e){x.all(e).catch(C)})),v,{all:function(e){var t=this,n=E(t),r=n.resolve,i=n.reject,a=O(function(){var n=[],a=0,o=1;m(e,!1,function(e){var s=a++,c=!1;n.push(void 0),o++,t.resolve(e).then(function(e){c||(c=!0,n[s]=e,--o||r(n))},i)}),--o||r(n)});return a&&i(a.error),n.promise},race:function(e){var t=this,n=E(t),r=n.reject,i=O(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return i&&r(i.error),n.promise}})},function(e,t,n){var r=n(61)(!0);n(27)(String,`String`,function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){n(65);for(var r=n(2),i=n(5),a=n(10),o=n(1)(`toStringTag`),s=[`NodeList`,`DOMTokenList`,`MediaList`,`StyleSheetList`,`CSSRuleList`],c=0;c<5;c++){var l=s[c],u=r[l],d=u&&u.prototype;d&&!d[o]&&i(d,o,l),a[l]=a.Array}},function(t,n){t.exports=e(`child_process`)},function(t,n){t.exports=e(`crypto`)}])})}))();function oh(e){return typeof e==`string`?`'${e}'`:new sh().serialize(e)}const sh=function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?e.localeCompare(t):n===`number`&&r===`number`?e-t:String.prototype.localeCompare.call(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}return this.serializeObjectEntries(r,Object.entries(e))}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t?.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`])e.prototype[`$`+t]=function(e){return`${t}[${e.join(`,`)}]`};for(let t of[`BigInt64Array`,`BigUint64Array`])e.prototype[`$`+t]=function(e){return`${t}[${e.join(`n,`)}${e.length>0?`n`:``}]`};return e}(),ch=globalThis.process?.getBuiltinModule?.(`crypto`)?.hash,lh=`sha256`,uh=`base64url`;function dh(e){if(ch)return ch(lh,e,uh);let t=we(lh).update(e);return globalThis.process?.versions?.webcontainer?t.digest().toString(uh):t.digest(uh)}function fh(e){return dh(oh(e))}function ph(){let e=mh();return async t=>{for(let n of t)n.module=e(n.filename);return t}}function mh(e=process.argv[1]?Ue(process.argv[1]):process.cwd(),t=Ge===`\\`){let n=t?hh(e):e;return e=>{if(!e)return;let r=t?hh(e):e,{dir:i,base:a,ext:o}=We.parse(r);(o===`.js`||o===`.mjs`||o===`.cjs`)&&(a=a.slice(0,-1*o.length));let s=decodeURIComponent(a);i||=`.`;let c=i.lastIndexOf(`/node_modules`);if(c>-1)return`${i.slice(c+14).replace(/\//g,`.`)}:${s}`;if(i.startsWith(n)){let e=i.slice(n.length+1).replace(/\//g,`.`);return e?`${e}:${s}`:s}return s}}function hh(e){return e.replace(/^[A-Z]:/,``).replace(/\\/g,`/`)}const gh=e=>{if(`flags`in e){let t=vh(e.flags),n=yh(e.flags);return{...e,featureFlags:t,featureFlagPayloads:n}}{let t=e.featureFlags??{},n=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,xh(t)])),r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,_h(e,t,n[e])]));return{...e,featureFlags:t,featureFlagPayloads:n,flags:r}}};function _h(e,t,n){return{key:e,enabled:typeof t==`string`?!0:t,variant:typeof t==`string`?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:n?JSON.stringify(n):void 0,description:void 0}}}const vh=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,bh(t)]).filter(([,e])=>e!==void 0)),yh=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(e=>{let n=t[e];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(e=>{let n=t[e].metadata?.payload;return[e,n?xh(n):void 0]}))},bh=e=>e===void 0?void 0:e.variant??e.enabled,xh=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},Sh=`0123456789abcdef`;var Ch=class e{constructor(e){this.bytes=e}static ofInner(t){if(t.length===16)return new e(t);throw TypeError(`not 128-bit length`)}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||t<0||n<0||r<0||i<0||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw RangeError(`invalid field value`);let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|n>>>8,a[7]=n,a[8]=128|r>>>24,a[9]=r>>>16,a[10]=r>>>8,a[11]=r,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,new e(a)}static parse(t){let n;switch(t.length){case 32:n=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:n=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join(``);break;case 38:n=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join(``);break;case 45:n=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join(``);break;default:break}if(n){let t=new Uint8Array(16);for(let e=0;e<16;e+=4){let r=parseInt(n.substring(2*e,2*e+8),16);t[e+0]=r>>>24,t[e+1]=r>>>16,t[e+2]=r>>>8,t[e+3]=r}return new e(t)}throw SyntaxError(`could not parse UUID string`)}toString(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=Sh.charAt(this.bytes[t]>>>4),e+=Sh.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+=`-`);return e}toHex(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=Sh.charAt(this.bytes[t]>>>4),e+=Sh.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error(`unreachable`);if(e<=7)return this.bytes.every(e=>e===0)?`NIL`:`VAR_0`;if(e<=11)return`VAR_10`;if(e<=13)return`VAR_110`;if(e<=15)return this.bytes.every(e=>e===255)?`MAX`:`VAR_RESERVED`;throw Error(`unreachable`)}getVersion(){return this.getVariant()===`VAR_10`?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},wh=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Th()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Ch.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Ch.ofInner(e)}};const Th=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())});let Eh;const Dh=()=>Oh().toString(),Oh=()=>(Eh||=new wh).generate();var kh=function(e){return e.AnonymousId=`anonymous_id`,e.DistinctId=`distinct_id`,e.Props=`props`,e.EnablePersonProcessing=`enable_person_processing`,e.PersonMode=`person_mode`,e.FeatureFlagDetails=`feature_flag_details`,e.FeatureFlags=`feature_flags`,e.FeatureFlagPayloads=`feature_flag_payloads`,e.BootstrapFeatureFlagDetails=`bootstrap_feature_flag_details`,e.BootstrapFeatureFlags=`bootstrap_feature_flags`,e.BootstrapFeatureFlagPayloads=`bootstrap_feature_flag_payloads`,e.OverrideFeatureFlags=`override_feature_flags`,e.Queue=`queue`,e.OptedOut=`opted_out`,e.SessionId=`session_id`,e.SessionStartTimestamp=`session_start_timestamp`,e.SessionLastTimestamp=`session_timestamp`,e.PersonProperties=`person_properties`,e.GroupProperties=`group_properties`,e.InstalledAppBuild=`installed_app_build`,e.InstalledAppVersion=`installed_app_version`,e.SessionReplay=`session_replay`,e.SurveyLastSeenDate=`survey_last_seen_date`,e.SurveysSeen=`surveys_seen`,e.Surveys=`surveys`,e.RemoteConfig=`remote_config`,e.FlagsEndpointWasHit=`flags_endpoint_was_hit`,e}({});const Ah=`amazonbot,amazonproductbot,app.hypefactors.com,applebot,archive.org_bot,awariobot,backlinksextendedbot,baiduspider,bingbot,bingpreview,chrome-lighthouse,dataforseobot,deepscan,duckduckbot,facebookexternal,facebookcatalog,http://yandex.com/bots,hubspot,ia_archiver,leikibot,linkedinbot,meta-externalagent,mj12bot,msnbot,nessus,petalbot,pinterest,prerender,rogerbot,screaming frog,sebot-wa,sitebulb,slackbot,slurp,trendictionbot,turnitin,twitterbot,vercel-screenshot,vercelbot,yahoo! slurp,yandexbot,zoombot,bot.htm,bot.php,(bot;,bot/,crawler,ahrefsbot,ahrefssiteaudit,semrushbot,siteauditbot,splitsignalbot,gptbot,oai-searchbot,chatgpt-user,perplexitybot,better uptime bot,sentryuptimebot,uptimerobot,headlesschrome,cypress,google-hoteladsverifier,adsbot-google,apis-google,duplexweb-google,feedfetcher-google,google favicon,google web preview,google-read-aloud,googlebot,googleother,google-cloudvertexbot,googleweblight,mediapartners-google,storebot-google,google-inspectiontool,bytespider`.split(`,`),jh=function(e,t=[]){if(!e)return!1;let n=e.toLowerCase();return Ah.concat(t).some(e=>{let t=e.toLowerCase();return n.indexOf(t)!==-1})},Mh=Array.isArray,Nh=Object.prototype;Nh.hasOwnProperty;const Ph=Nh.toString,Fh=Mh||function(e){return Ph.call(e)===`[object Array]`},Ih=e=>e===Object(e)&&!Fh(e),Lh=e=>e===void 0,Rh=e=>Ph.call(e)==`[object String]`,zh=e=>Rh(e)&&e.trim().length===0,Bh=e=>Ph.call(e)==`[object Number]`&&e===e,Vh=e=>e instanceof Error;function Hh(e){return typeof e!=`object`||!e}function Uh(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Wh(e){return!Lh(Event)&&Kh(e,Event)}function Gh(e){return Uh(e,`Object`)}function Kh(e,t){try{return e instanceof t}catch{return!1}}function qh(e,t,n,r,i){return t>n&&(r.warn(`min cannot be greater than max.`),t=n),Bh(e)?e>n?(r.warn(` cannot be greater than max: `+n+`. Using max value instead.`),n):e<t?(r.warn(` cannot be less than min: `+t+`. Using min value instead.`),t):e:(r.warn(` must be a number. using max or fallback. max: `+n+`, fallback: `+i),qh(i||n,t,n,r))}var Jh=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=qh(e.bucketSize,0,100,e._logger),this._refillRate=qh(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=qh(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,r=Math.floor(n/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess+=r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),r=this._buckets[n];return r?this._applyRefill(r,t):(r={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=r),r.tokens===0?!0:(r.tokens--,r.tokens===0&&this._onBucketRateLimited?.(e),r.tokens===0)}stop(){this._buckets={}}},Yh=class{add(e){let t=Dh();return this.promiseByIds[t]=e,e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds),t=e.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function Xh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}const Zh=(e,t,n)=>{function r(r,...i){t(()=>{let t=n[r];t(e,...i)})}return{info:(...e)=>{r(`log`,...e)},warn:(...e)=>{r(`warn`,...e)},error:(...e)=>{r(`error`,...e)},critical:(...t)=>{n.error(e,...t)},createLogger:r=>Zh(`${e} ${r}`,t,n)}},Qh=e=>e();function $h(e,t=Qh){return Zh(e,t,Xh())}const eg=`Android`;eg+``;const tg=`BlackBerry`,ng=`Samsung`;ng+``,ng+``;const rg=`Chrome`;rg+``,rg+``;const ig=`Opera`;ig+``;const ag=`Edge`;``+ag;const og=`Firefox`;og+``;const sg=`Nintendo`,cg=`PlayStation`,lg=`Xbox`;eg+``;const ug=`Windows`;ug+``;const dg=`Generic`;dg+``,dg+``;const fg=`(\\d+(\\.\\d+)?)`;RegExp(`Version/`+fg),new RegExp(lg,`i`),RegExp(cg+` \\w+`,`i`),RegExp(sg+` \\w+`,`i`),RegExp(tg+`|PlayBook|BB10`,`i`),RegExp(`rv:`+fg),RegExp(ag+`?\\/(\\d+(\\.\\d+)?)`),RegExp(`(`+rg+`|CrMo)\\/(\\d+(\\.\\d+)?)`),RegExp(`CriOS\\/`+fg),RegExp(`(UCBrowser|UCWEB)\\/`+fg),RegExp(`(`+ig+`|OPR)\\/(\\d+(\\.\\d+)?)`),RegExp(og+`\\/(\\d+(\\.\\d+)?)`),RegExp(`FxiOS\\/`+fg),RegExp(`Konqueror[:/]?`+fg,`i`),RegExp(tg+` (\\d+(\\.\\d+)?)`),RegExp(`android\\s`+fg,`i`),RegExp(`(rv:|MSIE )`+fg),RegExp(`rv:`+fg),RegExp(lg+`; Xbox (.*?)[);]`,`i`),new RegExp(sg,`i`),new RegExp(cg,`i`),new RegExp(ug,`i`),RegExp(`(`+eg+` (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)`,`i`);function pg(e,t){if(!e||typeof e!=`string`||mg(e))throw Error(t)}function mg(e){return e.trim().length===0}function hg(e){return e?.replace(/\/+$/,``)}async function gg(e,t){let n=null;for(let r=0;r<t.retryCount+1;r++){r>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(n=e,!t.retryCheck(e))throw e}}throw n}function _g(){return new Date().toISOString()}function vg(e,t){let n=setTimeout(e,t);return n?.unref&&n?.unref(),n}const yg=e=>e instanceof Error;function bg(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}var xg=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events[`*`]||[])n(e,t)}};function Sg(){return`CompressionStream`in globalThis}async function Cg(e,t=!0){try{let t=new Blob([e],{type:`text/plain`}).stream().pipeThrough(new CompressionStream(`gzip`));return await new Response(t).blob()}catch(e){return t&&console.error(`Failed to gzip compress data`,e),null}}var wg=class extends Error{constructor(e,t){super(`HTTP error while fetching PostHog: status=`+e.status+`, reqByteLength=`+t),this.response=e,this.reqByteLength=t,this.name=`PostHogFetchHttpError`}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},Tg=class extends Error{constructor(e){super(`Network error while fetching PostHog`,e instanceof Error?{cause:e}:{}),this.error=e,this.name=`PostHogFetchNetworkError`}};async function Eg(e){if(e instanceof wg){let t=``;try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error(`Error while flushing PostHog`,e);return Promise.resolve()}function Dg(e){return typeof e==`object`&&(e instanceof wg||e instanceof Tg)}function Og(e){return typeof e==`object`&&e instanceof wg&&e.status===413}var kg=class{constructor(e,t={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Yh,this._events=new xg,this._isInitialized=!1,pg(e,`You must pass your PostHog project's api key.`),this.apiKey=e,this.host=hg(t.host||`https://us.i.posthog.com`),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:Dg},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=t.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=$h(`[PostHog]`,this.logMsgIfDebug.bind(this)),this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn(`evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.`),this.disableCompression=!Sg()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(kh.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(kh.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(kh.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on(`*`,(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};this.enqueue(`identify`,r,n)})}async identifyStatelessImmediate(e,t,n){let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};await this.sendImmediate(`identify`,r,n)}captureStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue(`capture`,i,r)})}async captureStatelessImmediate(e,t,n,r){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate(`capture`,i,r)}aliasStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue(`alias`,i,r)})}async aliasStatelessImmediate(e,t,n,r){let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate(`alias`,i,r)}groupIdentifyStateless(e,t,n,r,i,a){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:`$groupidentify`,properties:{$group_type:e,$group_key:t,$group_set:n||{},...a||{}}});this.enqueue(`capture`,o,r)})}async getRemoteConfig(){await this._initPromise;let e=this.host;e===`https://us.i.posthog.com`?e=`https://us-assets.i.posthog.com`:e===`https://eu.i.posthog.com`&&(e=`https://eu-assets.i.posthog.com`);let t=`${e}/array/${this.apiKey}/config`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this._logger.error(`Remote config could not be loaded`,e),this._events.emit(`error`,e)})}async getFlags(e,t={},n={},r={},i={},a=!1){await this._initPromise;let o=a?`&config=true`:``,s=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:r,...i};this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`},body:JSON.stringify(c)};return this._logger.info(`Flags URL`,s),this.fetchWithRetry(s,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:gh(e)})).catch(e=>(this._events.emit(`error`,e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof wg)return{type:`api_error`,statusCode:e.status};if(e instanceof Tg){let t=e.error;return t instanceof Error&&(t.name===`AbortError`||t.name===`TimeoutError`)?{type:`timeout`}:{type:`connection_error`}}return{type:`unknown_error`}}async getFeatureFlagStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,n,r,i,a);if(o===void 0)return{response:void 0,requestId:void 0};let s=bh(o.response);return s===void 0&&(s=!1),{response:s,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,n,r,i,a,[e]);if(o!==void 0)return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,n,r,i,a,[e]);if(!o)return;let s=o[e];return s===void 0?null:s}async getFeatureFlagPayloadsStateless(e,t={},n={},r={},i,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)).payloads}async getFeatureFlagsStateless(e,t={},n={},r={},i,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,n,r,i,a);return o?{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o={};(i??this.disableGeoip)&&(o.geoip_disable=!0),a&&(o.flag_keys_to_evaluate=a);let s=await this.getFlags(e,t,n,r,o);if(!s.success)return;let c=s.response;return c.errorsWhileComputingFlags&&console.error(`[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices`),c.quotaLimited?.includes(`feature_flags`)?(console.warn(`[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts`),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this._logger.info(`Loading surveys is disabled.`),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}},n=(await this.fetchWithRetry(e,t).then(e=>{if(e.status!==200||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,n=Error(t);this._logger.error(n),this._events.emit(`error`,Error(t));return}return e.json()}).catch(e=>{this._logger.error(`Surveys API could not be loaded`,e),this._events.emit(`error`,e)}))?.surveys;return n&&this._logger.info(`Surveys fetched from API: `,JSON.stringify(n)),n??[]}get props(){return this._props||=this.getPersistedProperty(kh.Props),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(kh.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(kh.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r=this.prepareMessage(e,t,n);if(r=this.processBeforeEnqueue(r),r===null)return;let i=this.getPersistedProperty(kh.Queue)||[];i.length>=this.maxQueueSize&&(i.shift(),this._logger.info(`Queue is full, the oldest event is dropped.`)),i.push({message:r}),this.setPersistedProperty(kh.Queue,i),this._events.emit(e,r),i.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=vg(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r=this.prepareMessage(e,t,n);if(r=this.processBeforeEnqueue(r),r===null)return;let i={api_key:this.apiKey,batch:[r],sent_at:_g()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=`${this.host}/batch/`,s=this.disableCompression?null:await Cg(a,this.isDebug),c={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...s!==null&&{"Content-Encoding":`gzip`}},body:s||a};try{await this.fetchWithRetry(o,c)}catch(e){this._events.emit(`error`,e)}}prepareMessage(e,t,n){let r={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:_g(),uuid:n?.uuid?n.uuid:Dh()};return(n?.disableGeoip??this.disableGeoip)&&(r.properties||={},r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&=(clearTimeout(this._flushTimer),void 0)}flushBackground(){this.flush().catch(async e=>{await Eg(e)})}async flush(){let e=bg([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),bg([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==``&&(t[`User-Agent`]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(kh.Queue)||[];if(!e.length)return;let t=[],n=e.length;for(;e.length>0&&t.length<n;){let n=e.slice(0,this.maxBatchSize),r=n.map(e=>e.message),i=async()=>{let t=(this.getPersistedProperty(kh.Queue)||[]).slice(n.length);this.setPersistedProperty(kh.Queue,t),e=t,await this.flushStorage()},a={api_key:this.apiKey,batch:r,sent_at:_g()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),s=`${this.host}/batch/`,c=this.disableCompression?null:await Cg(o,this.isDebug),l={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...c!==null&&{"Content-Encoding":`gzip`}},body:c||o},u={retryCheck:e=>Og(e)?!1:Dg(e)};try{await this.fetchWithRetry(s,l,u)}catch(e){if(Og(e)&&r.length>1){this.maxBatchSize=Math.max(1,Math.floor(r.length/2)),this._logger.warn(`Received 413 when sending batch of size ${r.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof Tg||await i(),this._events.emit(`error`,e),e}await i(),t.push(...r)}this._events.emit(`flush`,t)}async fetchWithRetry(e,t,n,r){let i=t.body?t.body:``,a=-1;try{a=i instanceof Blob?i.size:Buffer.byteLength(i,`utf8`)}catch{a=i instanceof Blob?i.size:new TextEncoder().encode(i).length}return await gg(async()=>{let n=new AbortController,i=vg(()=>n.abort(),r??this.requestTimeout),o=null;try{o=await this.fetch(e,{signal:n.signal,...t})}catch(e){throw new Tg(e)}finally{clearTimeout(i)}if(t.mode!==`no-cors`&&(o.status<200||o.status>=400))throw new wg(o,a);return o},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(kh.Queue)||[]).length===0||(await this.flush(),t)););}catch(e){if(!Dg(e))throw e;await Eg(e)}},r;try{return await Promise.race([new Promise((n,i)=>{r=vg(()=>{this._logger.error(`Timed out while shutting down PostHog`),t=!0,i(`Timeout while shutting down PostHog. Some events may not have been sent.`)},e)}),n()])}finally{clearTimeout(r)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn(`shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup`):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};let Ag,jg,Mg;function Ng(e){let t=globalThis._posthogChunkIds;if(!t)return;let n=Object.keys(t);return Mg&&n.length===jg?Mg:(jg=n.length,Mg=n.reduce((n,r)=>{Ag||={};let i=Ag[r];if(i)n[i[0]]=i[1];else{let i=e(r);for(let e=i.length-1;e>=0;e--){let a=i[e]?.filename,o=t[r];if(a&&o){n[a]=o,Ag[r]=[a,o];break}}}return n},{}),Mg)}var Pg=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:`generic`},r=this.buildCoercingContext(n,t,0).apply(e),i=this.buildParsingContext(t),a=this.parseStacktrace(r,i);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:`error`}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&Fh(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:`Error`,value:`Unknown error`,stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let r;return e.stack!=``&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:r}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??`generic`,handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:`raw`,frames:e.stack});let r=[n];return e.cause!=null&&r.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),r}buildParsingContext(e){return{chunkIdMap:Ng(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let r=(n,r)=>{if(r<=4){let i=this.buildCoercingContext(e,t,r);return this.applyCoercers(n,i)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,n),next:e=>r(e,n+1)}}};const Fg=/^\s*[-]{4,}$/,Ig=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Lg=(e,t)=>{let n=e.match(Ig);if(n){let e,r,i,a,o;if(n[1]){i=n[1];let t=i.lastIndexOf(`.`);if(i[t-1]===`.`&&t--,t>0){e=i.slice(0,t),r=i.slice(t+1);let n=e.indexOf(`.Module`);n>0&&(i=i.slice(n+1),e=e.slice(0,n))}a=void 0}r&&(a=e,o=r),r===`<anonymous>`&&(o=void 0,i=void 0),i===void 0&&(o||=`?`,i=a?`${a}.${o}`:o);let s=n[2]?.startsWith(`file://`)?n[2].slice(7):n[2],c=n[5]===`native`;return s?.match(/\/[A-Z]:/)&&(s=s.slice(1)),!s&&n[5]&&!c&&(s=n[5]),{filename:s?decodeURI(s):void 0,module:void 0,function:i,lineno:zg(n[3]),colno:zg(n[4]),in_app:Rg(s||``,c),platform:t}}if(e.match(Fg))return{filename:e,platform:t}};function Rg(e,t=!1){return!(t||e&&!e.startsWith(`/`)&&!e.match(/^[A-Z]:/)&&!e.startsWith(`.`)&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes(`node_modules/`)}function zg(e){return parseInt(e||``,10)||void 0}const Bg=/\(error: (.*)\)/;function Vg(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>({...e,filename:e.filename||Hg(t).filename,function:e.function||`?`}))}function Hg(e){return e[e.length-1]||{}}function Ug(e,...t){return(n,r=0)=>{let i=[],a=n.split(`
35
- `);for(let n=r;n<a.length;n++){let r=a[n];if(r.length>1024)continue;let o=Bg.test(r)?r.replace(Bg,`$1`):r;if(!o.match(/\S*Error: /)){for(let n of t){let t=n(o,e);if(t){i.push(t);break}}if(i.length>=50)break}}return Vg(i)}}var Wg=class{match(e){return Vh(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message==`string`?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};const Gg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var Kg=class{match(e){return typeof e==`string`}coerce(e,t){let[n,r]=this.getInfos(e);return{type:n??`Error`,value:r??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t=`Error`,n=e,r=e.match(Gg);return r&&(t=r[1],n=r[2]),[t,n]}};const qg=[`fatal`,`error`,`warning`,`log`,`info`,`debug`];function Jg(e,t=40){let n=Object.keys(e);if(n.sort(),!n.length)return`[object has no keys]`;for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`, `);if(!(r.length>t))return e===n.length||r.length<=t?r:`${r.slice(0,t)}...`}return``}var Yg=class{match(e){return typeof e==`object`&&!!e}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:`error`,synthetic:!0}}getType(e){return Wh(e)?e.constructor.name:`Error`}getValue(e){if(`name`in e&&typeof e.name==`string`){let t=`'${e.name}' captured as exception`;return`message`in e&&typeof e.message==`string`&&(t+=` with message: '${e.message}'`),t}if(`message`in e&&typeof e.message==`string`)return e.message;let t=this.getObjectClassName(e),n=Jg(e);return`${t&&t!==`Object`?`'${t}'`:`Object`} captured as exception with keys: ${n}`}isSeverityLevel(e){return Rh(e)&&!zh(e)&&qg.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(yg(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Xg=class{match(e){return Wh(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Jg(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},Zg=class{match(e){return Hh(e)}coerce(e,t){return{type:`Error`,value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},Qg=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};const $g=new Qg(25),e_=new Qg(20);async function t_(e){let t={};for(let n=e.length-1;n>=0;n--){let r=e[n],i=r?.filename;!r||typeof i!=`string`||typeof r.lineno!=`number`||o_(i)||s_(r)||(t[i]||(t[i]=[]),t[i].push(r.lineno))}let n=Object.keys(t);if(n.length==0)return e;let r=[];for(let e of n){if(e_.get(e))continue;let n=t[e];if(!n)continue;n.sort((e,t)=>e-t);let i=l_(n);if(i.every(t=>c_(e,t)))continue;let a=p_($g,e,{});r.push(n_(e,i,a))}return await Promise.all(r).catch(()=>{}),e&&e.length>0&&r_(e,$g),$g.reduce(),e}function n_(e,t,n){return new Promise(r=>{let i=qe(e),a=Je({input:i});function o(){i.destroy(),r()}let s=0,c=0,l=t[c];if(l===void 0)return void o();let u=l[0],d=l[1];function f(){e_.set(e,1),a.close(),a.removeAllListeners(),o()}i.on(`error`,f),a.on(`error`,f),a.on(`close`,o),a.on(`line`,e=>{if(s++,!(s<u)&&(n[s]=m_(e,0),s>=d)){if(c===t.length-1){a.close(),a.removeAllListeners();return}c++;let e=t[c];if(e===void 0){a.close(),a.removeAllListeners();return}u=e[0],d=e[1]}})})}function r_(e,t){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno==`number`){let e=t.get(n.filename);if(e===void 0)continue;i_(n.lineno,n,e)}}function i_(e,t,n){if(t.lineno===void 0||n===void 0)return;t.pre_context=[];for(let r=d_(e);r<e;r++){let e=n[r];if(e===void 0)return void a_(t);t.pre_context.push(e)}if(n[e]===void 0)return void a_(t);t.context_line=n[e];let r=f_(e);t.post_context=[];for(let i=e+1;i<=r;i++){let e=n[i];if(e===void 0)break;t.post_context.push(e)}}function a_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function o_(e){return e.startsWith(`node:`)||e.endsWith(`.min.js`)||e.endsWith(`.min.cjs`)||e.endsWith(`.min.mjs`)||e.startsWith(`data:`)}function s_(e){return e.lineno!==void 0&&e.lineno>1e4||e.colno!==void 0&&e.colno>1e3}function c_(e,t){let n=$g.get(e);if(n===void 0)return!1;for(let e=t[0];e<=t[1];e++)if(n[e]===void 0)return!1;return!0}function l_(e){if(!e.length)return[];let t=0,n=e[0];if(typeof n!=`number`)return[];let r=u_(n),i=[];for(;;){if(t===e.length-1){i.push(r);break}let n=e[t+1];if(typeof n!=`number`)break;n<=r[1]?r[1]=n+7:(i.push(r),r=u_(n)),t++}return i}function u_(e){return[d_(e),f_(e)]}function d_(e){return Math.max(1,e-7)}function f_(e){return e+7}function p_(e,t,n){let r=e.get(t);return r===void 0?(e.set(t,n),n):r}function m_(e,t){let n=e,r=n.length;if(r<=150)return n;t>r&&(t=r);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,r);return a>r-5&&(a=r),a===r&&(i=Math.max(a-140,0)),n=n.slice(i,a),i>0&&(n=`...${n}`),a<r&&(n+=`...`),n}function h_(e,t){let n=!1;return Object.assign(r=>{let i=global.process.listeners(`uncaughtException`).filter(e=>e.name!==`domainUncaughtExceptionClear`&&!0!==e._posthogErrorHandler).length===0;e(r,{mechanism:{type:`onuncaughtexception`,handled:!1}}),!n&&i&&(n=!0,t(r))},{_posthogErrorHandler:!0})}function g_(e,t){globalThis.process?.on(`uncaughtException`,h_(e,t))}function __(e){globalThis.process?.on(`unhandledRejection`,t=>e(t,{mechanism:{type:`onunhandledrejection`,handled:!1}}))}var v_=class e{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Jh({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Ih(e)&&`__posthog_previously_captured_error`in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,n,r){let i={...r};n||(i.$process_person_profile=!1);let a=this.errorPropertiesBuilder.buildFromUnknown(e,t);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:`$exception`,distinctId:n||Dh(),properties:{...a,...i},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(g_(this.onException.bind(this),this.onFatalError.bind(this)),__(this.onException.bind(this)))}onException(t,n){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let r=await e.buildEventMessage(t,n),i=r.properties?.$exception_list[0]?.type??`Exception`;return this._rateLimiter.consumeRateLimit(i)?void this._logger.info(`Skipping exception capture because of client rate limiting.`,{exception:i}):this.client.capture(r)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};const y_={ERRORS_WHILE_COMPUTING:`errors_while_computing_flags`,FLAG_MISSING:`flag_missing`,QUOTA_LIMITED:`quota_limited`,UNKNOWN_ERROR:`unknown_error`};async function b_(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`SubtleCrypto API not available`);let n=await t.digest(`SHA-1`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const x_=[`is_not`];var S_=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name=`ClientError`,this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},C_=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},w_=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:r,host:i,customHeaders:a,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=r,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=a,this.onLoad=o.onLoad,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},r={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:r,evaluationCache:i}}async getFeatureFlag(e,t,n={},r={},i={}){await this.loadFeatureFlags();let a,o;if(!this.loadedSuccessfullyOnce)return a;if(o=this.featureFlagsByKey[e],o!==void 0){let s=this.createEvaluationContext(t,n,r,i);try{a=(await this.computeFlagAndPayloadLocally(o,s)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof C_||t instanceof Q?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},r={},i=this.featureFlags.length==0,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:i}=await this.computeFlagAndPayloadLocally(e,o);n[e.key]=t,i&&(r[e.key]=i)}catch(t){t instanceof C_||t instanceof Q?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),i=!0}})),{response:n,payloads:r,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:r,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let a;a=r===void 0?await this.computeFlagValueLocally(e,t):r;let o=this.getFeatureFlagPayload(e.key,a);return{value:a,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:r,personProperties:i,groupProperties:a}=t;if(e.ensure_experience_continuity)throw new Q(`Flag has experience continuity enabled`);if(!e.active)return!1;let o=(e.filters||{}).aggregation_group_type_index;if(o!=null){let n=this.groupTypeMapping[String(o)];if(!n)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${o} for feature flag ${e.key}`)),new Q(`Flag has unknown group type index`);if(!(n in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier===`device_id`&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id===``)&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let s=a[n];return await this.matchFeatureFlagProperties(e,r[n],s,t)}{let r=this.getBucketingValueForFlag(e,n,i);if(r===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new Q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,r,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier===`device_id`){let e=n?.$device_id;return e==null||e===``?void 0:e}return t}getFeatureFlagPayload(e,t){let n=null;if(!1!==t&&t!=null&&(typeof t==`boolean`?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t==`string`&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n==`object`)return n;if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:r}=n,i=e.key;if(!this.featureFlagsByKey)throw new Q(`Feature flags not available for dependency evaluation`);if(!(`dependency_chain`in e))throw new Q(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new Q(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(a.length===0)throw new Q(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let e of a){if(!(e in r)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{r[e]=await this.computeFlagValueLocally(t,n)}catch(t){throw new Q(`Error evaluating flag dependency '${e}' for flag '${i}': ${t}`)}else r[e]=!1;else throw new Q(`Missing flag dependency '${e}' for flag '${i}'`)}if(r[e]==null)throw new Q(`Dependency '${e}' could not be evaluated`)}let o=r[i];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return typeof e==`boolean`?e===t||typeof t==`string`&&t!==``&&!0===e:typeof e==`string`?t===e:!1}async matchFeatureFlagProperties(e,t,n,r){let i=e.filters||{},a=i.groups||[],o=!1,s;for(let c of a)try{if(await this.isConditionMatch(e,t,c,n,r)){let n=c.variant,r=i.multivariate?.variants||[];s=n&&r.some(e=>e.key===n)?n:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(e instanceof C_)throw e;if(e instanceof Q)o=!0;else throw e}if(s!==void 0)return s;if(o)throw new Q(`Can't determine if feature flag is enabled or not with given properties`);return!1}async isConditionMatch(e,t,n,r,i){let a=n.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((n.properties||[]).length>0){for(let e of n.properties){let t=e.type,n=!1;if(n=t===`cohort`?O_(e,r,this.cohorts,this.debugMode):t===`flag`?await this.evaluateFlagDependency(e,r,i):E_(e,r,o),!n)return!1}if(a==null)return!0}return!(a!=null&&await T_(e.key,t)>a/100)}async getMatchingVariant(e,t){let n=await T_(e.key,t,`variant`),r=this.variantLookupTable(e).find(e=>n>=e.valueMin&&n<e.valueMax);if(r)return r.key}variantLookupTable(e){let t=[],n=0,r=0;return((e.filters||{}).multivariate?.variants||[]).forEach(e=>{r=n+e.rollout_percentage/100,t.push({valueMin:n,valueMax:r,key:e.key}),n=r}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(`, `)}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping fetch, in backoff period`)):(this.loadingPromise||=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0}),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&=(clearTimeout(this.poller),void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache(`Loaded flags from cache (skipped fetch)`)||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Flags not modified (304), using cached data`)),this.flagsEtag=t.headers?.get(`ETag`)??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new S_(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn(`[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts`),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new S_(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new S_(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!(`flags`in n))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get(`ETag`)??void 0;let r={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(r),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(r)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags);break}default:return}}catch(e){e instanceof S_&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e=`GET`,t){let n={...this.customHeaders,"Content-Type":`application/json`,Authorization:`Bearer ${this.personalApiKey}`};return t&&(n[`If-None-Match`]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions(`GET`,this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout==`number`){let e=new AbortController;n=vg(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}};async function T_(e,t,n=``){let r=await b_(`${e}.${t}${n}`);return parseInt(r.slice(0,15),16)/0x1000000000000000}function E_(e,t,n){let r=e.key,i=e.value,a=e.operator||`exact`;if(r in t){if(a===`is_not_set`)throw new Q(`Operator is_not_set is not supported`)}else throw new Q(`Property ${r} not found in propertyValues`);let o=t[r];if(o==null&&!x_.includes(a))return n&&n(`Property ${r} cannot have a value of null/undefined with the ${a} operator`),!1;function s(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function c(e,t,n){if(n===`gt`)return e>t;if(n===`gte`)return e>=t;if(n===`lt`)return e<t;if(n===`lte`)return e<=t;throw Error(`Invalid operator: ${n}`)}switch(a){case`exact`:return s(i,o);case`is_not`:return!s(i,o);case`is_set`:return r in t;case`icontains`:return String(o).toLowerCase().includes(String(i).toLowerCase());case`not_icontains`:return!String(o).toLowerCase().includes(String(i).toLowerCase());case`regex`:return A_(String(i))&&String(o).match(String(i))!==null;case`not_regex`:return A_(String(i))&&String(o).match(String(i))===null;case`gt`:case`gte`:case`lt`:case`lte`:{let e=typeof i==`number`?i:null;if(typeof i==`string`)try{e=parseFloat(i)}catch{}return e==null||o==null?c(String(o),String(i),a):typeof o==`string`?c(o,String(i),a):c(o,e,a)}case`is_date_after`:case`is_date_before`:{if(typeof i==`boolean`)throw new Q(`Date operations cannot be performed on boolean values`);let e=L_(String(i));if(e??=I_(i),e==null)throw new Q(`Invalid date: ${i}`);let t=I_(o);return[`is_date_before`].includes(a)?t<e:t>e}case`semver_eq`:return M_(j_(String(o)),j_(String(i)))===0;case`semver_neq`:return M_(j_(String(o)),j_(String(i)))!==0;case`semver_gt`:return M_(j_(String(o)),j_(String(i)))>0;case`semver_gte`:return M_(j_(String(o)),j_(String(i)))>=0;case`semver_lt`:return M_(j_(String(o)),j_(String(i)))<0;case`semver_lte`:return M_(j_(String(o)),j_(String(i)))<=0;case`semver_tilde`:{let e=j_(String(o)),{lower:t,upper:n}=N_(String(i));return M_(e,t)>=0&&M_(e,n)<0}case`semver_caret`:{let e=j_(String(o)),{lower:t,upper:n}=P_(String(i));return M_(e,t)>=0&&M_(e,n)<0}case`semver_wildcard`:{let e=j_(String(o)),{lower:t,upper:n}=F_(String(i));return M_(e,t)>=0&&M_(e,n)<0}default:throw new Q(`Unknown operator: ${a}`)}}function D_(e,t){if(!(e in t))throw new C_(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function O_(e,t,n,r=!1){let i=String(e.value);D_(i,n);let a=n[i];return k_(a,t,n,r)}function k_(e,t,n,r=!1){if(!e)return!0;let i=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if(`values`in a[0]){for(let e of a)try{let a=k_(e,t,n,r);if(i===`AND`){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof C_)throw t;if(t instanceof Q)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Q(`Can't match cohort without a given cohort property value`);return i===`AND`}for(let e of a)try{let a;if(e.type===`cohort`)a=O_(e,t,n,r);else if(e.type===`flag`){r&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${e.key||`unknown`}'`);continue}else a=E_(e,t);let o=e.negation||!1;if(i===`AND`){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof C_)throw t;if(t instanceof Q)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Q(`can't match cohort without a given cohort property value`);return i===`AND`}function A_(e){try{return new RegExp(e),!0}catch{return!1}}function j_(e){let t=String(e).trim().replace(/^[vV]/,``).split(`-`)[0].split(`+`)[0];if(!t||t.startsWith(`.`))throw new Q(`Invalid semver: ${e}`);let n=t.split(`.`),r=t=>{if(t===void 0||t===``)return 0;if(!/^\d+$/.test(t))throw new Q(`Invalid semver: ${e}`);return parseInt(t,10)};return[r(n[0]),r(n[1]),r(n[2])]}function M_(e,t){for(let n=0;n<3;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function N_(e){let t=j_(e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function P_(e){let[t,n,r]=j_(e),i=[t,n,r],a;return a=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:i,upper:a}}function F_(e){let t=String(e).trim().replace(/^[vV]/,``).replace(/\.\*$/,``).replace(/\*$/,``);if(!t)throw new Q(`Invalid wildcard semver: ${e}`);let n=t.split(`.`),r=parseInt(n[0],10);if(isNaN(r))throw new Q(`Invalid wildcard semver: ${e}`);let i,a;if(n.length===1)i=[r,0,0],a=[r+1,0,0];else{let t=parseInt(n[1],10);if(isNaN(t))throw new Q(`Invalid wildcard semver: ${e}`);i=[r,t,0],a=[r,t+1,0]}return{lower:i,upper:a}}function I_(e){if(e instanceof Date)return e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Q(`${e} is in an invalid date format`)}throw new Q(`The date provided ${e} must be a string, number, or date object`)}function L_(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let r=t.groups.interval;if(r==`h`)n.setUTCHours(n.getUTCHours()-e);else if(r==`d`)n.setUTCDate(n.getUTCDate()-e);else if(r==`w`)n.setUTCDate(n.getUTCDate()-7*e);else if(r==`m`)n.setUTCMonth(n.getUTCMonth()-e);else{if(r!=`y`)return null;n.setUTCFullYear(n.getUTCFullYear()-e)}return n}}var R_=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t===null?void 0:t}constructor(){this._memoryStorage={}}};const z_=3e4;var B_=class extends kg{constructor(e,t={}){if(super(e,t),this._memoryStorage=new R_,this.options=t,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof t.featureFlagsPollingInterval==`number`?Math.max(t.featureFlagsPollingInterval,100):z_,typeof t.waitUntilDebounceMs==`number`&&(this.options.waitUntilDebounceMs=Math.max(t.waitUntilDebounceMs,0)),typeof t.waitUntilMaxWaitMs==`number`&&(this.options.waitUntilMaxWaitMs=Math.max(t.waitUntilMaxWaitMs,0)),t.personalApiKey){if(t.personalApiKey.includes(`phc_`))throw Error(`Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.`);!1!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new w_({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit(`error`,e)},onLoad:e=>{this._events.emit(`localEvaluationFlagsLoaded`,e)},customHeaders:this.getCustomHeaders(),cacheProvider:t.flagDefinitionCacheProvider,strictLocalEvaluation:t.strictLocalEvaluation}))}this.errorTracking=new v_(this,t,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||5e4}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=super.flush(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,n=new Promise(e=>{t=e});try{e(n)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt>=(this.options.waitUntilMaxWaitMs??500);if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),t)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=vg(()=>{this.resolveWaitUntilFlush()},n)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getLibraryVersion(){return`5.28.5`}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){typeof e==`string`&&this._logger.warn(`Called capture() with a string as the first argument when an object was expected.`),e.event===`$exception`&&!e._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStateless(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}async captureImmediate(e){return typeof e==`string`&&this._logger.warn(`Called captureImmediate() with a string as the first argument when an object was expected.`),e.event===`$exception`&&!e._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStatelessImmediate(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:r,$set_once:i,$anon_distinct_id:a,...o}=t,s={$set:r||o,$set_once:i||{},$anon_distinct_id:a??void 0};super.identifyStateless(e,s,{disableGeoip:n})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:r,$set_once:i,$anon_distinct_id:a,...o}=t,s={$set:r||o,$set_once:i||{},$anon_distinct_id:a??void 0};super.identifyStatelessImmediate(e,s,{disableGeoip:n})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=z_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{r(),t(!1)},e),r=this._events.on(`localEvaluationFlagsLoaded`,e=>{clearTimeout(n),r(),t(e>0)})})}_resolveDistinctId(e,t){return typeof e==`string`?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},r){let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let t=this._flagOverrides[e];if(t===void 0)return;let n=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:typeof t==`string`?t:void 0,payload:n}}let{groups:a,disableGeoip:o}=n,{onlyEvaluateLocally:s,personProperties:c,groupProperties:l}=n,u=this.addLocalPersonAndGroupProperties(t,a,c,l);c=u.allPersonProperties,l=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,a,c,l);s??=this.options.strictLocalEvaluation??!1;let f,p=!1,m,h,g,_,v,y;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let n=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,d,{matchValue:r});if(n){p=!0;let r=n.value;_=t.id,y=`Evaluated locally`,f={key:e,enabled:!1!==r,variant:typeof r==`string`?r:void 0,payload:n.payload??void 0}}}catch(t){if(t instanceof C_||t instanceof Q)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!p&&!s){let t=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,o,[e]);if(t===void 0)g=y_.UNKNOWN_ERROR;else{m=t.requestId,h=t.evaluatedAt;let n=[];t.errorsWhileComputingFlags&&n.push(y_.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes(`feature_flags`)&&n.push(y_.QUOTA_LIMITED);let r=t.flags[e];if(r===void 0)n.push(y_.FLAG_MISSING);else{_=r.metadata?.id,v=r.metadata?.version,y=r.reason?.description??r.reason?.code;let t;if(r.metadata?.payload!==void 0)try{t=JSON.parse(r.metadata.payload)}catch{t=r.metadata.payload}f={key:e,enabled:r.enabled,variant:r.variant,payload:t}}n.length>0&&(g=n.join(`,`))}}if(i){let n=f===void 0?void 0:!1===f.enabled?!1:f.variant??!0,r=`${e}_${n}`;if(!(t in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[t].includes(r)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(r):this.distinctIdHasSentFlagCalls[t]=[r];let i={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:_,$feature_flag_version:v,$feature_flag_reason:y,locally_evaluated:p,[`$feature/${e}`]:n,$feature_flag_request_id:m,$feature_flag_evaluated_at:p?Date.now():h};if(p&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();e!==void 0&&(i.$feature_flag_definitions_loaded_at=e)}g&&(i.$feature_flag_error=g),this.capture({distinctId:t,event:`$feature_flag_called`,properties:i,groups:a,disableGeoip:o})}}return f!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[e]}),f}async getFeatureFlag(e,t,n){let r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(r!==void 0)return!1===r.enabled?!1:r.variant??!0}async getFeatureFlagPayload(e,t,n,r){if(this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:r,options:i}=this._resolveDistinctId(t,n);return r?this._getFeatureFlagResult(e,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn(`[PostHog] distinctId is required — pass it explicitly or use withContext()`)}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw Error(`Personal API key is required for remote config payload decryption`);let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){let r=await this.getFeatureFlag(e,t,n);if(r!==void 0)return!!r||!1}async getAllFlags(e,t){let{distinctId:n,options:r}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,r)).featureFlags||{}:(this._logger.warn(`[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()`),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:r}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn(`[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()`),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:a,flagKeys:o}=r||{},{onlyEvaluateLocally:s,personProperties:c,groupProperties:l}=r||{},u=this.addLocalPersonAndGroupProperties(n,i,c,l);c=u.allPersonProperties,l=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,i,c,l);s??=this.options.strictLocalEvaluation??!1;let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),p={},m={},h=!0;if(f&&(p=f.response,m=f.payloads,h=f.fallbackToFlags),h&&!s){let e=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,o);p={...p,...e.flags||{}},m={...m,...e.payloads||{}}}return this._flagOverrides!==void 0&&(p={...p,...this._flagOverrides}),this._payloadOverrides!==void 0&&(m={...m,...this._payloadOverrides}),{featureFlags:p,featureFlagPayloads:m}}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:r,disableGeoip:i}){super.groupIdentifyStateless(e,t,n,{disableGeoip:i},r)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){`flags`in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),`payloads`in e&&(!1===e.payloads?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(`flags`in t){let e=t.flags;if(!1===e||Array.isArray(e)||typeof e==`object`&&e)return!0}if(`payloads`in t){let e=t.payloads;if(!1===e||typeof e==`object`&&e)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown();try{return await super._shutdown(e)}finally{t?.()}}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,Authorization:`Bearer ${this.options.personalApiKey}`}},r=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout==`number`){let e=new AbortController;r=vg(()=>{e.abort()},this.options.requestTimeout),n.signal=e.signal}try{return await this.fetch(t,n)}catch(e){this._events.emit(`error`,e);return}finally{r&&clearTimeout(r)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},r={};for(let[i,a]of Object.entries(e))if(Gh(a)&&t&&i in t){let e={};for(let[t,n]of Object.entries(a))e[String(t)]=String(n);r[String(i)]=e}else n[String(i)]=String(a);return{personProperties:n,groupProperties:r}}async getFeatureFlagsForEvent(e,t,n,r){let i=r?.personProperties||{},a=r?.groupProperties||{},o=r?.flagKeys;if(r?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,a,n)).flags}addLocalPersonAndGroupProperties(e,t,n,r){let i={distinct_id:e,...n||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...r?.[e]||{}};return{allPersonProperties:i,allGroupProperties:a}}createFeatureFlagEvaluationContext(e,t,n,r){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:r||{},evaluationCache:{}}}captureException(e,t,n,r){if(!v_.isPreviouslyCapturedError(e)){let i=Error(`PostHog syntheticException`);this.addPendingPromise(v_.buildEventMessage(e,{syntheticException:i},t,n).then(e=>this.capture({...e,uuid:r})))}}async captureExceptionImmediate(e,t,n){if(!v_.isPreviouslyCapturedError(e)){let r=Error(`PostHog syntheticException`);return this.addPendingPromise(v_.buildEventMessage(e,{syntheticException:r},t,n).then(e=>this.captureImmediate(e)))}}async prepareEventMessage(e){let{distinctId:t,event:n,properties:r,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c}=e,l=this.context?.get(),u=t||l?.distinctId,d={...this.props,...l?.properties||{},...r||{}};u||(u=Dh(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:u,event:n,properties:d,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c});if(!f)return Promise.reject(null);let p=await Promise.resolve().then(async()=>{if(a){let e=typeof a==`object`?a:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,i,s,e)}return f.event,{}}).then(e=>{let t={};if(e)for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let n=Object.keys(e||{}).filter(t=>e?.[t]!==!1).sort();return n.length>0&&(t.$active_feature_flags=n),t}).catch(()=>({})).then(e=>({...e,...f.properties||{},$groups:f.groups||i}));return f.event===`$pageview`&&this.options.__preview_capture_bot_pageviews&&typeof p.$raw_user_agent==`string`&&jh(p.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event=`$bot_pageview`,p.$browser_type=`bot`),{distinctId:f.distinctId,event:f.event,properties:p,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],r=e;for(let t of n){if(r=t(r),!r)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!r.properties||Object.keys(r.properties).length===0){let e=`Event '${r.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return r}},V_=class{constructor(){this.storage=new Ye}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};const H_=`posthog-node`;function U_(e,{organization:t,projectId:n,prefix:r,severityAllowList:i=[`error`],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(i===`*`||i.includes(o.level)))return o;o.tags||={};let s=o.tags[W_.POSTHOG_ID_TAG];if(s===void 0)return o;let c=e.options.host??`https://us.i.posthog.com`,l=new URL(`/project/${e.apiKey}/person/${s}`,c).toString();o.tags[`PostHog Person URL`]=l;let u=o.exception?.values||[],d=u.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:`raw`,frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:`node:javascript`}))}:void 0})),f={$exception_message:u[0]?.value||o.message,$exception_type:u[0]?.type,$exception_level:o.level,$exception_list:d,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:u[0]?.value||o.message,$sentry_exception_type:u[0]?.type,$sentry_tags:o.tags};return t&&n&&(f.$sentry_url=(r||`https://sentry.io/organizations/`)+t+`/issues/?project=`+n+`&query=`+o.event_id),a&&e.capture({event:`$exception`,distinctId:s,properties:f}),o}}var W_=class{static#e=this.POSTHOG_ID_TAG=`posthog_distinct_id`;constructor(e,t,n,r,i){this.name=H_,this.name=H_,this.setupOnce=function(a,o){let s=o()?.getClient()?.getDsn()?.projectId;a(U_(e,{organization:t,projectId:s,prefix:n,severityAllowList:r,sendExceptionsToPostHog:i??!0}))}}};v_.errorPropertiesBuilder=new Pg([new Xg,new Wg,new Yg,new Kg,new Zg],Ug(`node:javascript`,Lg),[ph(),t_]);const G_=new class extends B_{getLibraryId(){return`posthog-node`}initializeContext(){return new V_}}(`phc_t5FKk9mlc4pKbbBimiIlrM5Acq9meRp1FSuNjmwxjAX`,{host:`https://us.i.posthog.com`});var K_=class extends C.Service()(`@expect/AnalyticsProvider`){static layerPostHog=m.succeed(this)({capture:e=>u.sync(()=>{G_.captureImmediate({event:e.eventName,properties:e.properties,distinctId:e.distinctId})}),identify:e=>u.sync(()=>{G_.identify({distinctId:e.distinctId,properties:{email:e.email,...e.name?{name:e.name}:{}}})}),flush:u.tryPromise({try:()=>G_.flush(),catch:e=>e}).pipe(u.ignore)});static layerDev=m.succeed(this)({capture:e=>u.logInfo(`Tracked event`,{eventName:e.eventName,distinctId:e.distinctId,...e.properties}).pipe(u.annotateLogs({module:`Analytics`})),identify:e=>u.logInfo(`Identified user`,{distinctId:e.distinctId,email:e.email,name:e.name}).pipe(u.annotateLogs({module:`Analytics`})),flush:u.void})},q_=class extends C.Service()(`@expect/Analytics`,{make:u.gen(function*(){let e=yield*K_,t=yield*c.option(c.string(`NO_TELEMETRY`)),n=yield*c.option(c.string(`NO_TELEMTRY`)),r=_.match(t,{onNone:()=>!1,onSome:e=>e===`1`})||_.match(n,{onNone:()=>!1,onSome:e=>e===`1`}),i=yield*u.tryPromise(()=>(0,ah.machineId)()).pipe(u.orDie),a=fh(process.cwd()),o=(t,...[n])=>r?u.void:u.gen(function*(){let r={timestamp:new Date().toISOString(),projectId:a};yield*e.capture({eventName:t,properties:{...r,...n??{}},distinctId:i})}).pipe(u.catchCause(e=>u.logWarning(`Analytics capture failed`,{eventName:t,cause:e}).pipe(u.annotateLogs({module:`Analytics`}))));return{capture:o,track:((e,t)=>n=>u.tap(n,n=>{let r=t?t(n):void 0;return o.call(void 0,e,...r===void 0?[]:[r])})),flush:r?u.void:e.flush}})}){static layerPostHog=m.effect(this)(this.make).pipe(m.provide(K_.layerPostHog),m.provide(ye.layer));static layerDev=m.effect(this)(this.make).pipe(m.provide(K_.layerDev),m.provide(ye.layer))};const J_=e=>{let t=s.squash(e);return{error_tag:v.hasProperty(t,`_tag`)?String(t._tag):`Unknown`,error_message:s.pretty(e)}};(class extends C.Service()(`@expect/ErrorHandler`,{make:u.gen(function*(){let e=yield*q_;return{orDie:t=>t.pipe(u.tapCause(t=>e.capture(`error:unexpected`,J_(t))),u.orDie),streamOrDie:t=>t.pipe(w.tapCause(t=>e.capture(`error:unexpected`,J_(t))),w.orDie),tapCause:(...t)=>n=>n.pipe(u.tapCause(n=>u.all([e.capture(`error:expected`,J_(n)),u.logError(...t,n)],{discard:!0})))}})}){static layer=m.effect(this)(this.make)}),Xe.layerWebSocket().pipe(m.provide(Ne.layerWebSocketConstructor));const Y_=m.unwrap(u.gen(function*(){let e=`expect-cli`;return Ze.layerJson({baseUrl:`https://api.axiom.co`,resource:{serviceName:e},headers:{Authorization:`Bearer xaat-a6ce2fdb-d378-444e-9d72-bb458867187a`,"X-Axiom-Dataset":e}})})).pipe(m.provide(Me.layerUndici),m.orDie),X_=Be()($e(e=>({agentBackend:`claude`,browserHeaded:!1,replayHost:`https://expect.dev`,autoSaveFlows:!0,notifications:void 0,instructionHistory:[],setAgentBackend:t=>e({agentBackend:t}),toggleAutoSave:()=>e(e=>({autoSaveFlows:!e.autoSaveFlows})),toggleNotifications:()=>e(e=>({notifications:e.notifications!==!0})),rememberInstruction:t=>{t&&e(e=>({instructionHistory:[t,...e.instructionHistory.filter(e=>e!==t)].slice(0,20)}))}}),{name:`prompt-history`,storage:Qe(()=>hm),partialize:e=>({instructionHistory:e.instructionHistory,notifications:e.notifications})})),Z_=q_.layerPostHog,Q_=(e,...[t])=>u.runPromise(u.gen(function*(){let n=yield*q_;yield*n.capture.call(n,e,...t===void 0?[]:[t])}).pipe(u.catchCause(()=>u.void),u.provide(Z_))),$_=()=>Q_(`session:started`,{mode:`interactive`,skip_planning:!1,browser_headed:X_.getState().browserHeaded}),ev=e=>u.runPromise(u.gen(function*(){let t=yield*q_;yield*t.capture(`session:ended`,{session_ms:Date.now()-e}),yield*t.flush}).pipe(u.provide(Z_))),tv=()=>{let e=re(15);if(e[0]!==`d0800512c2dc78a7eda82a0b9a76ade6e9bb7fa0b8809da478275b21ba8ce62d`){for(let t=0;t<15;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`d0800512c2dc78a7eda82a0b9a76ade6e9bb7fa0b8809da478275b21ba8ce62d`}let t=Nt(),n;e[1]===t.RED?n=e[2]:(n=H(O,{color:t.RED,children:W.cross}),e[1]=t.RED,e[2]=n);let r;e[3]===t.GREEN?r=e[4]:(r=H(O,{color:t.GREEN,children:W.tick}),e[3]=t.GREEN,e[4]=r);let i;e[5]===t.PRIMARY?i=e[6]:(i=H(O,{bold:!0,color:t.PRIMARY,children:` Expect`}),e[5]=t.PRIMARY,e[6]=i);let a;e[7]===t.DIM?a=e[8]:(a=H(O,{color:t.DIM,children:` v${ht}`}),e[7]=t.DIM,e[8]=a);let o;return e[9]!==t.BORDER||e[10]!==n||e[11]!==r||e[12]!==i||e[13]!==a?(o=H(E,{children:U(O,{color:t.BORDER,children:[n,r,i,a]})}),e[9]=t.BORDER,e[10]=n,e[11]=r,e[12]=i,e[13]=a,e[14]=o):o=e[14],o},nv=[{id:`enable-sync`,label:`Use existing cookies`,detail:`Recommended. Uses your browser session as-is.`},{id:`run-without-sync`,label:`Skip cookies`,detail:`Not recommended. Tests requiring login will fail.`}],rv=e=>{let t=re(34);if(t[0]!==`e3c7abb53538ed236081ea9ec92e2272ee1c8b466fbb62e1c8ec442744cd59e3`){for(let e=0;e<34;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e3c7abb53538ed236081ea9ec92e2272ee1c8b466fbb62e1c8ec442744cd59e3`}let{changesFor:n,instruction:r,savedFlow:i}=e,a=Nt(),o=Xm(iv),[s,c]=R(0),l;t[1]!==n||t[2]!==r||t[3]!==i||t[4]!==o?(l=e=>{let t=e.id===`enable-sync`;Q_(`cookies:sync_choice`,{choice:t?`use_cookies`:`skip_cookies`}),o(Ym({changesFor:n,instruction:r,savedFlow:i,requiresCookies:t}))},t[1]=n,t[2]=r,t[3]=i,t[4]=o,t[5]=l):l=t[5];let u=l,d;t[6]!==u||t[7]!==s?(d=(e,t)=>{(t.downArrow||e===`j`||t.ctrl&&e===`n`)&&c(av),(t.upArrow||e===`k`||t.ctrl&&e===`p`)&&c(ov),e===`c`&&u(nv[0]),e===`a`&&u(nv[1]),t.return&&u(nv[s])},t[6]=u,t[7]=s,t[8]=d):d=t[8],te(d);let f;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(f=H(tv,{}),t[9]=f):f=t[9];let p;t[10]===a.DIM?p=t[11]:(p=H(O,{color:a.DIM,children:W.pointerSmall}),t[10]=a.DIM,t[11]=p);let m;t[12]!==a.TEXT||t[13]!==r?(m=H(O,{color:a.TEXT,children:r}),t[12]=a.TEXT,t[13]=r,t[14]=m):m=t[14];let h;t[15]!==p||t[16]!==m?(h=U(E,{children:[f,U(O,{wrap:`truncate`,children:[` `,p,` `,m]})]}),t[15]=p,t[16]=m,t[17]=h):h=t[17];let g;t[18]!==a.GREEN||t[19]!==a.YELLOW||t[20]!==s?(g=H(E,{marginTop:1,children:s===0?U(O,{color:a.GREEN,children:[W.tick,` Your signed-in session will be synced to the browser. Cookies stay on device.`]}):U(O,{color:a.YELLOW,children:[W.warning,` The browser won`,`'`,`t inherit your signed-in session without cookies.`]})}),t[18]=a.GREEN,t[19]=a.YELLOW,t[20]=s,t[21]=g):g=t[21];let _;t[22]!==a.DIM||t[23]!==a.PRIMARY||t[24]!==a.TEXT||t[25]!==u||t[26]!==s?(_=nv.map((e,t)=>{let n=t===s;return H(It,{onClick:()=>{c(t),u(e)},children:U(E,{flexDirection:`column`,marginBottom:1,children:[U(O,{children:[H(O,{color:n?a.PRIMARY:a.DIM,children:n?`${W.pointer} `:` `}),H(O,{color:n?a.PRIMARY:a.TEXT,bold:n,children:e.label})]}),U(O,{color:a.DIM,children:[` `,e.detail]})]})},e.id)}),t[22]=a.DIM,t[23]=a.PRIMARY,t[24]=a.TEXT,t[25]=u,t[26]=s,t[27]=_):_=t[27];let v;t[28]===_?v=t[29]:(v=H(E,{flexDirection:`column`,marginTop:1,children:_}),t[28]=_,t[29]=v);let y;return t[30]!==h||t[31]!==g||t[32]!==v?(y=U(E,{flexDirection:`column`,width:`100%`,paddingY:1,paddingX:1,children:[h,g,v]}),t[30]=h,t[31]=g,t[32]=v,t[33]=y):y=t[33],y};function iv(e){return e.setScreen}function av(e){return Math.min(nv.length-1,e+1)}function ov(e){return Math.max(0,e-1)}const sv=Be()($e(e=>({cookiesEnabled:!1,setCookiesEnabled:t=>e({cookiesEnabled:t}),toggleCookies:()=>e(e=>({cookiesEnabled:!e.cookiesEnabled})),lastBaseUrl:void 0,setLastBaseUrl:t=>e({lastBaseUrl:t})}),{name:`project-preferences`,storage:Qe(()=>vm)})),cv=`spotify,raycast,google,controlce,controlcenter,cursor,electron,slack,discord,figma,redis,postgres,mysqld,mongod,mongos,memcached,dockerd,containerd,com.docke,docker,code,rapportd,wifiagent,airplayxpc,identitys,sharingd,bluetoothd,screencap,loginwind,systempol,corespeec,apsd,mds_store,spotlight,lsd`.split(`,`),lv=[[/next[\\/]dist[\\/]/,`next`],[/next-server/,`next`],[/vite[\\/]/,`vite`],[/vite-plus[\\/]/,`vite`],[/react-scripts[\\/]/,`react-scripts`],[/angular[\\/]cli[\\/]/,`angular`],[/remix[\\/]/,`remix`],[/astro[\\/]/,`astro`],[/nuxt[\\/]/,`nuxt`],[/svelte[\\/]/,`svelte`],[/webpack[\\/]/,`webpack`],[/webpack-dev-server/,`webpack`],[/turbopack[\\/]/,`turbopack`],[/remotion[\\/]/,`remotion`],[/gatsby[\\/]/,`gatsby`],[/parcel[\\/]/,`parcel`],[/http-server/,`http-server`],[/live-server/,`live-server`],[/serve[\\/]/,`serve`],[/express[\\/]/,`express`],[/fastify[\\/]/,`fastify`],[/hono[\\/]/,`hono`],[/elysia[\\/]/,`elysia`]],uv=e=>{let t=e.toLowerCase();return cv.some(e=>t.startsWith(e))},dv=e=>{if(!/^\d+$/.test(e))return``;try{let t=Ee(`lsof -p ${e} -a -d cwd -Fn`,{encoding:`utf-8`,timeout:1e3}).split(`
36
- `).find(e=>e.startsWith(`n`));return t?t.slice(1):``}catch{return``}},fv=(e,t)=>{if(!/^\d+$/.test(e)||uv(t))return;let n=dv(e);try{let t=Ee(`ps -p ${e} -o command=`,{encoding:`utf-8`,timeout:1e3}).trim();for(let[e,r]of lv)if(e.test(t))return{name:r,isFramework:!0,cwd:n}}catch{}return{name:t,isFramework:!1,cwd:n}},pv=e=>{let t=new Set,n=[];for(let r of e.split(`
37
- `)){let e=r.trim().split(/\s+/);if(e.length<9)continue;let i=e[0]??``,a=e[1]??``,o=(e[8]??``).match(/:(\d+)$/);if(!o)continue;let s=Number(o[1]);s<1024||s>65535||t.has(s)||(t.add(s),n.push({port:s,pid:a,commandName:i}))}return n},mv=()=>{try{let e=pv(Ee(`lsof -iTCP -sTCP:LISTEN -nP`,{encoding:`utf-8`,timeout:3e3})),t=[];for(let n of e){let e=fv(n.pid,n.commandName);e!==void 0&&(n.port>=32768&&!e.isFramework||t.push({port:n.port,processName:e.name,cwd:e.cwd}))}return t.sort((e,t)=>e.port-t.port)}catch{return[]}},hv=()=>P({queryKey:[`listening-ports`],queryFn:()=>mv(),refetchInterval:5e3}),gv=e=>`http://localhost:${e}`,_v=(e,t)=>{let n=t.toLowerCase();return String(e.port).includes(n)||e.processName.toLowerCase().includes(n)||e.cwd.toLowerCase().includes(n)},vv=e=>{let t=e.trim(),n=Number(t);if(Number.isInteger(n)&&n>=1&&n<=65535)return n;let r=t.match(/:(\d+)\/?$/);if(r){let e=Number(r[1]);if(Number.isInteger(e)&&e>=1&&e<=65535)return e}},yv=e=>{let t=re(178);if(t[0]!==`84a93f0b7994a0f9318ab42167dadcad0ffba85a300830ca86b74045fc7574ce`){for(let e=0;e<178;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`84a93f0b7994a0f9318ab42167dadcad0ffba85a300830ca86b74045fc7574ce`}let{changesFor:n,instruction:r,savedFlow:i,requiresCookies:a}=e,o=Nt(),s=Xm(bv),c=sv(xv),l=sv(Sv),{data:u}=hv(),d=u===void 0?[]:u,[f,p]=R(!1),[m,h]=R(``),[g,_]=R(!1),[v,y]=R(``),b;t[1]===c?b=t[2]:(b=()=>{if(!c)return new Set;let e=c.match(/:(\d+)/);return e?new Set([Number(e[1])]):new Set},t[1]=c,t[2]=b);let[x,S]=R(b),C;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(C=new Set,t[3]=C):C=t[3];let[w,ee]=R(C),T=d.map(Cv),D=m?T.filter(e=>_v(e,m)):T,k=D.length,A=D.length+1,ne=D.length+2,j;t[4]===ne?j=t[5]:(j={itemCount:ne,visibleCount:10},t[4]=ne,t[5]=j);let{highlightedIndex:M,setHighlightedIndex:N,scrollOffset:P,handleNavigation:ie}=Gm(j),ae;t[6]!==n||t[7]!==w||t[8]!==r||t[9]!==a||t[10]!==i||t[11]!==l||t[12]!==s?(ae=e=>{let t=[...e,...w];l(t.length>0?t[0]:void 0),t.length===0?Q_(`port:skipped`):Q_(`port:selected`,{port_count:t.length,has_custom_url:w.size>0}),s(Jm.Testing({changesFor:n,instruction:r,savedFlow:i,requiresCookies:a,baseUrls:t.length>0?t:void 0}))},t[6]=n,t[7]=w,t[8]=r,t[9]=a,t[10]=i,t[11]=l,t[12]=s,t[13]=ae):ae=t[13];let F=ae,oe;t[14]===S?oe=t[15]:(oe=e=>{S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},t[14]=S,t[15]=oe);let I=oe,L;t[16]!==k||t[17]!==w||t[18]!==D||t[19]!==M||t[20]!==F||t[21]!==x||t[22]!==_||t[23]!==A?(L=()=>{if(M===A){F([]);return}if(x.size>0||w.size>0){F([...x].sort(wv).map(gv));return}if(M===k){_(!0);return}let e=D[M];e&&F([gv(e.port)])},t[16]=k,t[17]=w,t[18]=D,t[19]=M,t[20]=F,t[21]=x,t[22]=_,t[23]=A,t[24]=L):L=t[24];let z=L,B=Tv,se;t[25]!==y||t[26]!==ee||t[27]!==_?(se=e=>{let t=e.trim();if(!t){_(!1);return}let n=B(t);ee(e=>new Set([...e,n])),y(``),_(!1)},t[25]=y,t[26]=ee,t[27]=_,t[28]=se):se=t[28];let ce=se,V;t[29]===ee?V=t[30]:(V=e=>{ee(t=>{let n=new Set(t);return n.delete(e),n})},t[29]=ee,t[30]=V);let le=V,G;t[31]!==N||t[32]!==h?(G=e=>{h(e),N(0)},t[31]=N,t[32]=h,t[33]=G):G=t[33];let K=G,ue;t[34]!==p||t[35]!==h||t[36]!==I?(ue=e=>{let t=vv(e);if(t){I(t),p(!1),h(``);return}p(!1)},t[34]=p,t[35]=h,t[36]=I,t[37]=ue):ue=t[37];let de=ue,fe;t[38]!==z||t[39]!==k||t[40]!==D||t[41]!==ie||t[42]!==M||t[43]!==g||t[44]!==f||t[45]!==y||t[46]!==_||t[47]!==p||t[48]!==I?(fe=(e,t)=>{if(g){if(t.escape){_(!1),y(``);return}return}if(f){if(t.escape){p(!1);return}return}if(!ie(e,t)){if(e===`/`){p(!0);return}if(e===` `){if(M===k){_(!0);return}let e=D[M];e&&I(e.port);return}t.return&&z()}},t[38]=z,t[39]=k,t[40]=D,t[41]=ie,t[42]=M,t[43]=g,t[44]=f,t[45]=y,t[46]=_,t[47]=p,t[48]=I,t[49]=fe):fe=t[49],te(fe);let pe,me,he,ge,q,_e,ve,ye,be,xe,Se,Ce,we,Te,Ee,De;if(t[50]!==o.DIM||t[51]!==o.GREEN||t[52]!==o.PRIMARY||t[53]!==o.TEXT||t[54]!==o.YELLOW||t[55]!==k||t[56]!==w||t[57]!==D||t[58]!==M||t[59]!==r||t[60]!==P||t[61]!==x||t[62]!==N||t[63]!==A||t[64]!==I){let e=D.slice(P,P+8);he=P+8>=D.length,_e=he;let n=D[M];ge=M===k,q=M===A;let i;t[81]!==w||t[82]!==x?(i=[...[...x].sort(Ev).map(gv),...w],t[81]=w,t[82]=x,t[83]=i):i=t[83];let a=i;me=E,xe=`column`,Se=`100%`,Ce=1,we=1;let s;t[84]===Symbol.for(`react.memo_cache_sentinel`)?(s=H(tv,{}),t[84]=s):s=t[84];let c;t[85]===o.DIM?c=t[86]:(c=H(O,{color:o.DIM,children:W.pointerSmall}),t[85]=o.DIM,t[86]=c);let l;t[87]!==o.TEXT||t[88]!==r?(l=H(O,{color:o.TEXT,children:r}),t[87]=o.TEXT,t[88]=r,t[89]=l):l=t[89],t[90]!==c||t[91]!==l?(Te=U(E,{children:[s,U(O,{wrap:`truncate`,children:[` `,c,` `,l]})]}),t[90]=c,t[91]=l,t[92]=Te):Te=t[92],t[93]===o.DIM?Ee=t[94]:(Ee=H(E,{marginTop:1,children:H(O,{color:o.DIM,children:`Pick the dev server the agent should open in the browser.`})}),t[93]=o.DIM,t[94]=Ee);let u;t[95]!==o.GREEN||t[96]!==a?(u=a.length>0&&U(O,{color:o.GREEN,children:[W.tick,` `,a.join(`, `)]}),t[95]=o.GREEN,t[96]=a,t[97]=u):u=t[97];let d;t[98]!==o.DIM||t[99]!==a.length||t[100]!==n||t[101]!==ge||t[102]!==q?(d=a.length===0&&!q&&!ge&&n&&U(O,{color:o.DIM,children:[W.arrowRight,` `,gv(n.port)]}),t[98]=o.DIM,t[99]=a.length,t[100]=n,t[101]=ge,t[102]=q,t[103]=d):d=t[103];let f;t[104]!==o.YELLOW||t[105]!==a.length||t[106]!==q?(f=a.length===0&&q&&U(O,{color:o.YELLOW,children:[W.warning,` No base URL. The agent won`,`'`,`t know where your dev server is.`]}),t[104]=o.YELLOW,t[105]=a.length,t[106]=q,t[107]=f):f=t[107],t[108]!==u||t[109]!==d||t[110]!==f?(De=U(E,{marginTop:1,children:[u,d,f]}),t[108]=u,t[109]=d,t[110]=f,t[111]=De):De=t[111],pe=E,ve=`column`,ye=1;let p;t[112]!==o.DIM||t[113]!==o.PRIMARY||t[114]!==o.TEXT||t[115]!==M||t[116]!==P||t[117]!==x||t[118]!==N||t[119]!==I?(p=(e,t)=>{let n=t+P,r=n===M,i=x.has(e.port);return H(It,{onClick:()=>{N(n),I(e.port)},children:U(E,{children:[H(O,{color:r?o.PRIMARY:o.DIM,children:r?`${W.pointer} `:` `}),U(O,{color:i?o.PRIMARY:o.DIM,children:[i?W.checkboxOn:W.checkboxOff,` `]}),U(O,{color:r?o.PRIMARY:o.TEXT,bold:r,children:[`:`,e.port]}),e.processName&&U(O,{color:o.DIM,children:[` `,e.processName]}),e.cwd&&U(O,{color:o.DIM,children:[` `,e.cwd]})]})},e.port)},t[112]=o.DIM,t[113]=o.PRIMARY,t[114]=o.TEXT,t[115]=M,t[116]=P,t[117]=x,t[118]=N,t[119]=I,t[120]=p):p=t[120],be=e.map(p),t[50]=o.DIM,t[51]=o.GREEN,t[52]=o.PRIMARY,t[53]=o.TEXT,t[54]=o.YELLOW,t[55]=k,t[56]=w,t[57]=D,t[58]=M,t[59]=r,t[60]=P,t[61]=x,t[62]=N,t[63]=A,t[64]=I,t[65]=pe,t[66]=me,t[67]=he,t[68]=ge,t[69]=q,t[70]=_e,t[71]=ve,t[72]=ye,t[73]=be,t[74]=xe,t[75]=Se,t[76]=Ce,t[77]=we,t[78]=Te,t[79]=Ee,t[80]=De}else pe=t[65],me=t[66],he=t[67],ge=t[68],q=t[69],_e=t[70],ve=t[71],ye=t[72],be=t[73],xe=t[74],Se=t[75],Ce=t[76],we=t[77],Te=t[78],Ee=t[79],De=t[80];let Oe;t[121]!==o.DIM||t[122]!==o.PRIMARY||t[123]!==o.TEXT||t[124]!==k||t[125]!==v||t[126]!==he||t[127]!==ce||t[128]!==ge||t[129]!==g||t[130]!==y||t[131]!==N||t[132]!==_?(Oe=he&&H(It,{onClick:()=>{N(k),_(!0)},children:U(E,{children:[H(O,{color:ge?o.PRIMARY:o.DIM,children:ge?`${W.pointer} `:` `}),g&&U(E,{children:[H(O,{color:o.PRIMARY,children:`URL: `}),H(Ht,{focus:!0,value:v,placeholder:`http://localhost:4000 or staging.example.com`,onChange:y,onSubmit:ce})]}),!g&&U(O,{color:ge?o.PRIMARY:o.TEXT,bold:ge,children:[`Enter a custom URL`,W.ellipsis]})]})}),t[121]=o.DIM,t[122]=o.PRIMARY,t[123]=o.TEXT,t[124]=k,t[125]=v,t[126]=he,t[127]=ce,t[128]=ge,t[129]=g,t[130]=y,t[131]=N,t[132]=_,t[133]=Oe):Oe=t[133];let ke;t[134]!==o.DIM||t[135]!==o.PRIMARY||t[136]!==o.TEXT||t[137]!==he||t[138]!==w||t[139]!==le?(ke=he&&[...w].map(e=>H(It,{onClick:()=>le(e),children:U(E,{children:[H(O,{children:` `}),U(O,{color:o.PRIMARY,children:[W.checkboxOn,` `]}),H(O,{color:o.TEXT,children:e}),H(O,{color:o.DIM,children:` (click to remove)`})]})},e)),t[134]=o.DIM,t[135]=o.PRIMARY,t[136]=o.TEXT,t[137]=he,t[138]=w,t[139]=le,t[140]=ke):ke=t[140];let Ae;t[141]!==o.DIM||t[142]!==o.PRIMARY||t[143]!==q||t[144]!==F||t[145]!==N||t[146]!==A||t[147]!==_e?(Ae=_e&&H(It,{onClick:()=>{N(A),F([])},children:U(E,{children:[H(O,{color:q?o.PRIMARY:o.DIM,children:q?`${W.pointer} `:` `}),U(O,{color:q?o.PRIMARY:o.DIM,bold:q,children:[`Skip `,W.arrowRight,` no base URL`]})]})}),t[141]=o.DIM,t[142]=o.PRIMARY,t[143]=q,t[144]=F,t[145]=N,t[146]=A,t[147]=_e,t[148]=Ae):Ae=t[148];let je;t[149]!==o.DIM||t[150]!==D.length||t[151]!==_e?(je=D.length===0&&!_e&&H(O,{color:o.DIM,children:`No matching ports`}),t[149]=o.DIM,t[150]=D.length,t[151]=_e,t[152]=je):je=t[152];let Me;t[153]!==pe||t[154]!==ve||t[155]!==ye||t[156]!==be||t[157]!==Oe||t[158]!==ke||t[159]!==Ae||t[160]!==je?(Me=U(pe,{flexDirection:ve,marginTop:ye,children:[be,Oe,ke,Ae,je]}),t[153]=pe,t[154]=ve,t[155]=ye,t[156]=be,t[157]=Oe,t[158]=ke,t[159]=Ae,t[160]=je,t[161]=Me):Me=t[161];let Ne;t[162]!==K||t[163]!==de||t[164]!==f||t[165]!==m?(Ne=H(Ut,{isSearching:f,query:m,onChange:K,onSubmit:de}),t[162]=K,t[163]=de,t[164]=f,t[165]=m,t[166]=Ne):Ne=t[166];let Pe;return t[167]!==me||t[168]!==xe||t[169]!==Se||t[170]!==Ce||t[171]!==we||t[172]!==Te||t[173]!==Ee||t[174]!==De||t[175]!==Me||t[176]!==Ne?(Pe=U(me,{flexDirection:xe,width:Se,paddingY:Ce,paddingX:we,children:[Te,Ee,De,Me,Ne]}),t[167]=me,t[168]=xe,t[169]=Se,t[170]=Ce,t[171]=we,t[172]=Te,t[173]=Ee,t[174]=De,t[175]=Me,t[176]=Ne,t[177]=Pe):Pe=t[177],Pe};function bv(e){return e.setScreen}function xv(e){return e.lastBaseUrl}function Sv(e){return e.setLastBaseUrl}function Cv(e){return{port:e.port,processName:e.processName,cwd:e.cwd}}function wv(e,t){return e-t}function Tv(e){let t=e.trim(),n=Number(t);return Number.isInteger(n)&&n>=1&&n<=65535?gv(n):/^https?:\/\//i.test(t)?t:`http://${t}`}function Ev(e,t){return e-t}const Dv=e=>{let t=e.replace(`#`,``);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Ov=(e,t,n)=>`#${[e,t,n].map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`,kv=(e,t,n)=>e+(t-e)*n,Av=(e,t,n)=>{let[r,i,a]=Dv(e),[o,s,c]=Dv(t);return Ov(kv(r,o,n),kv(i,s,n),kv(a,c,n))},jv=({text:e,baseColor:t,highlightColor:n,speed:r=1})=>{let[i,a]=R(-16),o=L(r);o.current=r;let s=L(e.length);s.current=e.length;let c=L(!1);return c.current||(c.current=!0,setTimeout(()=>{setInterval(()=>{let e=s.current+16;a(t=>t>=e?-16:t+o.current)},50)},0)),H(O,{children:[...e].map((e,r)=>{let a=Math.abs(r-i),o=Math.max(0,1-a/16);return H(O,{color:o>0?Av(t,n,o):t,children:e},r)})})},Mv=Be(e=>({executedPlan:void 0,expanded:!1,setExecutedPlan:t=>e({executedPlan:t}),setExpanded:t=>e({expanded:t}),toggleExpanded:()=>e(e=>({expanded:!e.expanded}))})),Nv=e=>ot(Math.max(0,e),{secondsDecimalDigits:0}),Pv=new Set([`warpterminal`]),Fv=ct.stdout,Iv=st({preferOuter:!0}),Lv=process.stdout.isTTY&&!Pv.has(Iv??``),Rv=Lv&&Fv.kitty,zv=Lv&&Fv.iterm2,Bv=Rv||zv,Vv=st(),Hv=Vv===`tmux`||Vv===`screen`,Uv=e=>Hv?`Ptmux;${e.replaceAll(`\x1B`,`\x1B\x1B`)}\\`:e,Wv=(e,t)=>{let n=Buffer.from(e).toString(`base64`),r=`a=T,t=f`;return t.width&&(r+=`,c=${t.width}`),t.height&&(r+=`,r=${t.height}`),Uv(`_G${r};${n}\\`)},Gv=(e,t)=>{let n=`\x1B]1337;File=inline=1`;return t.width&&(n+=`;width=${t.width}`),t.height&&(n+=`;height=${t.height}`),n+=`;size=${e.byteLength}:${e.toString(`base64`)}`,Uv(n)},Kv=(e,t={})=>{if(!Ke.existsSync(e))return null;if(Rv)return Wv(e,t);if(zv)try{return Gv(Ke.readFileSync(e),t)}catch{return null}return null},qv=e=>e.startsWith(`file://`),Jv=e=>{let t=re(9);if(t[0]!==`edb58922a19f7cd34125950b48961a70defca0454a8de685a54dc50281109929`){for(let e=0;e<9;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`edb58922a19f7cd34125950b48961a70defca0454a8de685a54dc50281109929`}let{path:n,label:r}=e,i,a;t[1]===n?(i=t[2],a=t[3]):(i=qv(n)?pe.fileURLToPath(n):K.resolve(n),a=qv(n)?n:pe.pathToFileURL(i).href,t[1]=n,t[2]=i,t[3]=a);let o=a,s=r??i,c;t[4]===s?c=t[5]:(c=H(O,{children:s}),t[4]=s,t[5]=c);let l;return t[6]!==o||t[7]!==c?(l=H(lt,{url:o,children:c}),t[6]=o,t[7]=c,t[8]=l):l=t[8],l},Yv=({src:e,alt:t,width:n,height:r})=>{let i=K.resolve(e),{write:a}=ne(),o=L(!1);if(!o.current){let e=Kv(i,{width:n,height:r});e&&(a(e+`
38
- `),o.current=!0)}return Bv?null:H(Jv,{path:i,label:t})},Xv=({error:e,type:t})=>{if(!e.message)return null;let n=Nt(),r=t===`defect`;return U(E,{paddingX:1,paddingY:1,marginBottom:1,backgroundColor:n.ERROR_BG,width:`100%`,flexDirection:`column`,gap:0,children:[H(E,{paddingBottom:1,children:U(O,{color:n.RED,bold:!0,children:[W.warning,` `,e.displayName??e._tag]})}),H(E,{paddingBottom:1,children:H(O,{color:n.DIM,children:e.message})}),r&&U(O,{color:n.DIM,children:[`This is a bug. Report it at`,` `,H(O,{color:n.YELLOW,children:`https://github.com/millionco/expect/issues`})]}),U(O,{color:n.DIM,children:[`Press `,H(O,{color:n.RED,children:`esc`}),` to return`]})]})},Zv=e=>{let t=re(4);if(t[0]!==`075a231297c9d0f078b6eb696b743c17a186b30f3122dd20bf9f0b0544337fab`){for(let e=0;e<4;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`075a231297c9d0f078b6eb696b743c17a186b30f3122dd20bf9f0b0544337fab`}let{message:n}=e,r=Nt();if(!n)return null;let i;return t[1]!==r.RED||t[2]!==n?(i=H(E,{marginTop:1,children:H(O,{color:r.RED,children:n})}),t[1]=r.RED,t[2]=n,t[3]=i):i=t[3],i},Qv=({verbose:e,agent:t})=>{let n=Yp.withRepoRoot(process.cwd());return m.mergeAll(Zp.layer.pipe(m.provide(n)),Qp.layer,$n.layer,lm.layer,Xe.layer(),n,q_.layerPostHog).pipe(m.provide(Wa.layerFor(t??`claude`)),m.provide(ih),m.provide(Y_),m.provideMerge(m.succeed(x.MinimumLogLevel,e?`All`:`Error`)))},$v=tt.make(_.none()),ey=tt.runtime(u.fnUntraced(function*(e){return Qv({verbose:!0,agent:yield*e.some($v)})},m.unwrap)).pipe(tt.keepAlive),ty=e=>e;var ny=class extends S.ErrorClass(`ReplayProxyStartError`)({_tag:S.tag(`ReplayProxyStartError`),cause:S.String}){message=`Failed to start replay proxy: ${this.cause}`};const ry=(e,t,n,r)=>{let i=new URL(e.url??`/`,r),a=Fe({hostname:i.hostname,port:i.port,path:i.pathname+i.search,method:`GET`,headers:{...e.headers,host:i.host}});a.on(`upgrade`,(e,r,i)=>{t.write([`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${e.headers[`sec-websocket-accept`]}`,``,``].join(`\r
39
- `)),i.length>0&&t.write(i),n.length>0&&r.write(n),r.pipe(t),t.pipe(r),t.on(`error`,()=>r.destroy()),r.on(`error`,()=>t.destroy())}),a.on(`error`,()=>t.destroy()),a.end()},iy=u.fn(`startReplayProxy`)(function*(e){let t=new ut,n=[],r={title:``,status:`running`,steps:[]},i=!1,a=()=>{let e=r?.status;(e===`passed`||e===`failed`)&&(i=!0,r={...r,done:!0})};t.get(`/latest.json`,async t=>{if(i)return t.json(n);try{let r=await fetch(`${e.liveViewUrl}/latest.json`);if(!r.ok)return t.json(n);let i=await r.json();return Array.isArray(i)&&i.length>0&&(n=i),t.json(i)}catch{return t.json(n)}}),t.post(`/latest.json`,async e=>{try{let t=await e.req.json();return Array.isArray(t)&&(n=t),new Response(void 0,{status:204})}catch{return new Response(void 0,{status:400})}}),t.get(`/steps`,async t=>{if(i)return t.json(r);try{let n=await fetch(`${e.liveViewUrl}/steps`);return n.ok?(r=await n.json(),a(),t.json(r)):t.json(r)}catch{return t.json(r)}}),t.post(`/steps`,async t=>{try{let n=await t.req.text();r=JSON.parse(n),a();let i=await fetch(`${e.liveViewUrl}/steps`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n});return new Response(i.body,{status:i.status,headers:Object.fromEntries(i.headers.entries())})}catch{return new Response(void 0,{status:204})}});let o=/^https?:\/\//.test(e.replayHost)?e.replayHost:`http://${e.replayHost}`,s=new URL(o);t.all(`/*`,async e=>{let t=e.req.path;if(t===`/latest.json`||t===`/steps`)return e.text(`Not Found`,404);let n=new URL(t,o);n.search=new URL(e.req.url).search;try{return await dt(n.toString(),{headers:{"User-Agent":e.req.header(`user-agent`)??``,Accept:e.req.header(`accept`)??`*/*`,Host:s.host}})}catch(r){return console.error(`[replay-proxy] Failed to proxy ${t} to ${n}:`,r),e.text(`Bad Gateway: could not reach ${s.host}`,502)}}),t.onError((e,t)=>(console.error(`[replay-proxy] Unhandled error:`,e),t.text(`Internal Server Error`,500)));let c=yield*u.try({try:()=>ft({fetch:t.fetch,port:0}),catch:e=>new ny({cause:String(e)})});c.on(`upgrade`,(e,t,n)=>{ry(e,t,n,o)});let l=c.address(),d=`http://localhost:${typeof l==`object`&&l?l.port:0}`;return yield*u.logInfo(`Replay proxy started`,{proxyUrl:d,liveViewUrl:e.liveViewUrl}),{url:d,close:u.callback(e=>{c.close(()=>e(u.void))})}}),ay=e=>_.isSome(e)?Number(l.toEpochMillis(e.value)):void 0,oy=e=>e.length===0||!e.every(e=>e.status===`passed`||e.status===`failed`)?`running`:e.some(e=>e.status===`failed`)?`failed`:`passed`,sy=e=>{let t=e.events.find(e=>e._tag===`RunFinished`),n=t&&t._tag===`RunFinished`?t.status:oy(e.steps),r=t&&t._tag===`RunFinished`?t.summary:void 0,i=e.steps.map(e=>({stepId:e.id,title:e.title,status:e.status,summary:_.isSome(e.summary)?e.summary.value:void 0,startedAtMs:ay(e.startedAt),endedAtMs:ay(e.endedAt)}));return{title:e.title,status:n,summary:r,steps:i}},cy=u.fn(`pushStepState`)(function*(e,t){yield*u.tryPromise(()=>fetch(`${e}/steps`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).pipe(u.catchCause(()=>u.void))}),ly=`rrweb report:`,uy=`Playwright video:`,dy=()=>5e4+Math.floor(Math.random()*1e4),fy=e=>{let t=e.slice().reverse().find(e=>e._tag===`ToolResult`&&e.toolName===`close`&&!e.isError&&e.result.length>0);if(!t||t._tag!==`ToolResult`)return{localReplayUrl:void 0,videoUrl:void 0};let n=t.result.split(`
40
- `).map(e=>e.trim()).filter(e=>e.length>0),r=n.find(e=>e.startsWith(ly))?.replace(ly,``),i=n.find(e=>e.startsWith(uy))?.replace(uy,``);return{localReplayUrl:r&&r.trim().length>0?he(r.trim()).href:void 0,videoUrl:i&&i.trim().length>0?he(i.trim()).href:void 0}},py=tt.make([]),my=u.fnUntraced(function*(e,t){let n=yield*Qp,r=yield*Zp,i=yield*q_,a=yield*Yp,o=Date.now(),s=`http://localhost:${dy()}`,c;e.replayHost&&(c=`${(yield*iy({replayHost:e.replayHost,liveViewUrl:s})).url}/replay?live=true`,yield*u.logInfo(`Replay viewer available`,{replayUrl:c}),yield*u.sync(()=>e.onReplayUrl?.(c)));let l={...e.options,liveViewUrl:s};yield*i.capture(`run:started`,{plan_id:`direct`});let d=yield*r.execute(l).pipe(w.tap(t=>u.gen(function*(){e.onUpdate(t),yield*cy(s,sy(t))})),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Zn({...e.options,id:``,changesFor:e.options.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.options.instruction,baseUrl:void 0,isHeadless:e.options.isHeadless,requiresCookies:e.options.requiresCookies,testCoverage:_.none(),title:e.options.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock())),f=fy(d.events);if(c){let e=c.split(`/replay`)[0];yield*u.tryPromise(()=>fetch(`${s}/latest.json`).then(async t=>{if(!t.ok)return;let n=await t.json();await fetch(`${e}/latest.json`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})})).pipe(u.catchCause(()=>u.void)),yield*cy(e,sy(d))}let p=yield*n.report(d),m=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`passed`).length,h=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`failed`).length;return yield*i.capture(`run:completed`,{plan_id:d.id??`direct`,passed:m,failed:h,step_count:d.steps.length,file_count:0,duration_ms:Date.now()-o}),p.status===`passed`&&(yield*a.saveTestedFingerprint()),{executedPlan:d,report:p,replayUrl:c??f.localReplayUrl,localReplayUrl:f.localReplayUrl,videoUrl:f.videoUrl}},u.annotateLogs({fn:`executeFn`})),hy=ey.fn()((e,t)=>ty(my(e,t)).pipe(u.tapError(e=>u.gen(function*(){let t=yield*q_,n=e instanceof Error?e.constructor.name:`UnknownError`;yield*t.capture(`run:failed`,{plan_id:`direct`,error_tag:n})}).pipe(u.catchCause(()=>u.void))),u.provide(ye.layer)));ey.fn(u.fnUntraced(function*(e,t){let n=yield*Qp,r=yield*Zp,i=yield*q_,a=yield*Yp,o=Date.now(),s=`http://localhost:${dy()}`,c;e.replayHost&&(c=`${(yield*iy({replayHost:e.replayHost,liveViewUrl:s})).url}/replay?live=true`,yield*u.logInfo(`Replay viewer available`,{replayUrl:c}),yield*u.sync(()=>e.onReplayUrl?.(c)));let l={...e.options,liveViewUrl:s};yield*i.capture(`run:started`,{plan_id:`direct`});let d=yield*r.execute(l).pipe(w.tap(t=>u.gen(function*(){e.onUpdate(t),yield*cy(s,sy(t))})),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Zn({...e.options,id:``,changesFor:e.options.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.options.instruction,baseUrl:void 0,isHeadless:e.options.isHeadless,requiresCookies:e.options.requiresCookies,testCoverage:_.none(),title:e.options.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock())),f=fy(d.events);if(c){let e=c.split(`/replay`)[0];yield*u.tryPromise(()=>fetch(`${s}/latest.json`).then(async t=>{if(!t.ok)return;let n=await t.json();await fetch(`${e}/latest.json`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})})).pipe(u.catchCause(()=>u.void)),yield*cy(e,sy(d))}let p=yield*n.report(d),m=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`passed`).length,h=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`failed`).length;return yield*i.capture(`run:completed`,{plan_id:d.id??`direct`,passed:m,failed:h,step_count:d.steps.length,file_count:0,duration_ms:Date.now()-o}),p.status===`passed`&&(yield*a.saveTestedFingerprint()),{executedPlan:d,report:p,replayUrl:c??f.localReplayUrl,localReplayUrl:f.localReplayUrl,videoUrl:f.videoUrl}},u.annotateLogs({fn:`executeAtomFn`})));const gy=e=>{if(typeof e==`string`)try{let t=JSON.parse(e);if(v.isObject(t))return t}catch{return{}}return v.isObject(e)?e:{}},_y=e=>e.replace(/\s+/g,` `).trim(),vy=e=>{let t=e.match(/^mcp__.+__(.+)$/);return t?t[1]:e},yy=(e,t)=>{let n=vy(e),r=typeof t==`string`?t:JSON.stringify(t??{}),i=gy(t),a=g.value(n).pipe(g.when(`open`,()=>i.url?`"${i.url}"`:``),g.when(`screenshot`,()=>{let e=i.mode??`screenshot`;return e===`screenshot`?``:e}),g.when(`playwright`,()=>Re(_y(i.code??r),100)),g.when(`console_logs`,()=>i.type?`type: "${i.type}"`:``),g.when(`network_requests`,()=>{let e=[];return i.method&&e.push(i.method),i.url&&e.push(`"${i.url}"`),e.join(`, `)}),g.when(`performance_metrics`,()=>``),g.when(`close`,()=>``),g.orElse(()=>by(i))),o=(i.code??r).trim();return{name:n,args:a,multilineArgs:n===`playwright`&&o.includes(`
41
- `)?o:void 0}},by=e=>{let t=Object.values(e).filter(e=>typeof e==`string`&&e.length>0);return t.length===0?``:Re(_y(t.join(`, `)),100)},xy=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Sy=(e,t,n=e.length)=>{let r=[];for(let i=t;i<n;i++){let t=e[i];if(t._tag===`ToolCall`&&r.push({tool:yy(t.toolName,t.input),isRunning:!1,resultTokens:void 0}),t._tag===`ToolProgress`&&r.length>0){let e=r[r.length-1];r[r.length-1]={...e,resultTokens:Math.round(t.outputSize/4)}}if(t._tag===`ToolResult`&&r.length>0){let e=r[r.length-1];r[r.length-1]={...e,resultTokens:Math.round(t.result.length/4)}}}return r},Cy=(e,t)=>{if(e.length===0)return e;let n=t.at(-1)?._tag===`ToolResult`,r=[...e];return r[r.length-1]={...r[r.length-1],isRunning:!n},r},wy=(e,t=!1)=>{let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t]._tag===`StepStarted`){n=t;break}if(n===-1)return[];let r=Cy(Sy(e,n+1),e);return t?r:r.slice(-5)},Ty=(e,t=!1)=>{let n=Cy(Sy(e,0),e);return t?n:n.slice(-5)},Ey=(e,t)=>{let n=-1,r=0;for(let i=0;i<e.length;i++)if(e[i]._tag===`StepStarted`&&(n++,n===t&&(r=i+1),n===t+1))return[r,i];return[r,e.length]},Dy=(e,t)=>{let[n,r]=Ey(e,t);return Sy(e,n,r)},Oy=e=>{let t=re(15);if(t[0]!==`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`){for(let e=0;e<15;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`}let{display:n,indent:r}=e,i=Nt(),a;t[1]!==i.TEXT||t[2]!==n.tool.name?(a=H(O,{color:i.TEXT,children:n.tool.name}),t[1]=i.TEXT,t[2]=n.tool.name,t[3]=a):a=t[3];let o;t[4]===n.isRunning?o=t[5]:(o=n.isRunning&&U(O,{children:[` `,H(Le,{type:`line`})]}),t[4]=n.isRunning,t[5]=o);let s;t[6]===n.resultTokens?s=t[7]:(s=n.resultTokens!==void 0&&` ${W.arrowDown} ${xy(n.resultTokens)} tokens`,t[6]=n.resultTokens,t[7]=s);let c;return t[8]!==i.DIM||t[9]!==n.tool.args||t[10]!==r||t[11]!==a||t[12]!==o||t[13]!==s?(c=U(O,{color:i.DIM,wrap:`truncate`,children:[r,W.lineVertical,` `,a,`(`,n.tool.args,`)`,o,s]}),t[8]=i.DIM,t[9]=n.tool.args,t[10]=r,t[11]=a,t[12]=o,t[13]=s,t[14]=c):c=t[14],c},ky=e=>{if(!_.isNone(e.startedAt))return(_.isSome(e.endedAt)?l.toEpochMillis(e.endedAt.value):Date.now())-l.toEpochMillis(e.startedAt.value)},Ay=(e,t,n,r)=>{let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=`${n}-t${a}`;if(o.tool.multilineArgs){let e=o.tool.multilineArgs.split(`
42
- `);i.push(U(O,{color:r.DIM,wrap:`truncate`,children:[t,W.lineVertical,` `,H(O,{color:r.TEXT,children:o.tool.name}),`(`,o.isRunning&&U(O,{children:[` `,H(Le,{type:`line`})]}),o.resultTokens!==void 0&&` ${W.arrowDown} ${xy(o.resultTokens)} tokens`]},`${s}-h`));for(let n=0;n<e.length;n++)i.push(U(O,{color:r.DIM,children:[t,W.lineVertical,` `,` `,H(O,{color:r.TEXT,children:e[n]})]},`${s}-${n}`));i.push(U(O,{color:r.DIM,children:[t,W.lineVertical,` )`]},`${s}-c`))}else i.push(U(O,{color:r.DIM,wrap:`truncate`,children:[t,W.lineVertical,` `,H(O,{color:r.TEXT,children:o.tool.name}),`(`,o.tool.args,`)`,o.isRunning&&U(O,{children:[` `,H(Le,{type:`line`})]}),o.resultTokens!==void 0&&` ${W.arrowDown} ${xy(o.resultTokens)} tokens`]},s))}return i},jy=t=>{let n=re(113);if(n[0]!==`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`){for(let e=0;e<113;e+=1)n[e]=Symbol.for(`react.memo_cache_sentinel`);n[0]=`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`}let{changesFor:r,instruction:i,savedFlow:a,requiresCookies:o,baseUrls:s}=t,c=o===void 0?!1:o,l=Xm(My),u=Nt(),[,d]=At(),f=X_(Ny),p=X_(Py),m=X_(Fy),h=X_(Iy),g;n[1]===Symbol.for(`react.memo_cache_sentinel`)?(g={mode:`promiseExit`},n[1]=g):g=n[1];let[v,y]=rt(hy,g),b=at(py),[x,S]=R(void 0),C;n[2]===v?C=n[3]:(C=et.isWaiting(v),n[2]=v,n[3]=C);let w=C,ee;n[4]===v?ee=n[5]:(ee=et.isSuccess(v),n[4]=v,n[5]=ee);let T=ee,k=T?v.value.report:void 0,[A,ne]=R(void 0),[j,M]=R(void 0),[N,P]=R(0),[ie,ae]=R(!1),F=Mv(Ly),I=Mv(Ry),z=Mv(zy),B;n[6]===N?B=n[7]:(B=Nv(N),n[6]=N,n[7]=B);let se=B,ce=A?.steps?A.steps.length:0,V;if(n[8]!==u||n[9]!==se||n[10]!==A||n[11]!==F||n[12]!==w){if(V=[],F&&A){let e=A.steps??[];if(e.length===0&&w){let e=Ty(A.events,!0);V.push(...Ay(e,` `,`planning`,u))}for(let t=0;t<e.length;t++){let n=e[t],r=_.isSome(n.summary)?n.summary.value:n.title,i=ky(n),a=i===void 0?void 0:Nv(i),o=`${t+1}.`;if(n.status===`active`){V.push(U(E,{children:[U(O,{color:u.DIM,children:[` `,o,` `]}),H(Um,{}),H(O,{children:` `}),H(jv,{text:`${n.title} ${se}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]},`step-${t}`));let e=wy(A.events,!0);V.push(...Ay(e,` `,`s${t}`,u))}else if(n.status===`passed`){V.push(U(O,{children:[U(O,{color:u.DIM,children:[` `,o]}),U(O,{color:u.GREEN,children:[` `,W.tick,` `,Re(r,100)]}),a&&U(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`));let e=Dy(A.events,t);V.push(...Ay(e,` `,`s${t}`,u))}else if(n.status===`failed`){V.push(U(O,{children:[U(O,{color:u.DIM,children:[` `,o]}),U(O,{color:u.RED,children:[` `,W.cross,` `,Re(r,100)]}),a&&U(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`));let e=Dy(A.events,t);V.push(...Ay(e,` `,`s${t}`,u))}else n.status===`skipped`?V.push(U(O,{children:[U(O,{color:u.DIM,children:[` `,o]}),U(O,{color:u.YELLOW,children:[` `,W.arrowRight,` `,Re(r,100)]}),a&&U(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`)):V.push(U(O,{color:u.DIM,children:[` `,o,` `,W.circle,` `,n.title]},`step-${t}`))}}n[8]=u,n[9]=se,n[10]=A,n[11]=F,n[12]=w,n[13]=V}else V=n[13];let G=Math.max(1,d-6),K;n[14]!==V.length||n[15]!==G?(K={itemCount:V.length,visibleCount:G},n[14]=V.length,n[15]=G,n[16]=K):K=n[16];let ue=Gm(K),de=L(!1),fe,pe;n[17]!==F||n[18]!==V.length||n[19]!==ue?(fe=()=>{F&&!de.current&&V.length>0&&ue.setHighlightedIndex(V.length-1),de.current=F},pe=[F,V.length,ue],n[17]=F,n[18]=V.length,n[19]=ue,n[20]=fe,n[21]=pe):(fe=n[20],pe=n[21]),oe(fe,pe);let me,he;n[22]!==f||n[23]!==s||n[24]!==p||n[25]!==r||n[26]!==i||n[27]!==m||n[28]!==c||n[29]!==a||n[30]!==y?(he=()=>{M(Date.now());let e=s&&s.length>0?s.join(`, `):void 0,t=s?s.map(By).join(` `):void 0;return y({options:{changesFor:r,instruction:t?`${i} ${t}`:i,isHeadless:!p,requiresCookies:c,savedFlow:a,baseUrl:e},agentBackend:f,replayHost:m,onUpdate:ne,onReplayUrl:S}),()=>{y(tt.Interrupt)}},me=[y,f,p,r,i,a,c,s,m],n[22]=f,n[23]=s,n[24]=p,n[25]=r,n[26]=i,n[27]=m,n[28]=c,n[29]=a,n[30]=y,n[31]=me,n[32]=he):(me=n[31],he=n[32]),oe(he,me);let ge=T?v.value.replayUrl:void 0,q=T?v.value.localReplayUrl:void 0,_e=T?v.value.videoUrl:void 0,ve,ye;n[33]!==A||n[34]!==T||n[35]!==q||n[36]!==ge||n[37]!==k||n[38]!==l||n[39]!==_e?(ve=()=>{T&&A&&k&&(Mv.getState().setExecutedPlan(A),l(Jm.Results({report:k,replayUrl:ge,localReplayUrl:q,videoUrl:_e})))},ye=[T,A,k,ge,q,_e,l],n[33]=A,n[34]=T,n[35]=q,n[36]=ge,n[37]=k,n[38]=l,n[39]=_e,n[40]=ve,n[41]=ye):(ve=n[40],ye=n[41]),oe(ve,ye);let be;n[42]===l?be=n[43]:(be=()=>{Mv.getState().setExecutedPlan(void 0),l(Jm.Main())},n[42]=l,n[43]=be);let xe=be,Se,Ce;n[44]!==w||n[45]!==j?(Se=()=>{if(j===void 0||!w)return;let e=setInterval(()=>{P(Date.now()-j)},1e3);return()=>clearInterval(e)},Ce=[j,w],n[44]=w,n[45]=j,n[46]=Se,n[47]=Ce):(Se=n[46],Ce=n[47]),oe(Se,Ce);let we;n[48]!==A||n[49]!==v||n[50]!==F||n[51]!==ue||n[52]!==xe||n[53]!==w||n[54]!==x||n[55]!==q||n[56]!==ge||n[57]!==k||n[58]!==I||n[59]!==l||n[60]!==ie||n[61]!==z||n[62]!==h||n[63]!==_e?(we=(t,n)=>{let r=t.toLowerCase();if(ie){if(n.return||r===`y`){ae(!1),Q_(`run:cancelled`),xe();return}(n.escape||r===`n`)&&ae(!1);return}if(r===`o`&&!n.ctrl&&!n.meta&&x){let{exec:t}=e(`node:child_process`);t(`open "${x.replace(/"/g,`\\"`)}"`),Q_(`live_preview:opened`);return}if(n.ctrl&&t===`o`){z();return}if(n.ctrl&&t===`n`){h();return}if(F){if(ue.handleNavigation(t,n))return;if(n.escape){I(!1);return}return}if(n.escape){if(et.isFailure(v)){xe();return}if(w){ae(!0);return}if(A&&k){Mv.getState().setExecutedPlan(A),l(Jm.Results({report:k,replayUrl:ge,localReplayUrl:q,videoUrl:_e}));return}xe()}},n[48]=A,n[49]=v,n[50]=F,n[51]=ue,n[52]=xe,n[53]=w,n[54]=x,n[55]=q,n[56]=ge,n[57]=k,n[58]=I,n[59]=l,n[60]=ie,n[61]=z,n[62]=h,n[63]=_e,n[64]=we):we=n[64],te(we);let Te;n[65]!==V||n[66]!==ue.scrollOffset||n[67]!==G?(Te=V.slice(ue.scrollOffset,ue.scrollOffset+G),n[65]=V,n[66]=ue.scrollOffset,n[67]=G,n[68]=Te):Te=n[68];let Ee=Te,De;n[69]===b?De=n[70]:(De=H(D,{items:[...b],children:Vy}),n[69]=b,n[70]=De);let Oe;n[71]===Symbol.for(`react.memo_cache_sentinel`)?(Oe=H(tv,{}),n[71]=Oe):Oe=n[71];let ke;n[72]===u.DIM?ke=n[73]:(ke=H(O,{color:u.DIM,children:W.pointerSmall}),n[72]=u.DIM,n[73]=ke);let Ae;n[74]!==u.TEXT||n[75]!==i?(Ae=H(O,{color:u.TEXT,children:i}),n[74]=u.TEXT,n[75]=i,n[76]=Ae):Ae=n[76];let je;n[77]!==ke||n[78]!==Ae?(je=U(E,{children:[Oe,U(O,{wrap:`truncate`,children:[` `,ke,` `,Ae]})]}),n[77]=ke,n[78]=Ae,n[79]=je):je=n[79];let Me;n[80]!==u.DIM||n[81]!==u.PRIMARY||n[82]!==w||n[83]!==x?(Me=x&&w&&H(E,{marginTop:0,children:U(O,{color:u.DIM,children:[` `,`Press `,H(O,{color:u.PRIMARY,children:`o`}),` to open live preview`]})}),n[80]=u.DIM,n[81]=u.PRIMARY,n[82]=w,n[83]=x,n[84]=Me):Me=n[84];let Ne;n[85]!==u.DIM||n[86]!==u.GREEN||n[87]!==u.RED||n[88]!==u.YELLOW||n[89]!==se||n[90]!==A||n[91]!==F||n[92]!==w||n[93]!==ce||n[94]!==Ee?(Ne=F?H(E,{flexDirection:`column`,marginTop:1,children:Ee}):U(le,{children:[ce===0&&w&&(()=>{let e=A?Ty(A.events,!1):[];return U(E,{marginTop:1,flexDirection:`column`,children:[U(E,{children:[H(Um,{}),H(O,{children:` `}),H(jv,{text:`Starting${W.ellipsis} ${se}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]}),e.map(Hy)]})})(),H(E,{flexDirection:`column`,marginTop:1,children:(A?.steps??[]).map((e,t)=>{let n=_.isSome(e.summary)?e.summary.value:e.title,r=ky(e),i=r===void 0?void 0:Nv(r),a=`${t+1}.`;if(e.status===`active`){let t=A?wy(A.events,!1):[];return U(E,{flexDirection:`column`,children:[U(E,{children:[U(O,{color:u.DIM,children:[` `,a,` `]}),H(Um,{}),H(O,{children:` `}),H(jv,{text:`${e.title} ${se}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]}),t.map(Uy)]},e.id)}return e.status===`passed`?U(O,{children:[U(O,{color:u.DIM,children:[` `,a]}),U(O,{color:u.GREEN,children:[` `,W.tick,` `,Re(n,100)]}),i&&U(O,{color:u.DIM,children:[` `,i]})]},e.id):e.status===`failed`?U(O,{children:[U(O,{color:u.DIM,children:[` `,a]}),U(O,{color:u.RED,children:[` `,W.cross,` `,Re(n,100)]}),i&&U(O,{color:u.DIM,children:[` `,i]})]},e.id):e.status===`skipped`?U(O,{children:[U(O,{color:u.DIM,children:[` `,a]}),U(O,{color:u.YELLOW,children:[` `,W.arrowRight,` `,Re(n,100)]}),i&&U(O,{color:u.DIM,children:[` `,i]})]},e.id):U(O,{color:u.DIM,children:[` `,a,` `,W.circle,` `,e.title]},e.id)})})]}),n[85]=u.DIM,n[86]=u.GREEN,n[87]=u.RED,n[88]=u.YELLOW,n[89]=se,n[90]=A,n[91]=F,n[92]=w,n[93]=ce,n[94]=Ee,n[95]=Ne):Ne=n[95];let Pe;n[96]!==u.PRIMARY||n[97]!==u.YELLOW||n[98]!==ie?(Pe=ie&&H(E,{marginTop:1,children:U(O,{color:u.YELLOW,children:[`Stop run? `,H(O,{color:u.PRIMARY,children:`enter`}),` to stop,`,` `,H(O,{color:u.PRIMARY,children:`esc`}),` to dismiss`]})}),n[96]=u.PRIMARY,n[97]=u.YELLOW,n[98]=ie,n[99]=Pe):Pe=n[99];let Fe;n[100]!==je||n[101]!==Me||n[102]!==Ne||n[103]!==Pe?(Fe=U(E,{flexDirection:`column`,width:`100%`,paddingY:1,paddingX:1,children:[je,Me,Ne,Pe]}),n[100]=je,n[101]=Me,n[102]=Ne,n[103]=Pe,n[104]=Fe):Fe=n[104];let Ie;n[105]===v?Ie=n[106]:(Ie=et.builder(v).onError(Wy).onDefect(Gy).orNull(),n[105]=v,n[106]=Ie);let Le;n[107]!==Fe||n[108]!==Ie?(Le=U(E,{flexDirection:`column`,width:`100%`,children:[Fe,Ie]}),n[107]=Fe,n[108]=Ie,n[109]=Le):Le=n[109];let ze;return n[110]!==De||n[111]!==Le?(ze=U(le,{children:[De,Le]}),n[110]=De,n[111]=Le,n[112]=ze):ze=n[112],ze};function My(e){return e.setScreen}function Ny(e){return e.agentBackend}function Py(e){return e.browserHeaded}function Fy(e){return e.replayHost}function Iy(e){return e.toggleNotifications}function Ly(e){return e.expanded}function Ry(e){return e.setExpanded}function zy(e){return e.toggleExpanded}function By(e){return`[url: ${e}]`}function Vy(e){return H(E,{paddingX:1,children:H(Yv,{src:e,alt:e})},e)}function Hy(e,t){return H(Oy,{display:e,indent:` `},t)}function Uy(e,t){return H(Oy,{display:e,indent:` `},t)}function Wy(e){return H(Xv,{type:`error`,error:e})}function Gy(e){return H(Xv,{type:`defect`,error:{_tag:`Defect`,message:s.pretty(s.fail(e))}})}const Ky=e=>{try{return z.execSync(`pbcopy`,{input:e,stdio:[`pipe`,`ignore`,`ignore`]}),!0}catch{return!1}},qy=(e,t)=>u.runPromise(fm.use(n=>n.addComment(process.cwd(),e,t)).pipe(u.provide(fm.layer))),Jy=()=>N({mutationFn:({pullRequest:e,body:t})=>qy(e,t)}),Yy=ey.fn(u.fnUntraced(function*(e,t){return yield*(yield*lm).save(e.plan)},u.annotateLogs({fn:`saveFlowFn`}),u.provide(ye.layer))),Xy=e=>{if(!(_.isNone(e.startedAt)||_.isNone(e.endedAt)))return l.toEpochMillis(e.endedAt.value)-l.toEpochMillis(e.startedAt.value)},Zy=e=>{let t=0;for(let n of e){let e=Xy(n);e!==void 0&&(t+=e)}return t},Qy=e=>{let t=re(141);if(t[0]!==`b7e547f8ebc01ced52659efc05613f9ccf6a352b61760b052762a2223144f2e9`){for(let e=0;e<141;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`b7e547f8ebc01ced52659efc05613f9ccf6a352b61760b052762a2223144f2e9`}let{report:n,replayUrl:r,localReplayUrl:i,videoUrl:a}=e,o=Nt(),s=Xm($y),[c,l]=R(void 0),u=Jy(),d;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(d={mode:`promiseExit`},t[1]=d):d=t[1];let[f,p]=rt(Yy,d),m=f.waiting,h;t[2]===f?h=t[3]:(h=et.isSuccess(f),t[2]=f,t[3]=h);let g=h,v;t[4]!==u||t[5]!==n.pullRequest||t[6]!==n.toPlainText?(v=()=>{_.isSome(n.pullRequest)&&(Q_(`results:posted_to_pr`),u.mutate({pullRequest:n.pullRequest.value,body:n.toPlainText}))},t[4]=u,t[5]=n.pullRequest,t[6]=n.toPlainText,t[7]=v):v=t[7];let y=v,b;t[8]!==o.GREEN||t[9]!==o.RED||t[10]!==n.toPlainText?(b=()=>{Ky(n.toPlainText)?(Q_(`results:copied_to_clipboard`),l({text:`${W.tick} Copied to clipboard`,color:o.GREEN})):l({text:`${W.cross} Failed to copy to clipboard`,color:o.RED})},t[8]=o.GREEN,t[9]=o.RED,t[10]=n.toPlainText,t[11]=b):b=t[11];let x=b,S;t[12]!==n||t[13]!==m||t[14]!==g||t[15]!==p?(S=async()=>{m||g||(Q_(`flow:saved`,{step_count:n.steps.length}),await p({plan:n}))},t[12]=n,t[13]=m,t[14]=g,t[15]=p,t[16]=S):S=t[16];let C=S,w;t[17]!==n.changesFor||t[18]!==n.instruction||t[19]!==s?(w=()=>{Q_(`results:restarted`),Mv.getState().setExecutedPlan(void 0),s(Ym({changesFor:n.changesFor,instruction:n.instruction}))},t[17]=n.changesFor,t[18]=n.instruction,t[19]=s,t[20]=w):w=t[20];let ee=w,T;t[21]!==x||t[22]!==y||t[23]!==ee||t[24]!==C?(T=e=>{let t=e.toLowerCase();t===`y`&&x(),t===`p`&&y(),t===`s`&&C(),t===`r`&&ee()},t[21]=x,t[22]=y,t[23]=ee,t[24]=C,t[25]=T):T=t[25],te(T);let D=n.status===`passed`,k=D?o.GREEN:o.RED,A=D?W.tick:W.cross,ne=D?`Passed`:`Failed`,j,M,N,P,ie,ae,F,oe,I,L,z;if(t[26]!==o.DIM||t[27]!==o.GREEN||t[28]!==o.RED||t[29]!==o.TEXT||t[30]!==o.YELLOW||t[31]!==i||t[32]!==r||t[33]!==n.instruction||t[34]!==n.stepStatuses||t[35]!==n.steps||t[36]!==k||t[37]!==A||t[38]!==ne){let e=Zy(n.steps);M=r??i,N=!!r&&!!i&&r!==i&&i!==void 0,j=E,L=`column`,z=`100%`,P=1,ie=1;let a;t[50]===Symbol.for(`react.memo_cache_sentinel`)?(a=H(tv,{}),t[50]=a):a=t[50];let s;t[51]===o.DIM?s=t[52]:(s=H(O,{color:o.DIM,children:W.pointerSmall}),t[51]=o.DIM,t[52]=s);let c;t[53]!==o.TEXT||t[54]!==n.instruction?(c=H(O,{color:o.TEXT,children:n.instruction}),t[53]=o.TEXT,t[54]=n.instruction,t[55]=c):c=t[55],t[56]!==s||t[57]!==c?(ae=U(E,{children:[a,U(O,{wrap:`truncate`,children:[` `,s,` `,c]})]}),t[56]=s,t[57]=c,t[58]=ae):ae=t[58];let l;t[59]!==k||t[60]!==A||t[61]!==ne?(l=U(O,{color:k,bold:!0,children:[A,` `,ne]}),t[59]=k,t[60]=A,t[61]=ne,t[62]=l):l=t[62];let u=n.steps.length===1?``:`s`,d;t[63]!==o.DIM||t[64]!==n.steps.length||t[65]!==u?(d=U(O,{color:o.DIM,children:[` `,n.steps.length,` step`,u]}),t[63]=o.DIM,t[64]=n.steps.length,t[65]=u,t[66]=d):d=t[66],t[67]!==l||t[68]!==d?(F=U(E,{marginTop:1,children:[l,d]}),t[67]=l,t[68]=d,t[69]=F):F=t[69];let f;if(t[70]!==o.DIM||t[71]!==o.GREEN||t[72]!==o.RED||t[73]!==o.YELLOW||t[74]!==n.stepStatuses||t[75]!==n.steps){let e;t[77]!==o.DIM||t[78]!==o.GREEN||t[79]!==o.RED||t[80]!==o.YELLOW||t[81]!==n.stepStatuses?(e=(e,t)=>{let r=Xy(e),i=r===void 0?void 0:Nv(r),a=n.stepStatuses.get(e.id),s=a?.status===`failed`,c=a?.status===`skipped`,l=s?o.RED:c?o.YELLOW:o.GREEN,u=s?W.cross:c?W.arrowRight:W.tick,d=`${t+1}.`;return U(E,{flexDirection:`column`,children:[U(O,{children:[U(O,{color:o.DIM,children:[` `,d]}),U(O,{color:l,children:[` `,u,` `,e.title]}),i&&U(O,{color:o.DIM,children:[` `,i]})]}),(s||c)&&a?.summary&&U(O,{color:o.DIM,children:[` `,a.summary]})]},e.id)},t[77]=o.DIM,t[78]=o.GREEN,t[79]=o.RED,t[80]=o.YELLOW,t[81]=n.stepStatuses,t[82]=e):e=t[82],f=n.steps.map(e),t[70]=o.DIM,t[71]=o.GREEN,t[72]=o.RED,t[73]=o.YELLOW,t[74]=n.stepStatuses,t[75]=n.steps,t[76]=f}else f=t[76];t[83]===f?oe=t[84]:(oe=H(E,{flexDirection:`column`,marginTop:1,children:f}),t[83]=f,t[84]=oe),I=e>0&&H(E,{marginTop:1,children:U(O,{color:o.DIM,children:[`Worked for `,Nv(e)]})}),t[26]=o.DIM,t[27]=o.GREEN,t[28]=o.RED,t[29]=o.TEXT,t[30]=o.YELLOW,t[31]=i,t[32]=r,t[33]=n.instruction,t[34]=n.stepStatuses,t[35]=n.steps,t[36]=k,t[37]=A,t[38]=ne,t[39]=j,t[40]=M,t[41]=N,t[42]=P,t[43]=ie,t[44]=ae,t[45]=F,t[46]=oe,t[47]=I,t[48]=L,t[49]=z}else j=t[39],M=t[40],N=t[41],P=t[42],ie=t[43],ae=t[44],F=t[45],oe=t[46],I=t[47],L=t[48],z=t[49];let B;t[85]===c?B=t[86]:(B=c&&H(E,{marginTop:1,children:H(O,{color:c.color,children:c.text})}),t[85]=c,t[86]=B);let se;t[87]!==o.DIM||t[88]!==u.isPending?(se=u.isPending&&H(E,{marginTop:1,children:U(O,{color:o.DIM,children:[`Posting to PR`,W.ellipsis]})}),t[87]=o.DIM,t[88]=u.isPending,t[89]=se):se=t[89];let ce;t[90]!==o.GREEN||t[91]!==u.isSuccess?(ce=u.isSuccess&&H(E,{marginTop:1,children:U(O,{color:o.GREEN,children:[W.tick,` Posted to PR`]})}),t[90]=o.GREEN,t[91]=u.isSuccess,t[92]=ce):ce=t[92];let V;t[93]!==o.RED||t[94]!==u.isError?(V=u.isError&&H(E,{marginTop:1,children:U(O,{color:o.RED,children:[W.cross,` Failed to post to PR`]})}),t[93]=o.RED,t[94]=u.isError,t[95]=V):V=t[95];let le;t[96]!==o.DIM||t[97]!==m?(le=m&&H(E,{marginTop:1,children:U(O,{color:o.DIM,children:[`Saving flow`,W.ellipsis]})}),t[96]=o.DIM,t[97]=m,t[98]=le):le=t[98];let G;t[99]!==o.GREEN||t[100]!==g?(G=g&&H(E,{marginTop:1,children:U(O,{color:o.GREEN,children:[W.tick,` Flow saved`]})}),t[99]=o.GREEN,t[100]=g,t[101]=G):G=t[101];let K;t[102]!==o.RED||t[103]!==f?(K=et.isFailure(f)&&H(E,{marginTop:1,children:U(O,{color:o.RED,children:[W.cross,` Failed to save flow`]})}),t[102]=o.RED,t[103]=f,t[104]=K):K=t[104];let ue;t[105]!==o.DIM||t[106]!==o.PRIMARY||t[107]!==M?(ue=M&&H(E,{flexDirection:`column`,paddingX:1,marginTop:1,children:U(O,{color:o.DIM,children:[`Replay:`,` `,H(O,{color:o.PRIMARY,bold:!0,children:M})]})}),t[105]=o.DIM,t[106]=o.PRIMARY,t[107]=M,t[108]=ue):ue=t[108];let de;t[109]!==o.DIM||t[110]!==o.PRIMARY||t[111]!==i||t[112]!==N?(de=N&&H(E,{flexDirection:`column`,paddingX:1,children:U(O,{color:o.DIM,children:[`Local Replay:`,` `,H(O,{color:o.PRIMARY,bold:!0,children:i})]})}),t[109]=o.DIM,t[110]=o.PRIMARY,t[111]=i,t[112]=N,t[113]=de):de=t[113];let fe;t[114]!==o.DIM||t[115]!==o.PRIMARY||t[116]!==a?(fe=a&&H(E,{flexDirection:`column`,paddingX:1,children:U(O,{color:o.DIM,children:[`Video:`,` `,H(O,{color:o.PRIMARY,bold:!0,children:a})]})}),t[114]=o.DIM,t[115]=o.PRIMARY,t[116]=a,t[117]=fe):fe=t[117];let pe;t[118]===n.screenshotPaths?pe=t[119]:(pe=n.screenshotPaths.map(eb),t[118]=n.screenshotPaths,t[119]=pe);let me;return t[120]!==j||t[121]!==P||t[122]!==ie||t[123]!==ae||t[124]!==F||t[125]!==oe||t[126]!==I||t[127]!==B||t[128]!==se||t[129]!==ce||t[130]!==V||t[131]!==le||t[132]!==G||t[133]!==K||t[134]!==ue||t[135]!==de||t[136]!==fe||t[137]!==pe||t[138]!==L||t[139]!==z?(me=U(j,{flexDirection:L,width:z,paddingY:P,paddingX:ie,children:[ae,F,oe,I,B,se,ce,V,le,G,K,ue,de,fe,pe]}),t[120]=j,t[121]=P,t[122]=ie,t[123]=ae,t[124]=F,t[125]=oe,t[126]=I,t[127]=B,t[128]=se,t[129]=ce,t[130]=V,t[131]=le,t[132]=G,t[133]=K,t[134]=ue,t[135]=de,t[136]=fe,t[137]=pe,t[138]=L,t[139]=z,t[140]=me):me=t[140],me};function $y(e){return e.setScreen}function eb(e){return H(E,{marginTop:1,children:H(Yv,{src:e,alt:`Screenshot: ${e}`})},e)}const tb=m.mergeAll(lm.layer,Yp.withRepoRoot(process.cwd())),nb=()=>P({queryKey:[`saved-flows`],queryFn:()=>u.gen(function*(){return yield*(yield*lm).list()}).pipe(u.provide(tb),u.provide(ye.layer),u.catchTag(`FindRepoRootError`,()=>u.succeed([])),u.runPromise)}),rb=new fn({isGitRepo:!1,currentBranch:`HEAD`,mainBranch:void 0,isOnMain:!1,hasChangesFromMain:!1,hasUnstagedChanges:!1,hasBranchCommits:!1,branchCommitCount:0,fileStats:[],workingTreeFileStats:[],fingerprint:void 0,savedFingerprint:void 0}),ib=()=>P({queryKey:[`git-state`],queryFn:async()=>{let e=await u.runPromiseExit(u.gen(function*(){return yield*(yield*Yp).getState()}).pipe(u.provide(Yp.withRepoRoot(process.cwd())),u.catchTag(`FindRepoRootError`,()=>u.succeed(rb)),u.timeoutOrElse({duration:1e4,onTimeout:()=>u.succeed(rb)}),u.provide(ye.layer)));return d.isSuccess(e)?e.value:rb}}),ab=e=>Array.isArray(e.flow?.steps)?e.flow.steps:[],ob=(e,t)=>{let n=hn.makeUnsafe({_tag:`Changes`,mainBranch:t}),r=ab(e),i={title:e.flow.title,userInstruction:e.flow.userInstruction,steps:r},a=e.environment.cookies;Q_(`flow:reused`,{slug:e.slug,step_count:r.length}),Xm.getState().setScreen(Ym({changesFor:n,instruction:e.flow.userInstruction,savedFlow:i,requiresCookies:a}))},sb=()=>{let e=re(11);if(e[0]!==`53939b05c229418d7d52eba403172d78da52d4f06481f5625a9cf002fc443ae8`){for(let t=0;t<11;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`53939b05c229418d7d52eba403172d78da52d4f06481f5625a9cf002fc443ae8`}let t=Nt(),[n]=At(),r=Xm(cb),{data:i}=ib(),{data:a,isLoading:o}=nb(),s=a===void 0?[]:a,{highlightedIndex:c,setHighlightedIndex:l,scrollOffset:u,handleNavigation:d}=Gm({itemCount:s.length,visibleCount:15}),f=Math.min(40,Math.floor(n*.35)),p=Math.max(20,n-f-8),m=s.slice(u,u+15);te((e,t)=>{if(!d(e,t)){if(t.return){let e=s[c];e&&ob(e,i?.mainBranch??`main`)}t.escape&&r(Jm.Main())}});let h=E,g=`${s.length} flow${s.length===1?``:`s`}`,_;e[1]===g?_=e[2]:(_=H(E,{paddingX:1,children:H(Qm,{title:`Saved flows`,subtitle:g})}),e[1]=g,e[2]=_);let v;e[3]===o?v=e[4]:(v=o&&H(E,{marginTop:1,paddingX:1,children:H(Um,{message:`Loading saved flows...`})}),e[3]=o,e[4]=v);let y=!o&&s.length===0&&H(E,{marginTop:1,paddingX:1,flexDirection:`column`,children:U(O,{color:t.DIM,children:[`No saved flows yet. Run a test and press `,H(O,{color:t.PRIMARY,children:`s`}),` on the results screen to save a flow.`]})}),b=!o&&s.length>0&&H(E,{marginTop:1,flexDirection:`column`,height:15,overflow:`hidden`,paddingX:1,children:m.map((e,n)=>{let r=n+u,a=r===c,o=ab(e).length;return U(It,{onClick:()=>{l(r),ob(e,i?.mainBranch??`main`)},children:[H(O,{color:a?t.PRIMARY:t.DIM,children:a?`${W.pointer} `:` `}),H(O,{color:a?t.PRIMARY:t.TEXT,bold:a,children:Wm(Re(e.title,f-1),f)}),H(O,{color:t.DIM,children:Wm(`${o} step${o===1?``:`s`}`,10)}),H(O,{color:t.DIM,children:Re(e.description,p)})]},e.slug)})}),x;return e[5]!==h||e[6]!==_||e[7]!==v||e[8]!==y||e[9]!==b?(x=U(h,{flexDirection:`column`,width:`100%`,paddingY:1,children:[_,v,y,b]}),e[5]=h,e[6]=_,e[7]=v,e[8]=y,e[9]=b,e[10]=x):x=e[10],x};function cb(e){return e.setScreen}const lb=e=>{let t=re(7);if(t[0]!==`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`){for(let e=0;e<7;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`}let{status:n}=e,r=Nt();if(n===`open`){let e;return t[1]===r.GREEN?e=t[2]:(e=U(O,{color:r.GREEN,children:[W.bullet,` `]}),t[1]=r.GREEN,t[2]=e),e}if(n===`merged`){let e;return t[3]===r.PURPLE?e=t[4]:(e=U(O,{color:r.PURPLE,children:[W.bullet,` `]}),t[3]=r.PURPLE,t[4]=e),e}if(n===`draft`){let e;return t[5]===r.DIM?e=t[6]:(e=U(O,{color:r.DIM,children:[W.bullet,` `]}),t[5]=r.DIM,t[6]=e),e}return null},ub=e=>{let t=re(30);if(t[0]!==`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`){for(let e=0;e<30;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`}let{options:n,selectedIndex:r,isLoading:i,gitState:a}=e,o=Nt(),s;bb0:{if(n.length<=8){s=0;break bb0}let e=n.length-8;s=Math.min(e,Math.max(0,r-4))}let c=s,l,u,d,f;if(t[1]!==o||t[2]!==a||t[3]!==i||t[4]!==n||t[5]!==c||t[6]!==r){f=Symbol.for(`react.early_return_sentinel`);bb1:{let e=n.slice(c,c+8);if(n.length===0&&!i){let e;t[11]===o.DIM?e=t[12]:(e=H(E,{flexDirection:`column`,children:H(O,{color:o.DIM,children:`No matching results`})}),t[11]=o.DIM,t[12]=e),f=e;break bb1}l=E,u=`column`;let s;t[13]!==o||t[14]!==a||t[15]!==c||t[16]!==r?(s=(e,t)=>{let n=t+c===r,i=Rm(e,a),s=zm(e,a),l=e._tag===`PullRequest`||e._tag===`Branch`?e.branch.prNumber:null,u=e._tag===`PullRequest`||e._tag===`Branch`?e.branch.prStatus:null;return U(O,{wrap:`truncate`,children:[H(O,{color:n?o.PRIMARY:o.DIM,children:n?`${W.pointer} `:` `}),e._tag===`WorkingTree`?U(O,{color:o.GREEN,children:[W.bullet,` `]}):null,u?H(lb,{status:u}):null,H(O,{color:n?o.PRIMARY:o.TEXT,bold:n,children:i}),l?U(O,{children:[` `,U(O,{color:u===`open`?o.GREEN:u===`merged`?o.PURPLE:o.DIM,children:[`#`,l]}),u?U(O,{color:o.DIM,children:[` `,u]}):null]}):null,s&&!l?U(O,{color:o.DIM,children:[` `,s]}):null]},Kn(e))},t[13]=o,t[14]=a,t[15]=c,t[16]=r,t[17]=s):s=t[17],d=e.map(s)}t[1]=o,t[2]=a,t[3]=i,t[4]=n,t[5]=c,t[6]=r,t[7]=l,t[8]=u,t[9]=d,t[10]=f}else l=t[7],u=t[8],d=t[9],f=t[10];if(f!==Symbol.for(`react.early_return_sentinel`))return f;let p;t[18]!==o||t[19]!==i?(p=i?H(E,{children:U(O,{color:o.DIM,children:[` Loading PRs and branches`,W.ellipsis]})}):null,t[18]=o,t[19]=i,t[20]=p):p=t[20];let m;t[21]!==o||t[22]!==n.length?(m=n.length>8?H(E,{children:U(O,{color:o.DIM,children:[` `,n.length-8,` more `,W.arrowUp,`/`,W.arrowDown]})}):null,t[21]=o,t[22]=n.length,t[23]=m):m=t[23];let h;return t[24]!==l||t[25]!==u||t[26]!==d||t[27]!==p||t[28]!==m?(h=U(l,{flexDirection:u,children:[d,p,m]}),t[24]=l,t[25]=u,t[26]=d,t[27]=p,t[28]=m,t[29]=h):h=t[29],h},db=({gitState:e,onSelect:t})=>{let[n,r]=R(!1),[i,a]=R(``),[o,s]=R(0),{data:c=[]}=P({queryKey:[`local-context-options`,e?.currentBranch],queryFn:()=>Fm(e),enabled:!!e}),{data:l=[],isLoading:u}=P({queryKey:[`remote-context-options`,e?.currentBranch],queryFn:()=>Lm(e),enabled:n&&!!e}),d=I(()=>[...c,...l],[c,l]),f=I(()=>Vm(d,i,e),[d,i,e]);oe(()=>{s(0)},[i]);let p=ae(()=>{r(!0),a(``),s(0)},[]),m=ae(()=>{r(!1),a(``)},[]);return{pickerOpen:n,pickerQuery:i,pickerIndex:o,filteredOptions:f,localOptions:c,remoteLoading:u,openPicker:p,closePicker:m,handleContextSelect:ae(e=>{t(e),m()},[t,m]),setPickerQuery:a,setPickerIndex:s,createInputChangeHandler:(e,t)=>r=>{let i=Dt(r),o=e.current;if(i.length>o.length&&i[i.length-1]===`@`&&(o.length===0||i[i.length-2]===` `)){t(i.slice(0,-1)),p();return}if(n){i.length-o.length<0?(m(),t(i)):a(e=>{let n=i.slice(o.length);return n.includes(` `)?(m(),t(i),``):e+n});return}t(i)}}},fb=e=>{let t=new Set;return e.filter(e=>t.has(e.path)?!1:(t.add(e.path),!0))},pb=e=>P({queryKey:[`test-coverage`,e?.fingerprint],queryFn:async()=>{if(!e?.isGitRepo||!e.hasChangesFromMain&&!e.hasUnstagedChanges)return;let t=e.mainBranch??`main`,n=await u.runPromiseExit(u.gen(function*(){let e=yield*Yp,n=yield*Nm,r=yield*e.getChangedFiles(hn.makeUnsafe({_tag:`WorkingTree`})),i=yield*e.getChangedFiles(hn.makeUnsafe({_tag:`Changes`,mainBranch:t})),a=fb([...r,...i]);if(a.length!==0)return yield*n.analyze(a)}).pipe(u.provide(Yp.withRepoRoot(process.cwd())),u.provide(Nm.layer),u.timeoutOrElse({duration:15e3,onTimeout:()=>u.succeed(void 0)}),u.provide(ye.layer)));if(d.isSuccess(n))return n.value},enabled:!!(e?.isGitRepo&&(e.hasChangesFromMain||e.hasUnstagedChanges)),staleTime:3e4}),mb=[`Test the main user flow end to end`,`Smoke test the homepage and key pages`,`Check authentication and protected routes`],hb=[`Verify my recent changes work as expected`,`Check for regressions in related features`,`Test the main user flow end to end`],gb=[`Test the changes on this branch`,`Smoke test this branch end to end`,`Check for regressions on this branch`],_b=[`Test the changes in this pull request`,`Check for regressions introduced by this PR`,`Verify the PR works end to end`],vb=[`Test the changes from this commit`,`Check if this commit introduces regressions`,`Verify this commit works as expected`],yb=(e,t)=>{if(!e)return mb;switch(e._tag){case`WorkingTree`:return hb;case`Branch`:return gb;case`PullRequest`:return _b;case`Commit`:return vb;default:return mb}},bb=e=>e>=70?Mt.GREEN:e>=40?Mt.YELLOW:Mt.RED,xb=e=>e>=70?`#0a2b0a`:e>=40?`#332b00`:`#331510`,Sb=e=>`Use Expect to test your changes.`,Cb=e=>{let t=Math.round(e/100*10),n=10-t;return{filled:`█`.repeat(t),empty:`░`.repeat(n)}},wb=({gitState:e})=>{let t=Nt(),[n]=At(),r=X_(e=>e.instructionHistory),i=Xm(e=>e.setScreen),[a,o]=R(void 0),[s,c]=R(``),[l,u]=R(0),[d,f]=R(0),[p,m]=R(!1),[h,g]=R(void 0),[_,v]=R(-1),[y,b]=R(``),x=sv(e=>e.cookiesEnabled),S=sv(e=>e.toggleCookies),{data:C}=pb(e),w=()=>{if(r.length===0)return;let e=_+1;e>=r.length||(_===-1&&b(s),v(e),c(r[e]),u(e=>e+1))},ee=()=>{if(_<=-1)return;let e=_-1;v(e),c(e===-1?y:r[e]),u(e=>e+1)},T=db({gitState:e??null,onSelect:e=>{o(e),Q_(`context:selected`,{context_type:{WorkingTree:`working_tree`,Branch:`branch`,PullRequest:`pull_request`,Commit:`commit`}[e._tag]})}}),D=T.localOptions.find(e=>e._tag===`WorkingTree`)??void 0,k=a??D??null,A=yb(k,e??null);oe(()=>{f(0)},[k,e]);let ne=t=>{let n=(t??s).trim();if(!n){g(`Describe what you want the browser agent to test.`);return}if(!e)return;let r=e.mainBranch??`main`,a;k?._tag===`Commit`?a=hn.makeUnsafe({_tag:`Commit`,hash:k.hash}):k?._tag===`Branch`||k?._tag===`PullRequest`?(k.branch.name&&(um(process.cwd(),k.branch.name),Zm.invalidateQueries({queryKey:[`git-state`]})),a=hn.makeUnsafe({_tag:`Branch`,mainBranch:r})):a=hn.makeUnsafe({_tag:`Changes`,mainBranch:r}),X_.getState().rememberInstruction(n),x||qm(n)?i(Ym({changesFor:a,instruction:n,requiresCookies:x})):i(Jm.CookieSyncConfirm({changesFor:a,instruction:n}))},j=L(s);j.current=s;let M=T.createInputChangeHandler(j,e=>{c(e),h&&g(void 0)}),N=!s.includes(`
43
- `),P=s===``&&!T.pickerOpen&&A.length>0,re=P&&!p&&n>=80,ie=A[d%A.length];return te((e,t)=>{if(T.pickerOpen){if(t.escape){T.closePicker();return}if(t.downArrow||t.ctrl&&e===`n`){T.setPickerIndex(Math.min(T.filteredOptions.length-1,T.pickerIndex+1));return}if(t.upArrow||t.ctrl&&e===`p`){T.setPickerIndex(Math.max(0,T.pickerIndex-1));return}if(t.return||t.tab){let e=T.filteredOptions[T.pickerIndex];e&&T.handleContextSelect(e);return}if(t.backspace||t.delete){T.pickerQuery.length===0?T.closePicker():T.setPickerQuery(T.pickerQuery.slice(0,-1));return}e&&!t.ctrl&&!t.meta&&T.setPickerQuery(T.pickerQuery+e);return}if(N&&t.upArrow){w();return}if(N&&t.downArrow){ee();return}if(t.ctrl&&e===`k`){S(),Q_(`cookies:toggled`,{enabled:!x});return}if(t.tab&&!t.shift&&P&&ie){c(ie),u(e=>e+1),Q_(`suggestion:accepted`);return}if(!(t.tab&&t.shift)&&P){if(t.rightArrow){f(e=>(e+1)%A.length),m(!0);return}if(t.leftArrow){f(e=>(e-1+A.length)%A.length),m(!0);return}}},{isActive:!0}),U(E,{flexDirection:`column`,width:`100%`,paddingY:1,children:[H(E,{flexDirection:`column`,marginBottom:1,paddingX:1,children:H(tv,{})}),(e?.hasUntestedChanges||C&&C.totalCount>0)&&!(C&&C.totalCount>0&&C.percent>=90)&&U(E,{paddingX:1,paddingY:1,marginBottom:1,backgroundColor:C&&C.totalCount>0?xb(C.percent):t.BANNER_BG,width:`100%`,flexDirection:`column`,gap:0,children:[(()=>{if(C&&C.totalCount>0)return U(E,{children:[U(O,{color:bb(C.percent),bold:!0,children:[W.warning,` Untested changes`]}),H(O,{children:` `}),H(O,{color:bb(C.percent),children:Cb(C.percent).filled}),H(O,{color:t.DIM,children:Cb(C.percent).empty}),U(O,{color:bb(C.percent),children:[` `,C.percent,`% test coverage`]})]});if(!e)return null;let n=e.workingTreeFileStats,r=n.reduce((e,t)=>e+t.added,0),i=n.reduce((e,t)=>e+t.removed,0);return U(E,{children:[U(O,{color:t.YELLOW,bold:!0,children:[W.warning,` Untested changes detected`]}),n.length>0&&U(le,{children:[U(O,{color:t.DIM,children:[` `,n.length,` file`,n.length===1?``:`s`,` `]}),r>0&&U(O,{color:t.GREEN,children:[`+`,r]}),r>0&&i>0&&H(O,{color:t.DIM,children:` `}),i>0&&U(O,{color:t.RED,children:[`-`,i]})]})]})})(),H(O,{color:t.DIM,children:C&&C.totalCount>0?Sb(C.percent):`Describe what to test and hit enter to verify your changes.`})]}),U(E,{flexDirection:`column`,width:`100%`,children:[U(E,{paddingX:1,children:[!e&&H(Um,{message:`loading context`}),e&&e.isGitRepo&&k&&H(It,{fullWidth:!1,onClick:()=>{T.pickerOpen?T.closePicker():T.openPicker()},children:U(O,{color:t.DIM,children:[W.bullet,` `,U(O,{color:t.PRIMARY,children:[`@`,Bm(k,e)]}),zm(k,e)&&` (${zm(k,e)})`]})})]}),H(It,{children:H(E,{flexDirection:`column`,marginTop:1,backgroundColor:t.INPUT_BG,width:`100%`,paddingX:1,paddingY:1,children:U(E,{children:[H(O,{color:t.PRIMARY,children:`❯ `}),H(E,{flexGrow:1,children:H(Ht,{focus:!T.pickerOpen,multiline:!0,placeholder:ie?`${ie} [tab]`:``,value:s,onSubmit:ne,onUpArrowAtTop:N?void 0:w,onDownArrowAtBottom:N?void 0:ee,onChange:M},l)}),re?H(O,{color:t.DIM,children:` ←→ cycle test suggestions`}):null]})})}),e?.isGitRepo&&T.pickerOpen&&U(Pt,{color:t.BORDER,children:[U(E,{marginBottom:0,children:[H(O,{color:t.DIM,children:`@ `}),H(O,{color:t.PRIMARY,children:T.pickerQuery}),H(O,{color:t.DIM,children:T.pickerQuery?``:`type to filter`})]}),H(ub,{options:T.filteredOptions,selectedIndex:T.pickerIndex,isLoading:T.remoteLoading,gitState:e})]}),e?.isGitRepo&&!T.pickerOpen&&H(E,{marginTop:1,paddingX:1,children:U(O,{color:t.DIM,children:[H(O,{color:t.PRIMARY,children:`@`}),` add context`]})})]}),H(Zv,{message:h})]})},Tb=e=>{let t=re(10);if(t[0]!==`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`){for(let e=0;e<10;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`}let{segment:n,mutedColor:r}=e,i=n.color??r,a;t[1]!==n.label||t[2]!==i?(a=U(O,{color:i,children:[n.label,` `]}),t[1]=n.label,t[2]=i,t[3]=a):a=t[3];let o=n.color??r,s;t[4]!==n.key||t[5]!==o?(s=U(O,{color:o,children:[`[`,n.key,`]`]}),t[4]=n.key,t[5]=o,t[6]=s):s=t[6];let c;return t[7]!==a||t[8]!==s?(c=U(le,{children:[a,s]}),t[7]=a,t[8]=s,t[9]=c):c=t[9],c},Eb=e=>{let t=re(12);if(t[0]!==`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`){for(let e=0;e<12;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`}let{segments:n,color:r,mutedColor:i}=e,a;t[1]===r?a=t[2]:(a=H(O,{color:r,children:` `}),t[1]=r,t[2]=a);let o;if(t[3]!==i||t[4]!==n){let e;t[6]!==i||t[7]!==n.length?(e=(e,t)=>U(E,{children:[e.onClick?H(It,{fullWidth:!1,onClick:e.onClick,children:H(Tb,{segment:e,mutedColor:i})}):H(Tb,{segment:e,mutedColor:i}),t<n.length-1&&H(O,{color:i,children:` `})]},e.key+e.label),t[6]=i,t[7]=n.length,t[8]=e):e=t[8],o=n.map(e),t[3]=i,t[4]=n,t[5]=o}else o=t[5];let s;return t[9]!==a||t[10]!==o?(s=U(E,{children:[a,o]}),t[9]=a,t[10]=o,t[11]=s):s=t[11],s},Db=S.Struct({version:S.String}),Ob=(e,t)=>{let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1},kb=u.gen(function*(){let e=yield*u.tryPromise({try:()=>fetch(`https://registry.npmjs.org/${yt}/latest`).then(e=>e.json()),catch:e=>Error(`npm registry fetch failed: ${e}`)});return(yield*u.try({try:()=>S.decodeUnknownSync(Db)(e),catch:e=>Error(`npm response decode failed: ${e}`)})).version}).pipe(u.timeoutOrElse({duration:5e3,onTimeout:()=>u.succeed(void 0)})),Ab=()=>{let{data:e}=P({queryKey:[`update-check`],queryFn:async()=>{let e=await u.runPromiseExit(kb);if(d.isSuccess(e))return e.value},staleTime:36e5,retry:!1,refetchOnWindowFocus:!1});return{latestVersion:e,updateAvailable:e!==void 0&&Ob(e,`0.0.11`)}},jb=(e,t)=>{let n=re(87);if(n[0]!==`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`){for(let e=0;e<87;e+=1)n[e]=Symbol.for(`react.memo_cache_sentinel`);n[0]=`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`}let r=Nt(),i=Xm(Pb),a=sv(Fb),o=sv(Ib),s=X_(Lb),c=X_(Rb),l=Mv(zb);switch(e._tag){case`Main`:{let e=a?`cookies on`:`cookies off`,r;n[1]!==e||n[2]!==o?(r={key:`ctrl+k`,label:e,cta:!0,onClick:o},n[1]=e,n[2]=o,n[3]=r):r=n[3];let s;n[4]===i?s=n[5]:(s={key:`ctrl+r`,label:`saved flows`,cta:!0,onClick:()=>i(Jm.SavedFlowPicker())},n[4]=i,n[5]=s);let c;if(n[6]!==t?.isGitRepo||n[7]!==i||n[8]!==r||n[9]!==s){if(c=[r,s],t?.isGitRepo){let e;n[11]===i?e=n[12]:(e={key:`ctrl+p`,label:`pick pr`,cta:!0,onClick:()=>i(Jm.SelectPr())},n[11]=i,n[12]=e),c.push(e)}n[6]=t?.isGitRepo,n[7]=i,n[8]=r,n[9]=s,n[10]=c}else c=n[10];return c}case`SelectPr`:{let e,t,a;n[13]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},t={key:`←→`,label:`filter`},a={key:`/`,label:`search`},n[13]=e,n[14]=t,n[15]=a):(e=n[13],t=n[14],a=n[15]);let o;n[16]===i?o=n[17]:(o={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Jm.Main())},n[16]=i,n[17]=o);let s;n[18]===r.PRIMARY?s=n[19]:(s={key:`enter`,label:`select`,color:r.PRIMARY,cta:!0},n[18]=r.PRIMARY,n[19]=s);let c;return n[20]!==o||n[21]!==s?(c=[e,t,a,o,s],n[20]=o,n[21]=s,n[22]=c):c=n[22],c}case`SavedFlowPicker`:{let e;n[23]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},n[23]=e):e=n[23];let t;n[24]===i?t=n[25]:(t={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Jm.Main())},n[24]=i,n[25]=t);let a;n[26]===r.PRIMARY?a=n[27]:(a={key:`enter`,label:`select`,color:r.PRIMARY,cta:!0},n[26]=r.PRIMARY,n[27]=a);let o;return n[28]!==t||n[29]!==a?(o=[e,t,a],n[28]=t,n[29]=a,n[30]=o):o=n[30],o}case`CookieSyncConfirm`:{let t;n[31]===Symbol.for(`react.memo_cache_sentinel`)?(t={key:`↑↓`,label:`nav`},n[31]=t):t=n[31];let a;n[32]===i?a=n[33]:(a={key:`esc`,label:`back`,onClick:()=>i(Jm.Main())},n[32]=i,n[33]=a);let o;n[34]!==e.changesFor||n[35]!==e.instruction||n[36]!==e.savedFlow||n[37]!==i?(o={key:`c`,label:`enable sync`,cta:!0,onClick:()=>{i(Ym({changesFor:e.changesFor,instruction:e.instruction,savedFlow:e.savedFlow,requiresCookies:!0}))}},n[34]=e.changesFor,n[35]=e.instruction,n[36]=e.savedFlow,n[37]=i,n[38]=o):o=n[38];let s;n[39]!==e.changesFor||n[40]!==e.instruction||n[41]!==e.savedFlow||n[42]!==i?(s=()=>{i(Ym({changesFor:e.changesFor,instruction:e.instruction,savedFlow:e.savedFlow,requiresCookies:!1}))},n[39]=e.changesFor,n[40]=e.instruction,n[41]=e.savedFlow,n[42]=i,n[43]=s):s=n[43];let c;n[44]!==r.PRIMARY||n[45]!==s?(c={key:`a`,label:`run anyway`,color:r.PRIMARY,cta:!0,onClick:s},n[44]=r.PRIMARY,n[45]=s,n[46]=c):c=n[46];let l;return n[47]!==a||n[48]!==o||n[49]!==c?(l=[t,a,o,c],n[47]=a,n[48]=o,n[49]=c,n[50]=l):l=n[50],l}case`PortPicker`:{let e,t,a;n[51]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},t={key:`space`,label:`toggle`},a={key:`/`,label:`custom port`},n[51]=e,n[52]=t,n[53]=a):(e=n[51],t=n[52],a=n[53]);let o;n[54]===i?o=n[55]:(o={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Jm.Main())},n[54]=i,n[55]=o);let s;n[56]===r.PRIMARY?s=n[57]:(s={key:`enter`,label:`confirm`,color:r.PRIMARY,cta:!0},n[56]=r.PRIMARY,n[57]=s);let c;return n[58]!==o||n[59]!==s?(c=[e,t,a,o,s],n[58]=o,n[59]=s,n[60]=c):c=n[60],c}case`Testing`:{let e=s===!0?`notify on`:`notify off`,t=l?`collapse`:`expand`,r;n[61]!==e||n[62]!==c?(r={key:`ctrl+n`,label:e,cta:!0,onClick:c},n[61]=e,n[62]=c,n[63]=r):r=n[63];let i;n[64]===t?i=n[65]:(i={key:`ctrl+o`,label:t,cta:!0},n[64]=t,n[65]=i);let a=l?`collapse`:`cancel`,o;n[66]===a?o=n[67]:(o={key:`esc`,label:a},n[66]=a,n[67]=o);let u;return n[68]!==r||n[69]!==i||n[70]!==o?(u=[r,i,o],n[68]=r,n[69]=i,n[70]=o,n[71]=u):u=n[71],u}case`Results`:{let t;n[72]===Symbol.for(`react.memo_cache_sentinel`)?(t={key:`y`,label:`copy`,cta:!0},n[72]=t):t=n[72];let r;if(n[73]!==e.report.changesFor||n[74]!==e.report.instruction||n[75]!==e.report.pullRequest||n[76]!==i){if(r=[t],_.isSome(e.report.pullRequest)){let e;n[78]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`p`,label:`post to PR`,cta:!0},n[78]=e):e=n[78],r.push(e)}let a;n[79]===Symbol.for(`react.memo_cache_sentinel`)?(a={key:`s`,label:`save flow`,cta:!0},n[79]=a):a=n[79],r.push(a);let o;n[80]!==e.report.changesFor||n[81]!==e.report.instruction||n[82]!==i?(o={key:`r`,label:`restart`,cta:!0,onClick:()=>{Mv.getState().setExecutedPlan(void 0),i(Ym({changesFor:e.report.changesFor,instruction:e.report.instruction}))}},n[80]=e.report.changesFor,n[81]=e.report.instruction,n[82]=i,n[83]=o):o=n[83],r.push(o);let s;n[84]===i?s=n[85]:(s={key:`esc`,label:`main menu`,cta:!0,onClick:()=>{Mv.getState().setExecutedPlan(void 0),i(Jm.Main())}},n[84]=i,n[85]=s),r.push(s),n[73]=e.report.changesFor,n[74]=e.report.instruction,n[75]=e.report.pullRequest,n[76]=i,n[77]=r}else r=n[77];return r}default:{let e;return n[86]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],n[86]=e):e=n[86],e}}},Mb=e=>e.length>0?` ${e.map(e=>`${e.label} [${e.key}]`).join(` `)}`:``,Nb=()=>{let e=re(34);if(e[0]!==`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`){for(let t=0;t<34;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`}let[t]=At(),{data:n}=ib(),r=Xm(Bb),{latestVersion:i,updateAvailable:a}=Ab(),o=jb(r,n),s,c,l,u,d,f,p,m;if(e[1]!==o||e[2]!==t||e[3]!==i||e[4]!==r._tag||e[5]!==a){let n=a?[...o,{key:`ctrl+u`,label:`v${i} available`,cta:!0,color:J.warning}]:o;u=n.filter(Vb);let h=ze(Mb(u)),g=Ub,_=n.filter(Wb),v=g(_)+h+2>t?_.filter(Gb):_,y=g(v);l=Math.max(0,t-y-h-2),c=E,p=`column`,e[14]!==t||e[15]!==r._tag?(m=r._tag===`Testing`?H(jv,{text:`─`.repeat(t),baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight,speed:3}):H(O,{color:J.border,children:`─`.repeat(t)}),e[14]=t,e[15]=r._tag,e[16]=m):m=e[16],s=E,d=1,f=v.map(Kb),e[1]=o,e[2]=t,e[3]=i,e[4]=r._tag,e[5]=a,e[6]=s,e[7]=c,e[8]=l,e[9]=u,e[10]=d,e[11]=f,e[12]=p,e[13]=m}else s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13];let h;e[17]===l?h=e[18]:(h=` `.repeat(l),e[17]=l,e[18]=h);let g;e[19]===h?g=e[20]:(g=H(O,{children:h}),e[19]=h,e[20]=g);let _;e[21]===u?_=e[22]:(_=u.length>0?H(Eb,{segments:u,color:J.primary,mutedColor:J.textMuted}):null,e[21]=u,e[22]=_);let v;e[23]!==s||e[24]!==d||e[25]!==f||e[26]!==g||e[27]!==_?(v=U(s,{paddingX:d,children:[f,g,_]}),e[23]=s,e[24]=d,e[25]=f,e[26]=g,e[27]=_,e[28]=v):v=e[28];let y;return e[29]!==c||e[30]!==p||e[31]!==m||e[32]!==v?(y=U(c,{flexDirection:p,children:[m,v]}),e[29]=c,e[30]=p,e[31]=m,e[32]=v,e[33]=y):y=e[33],y};function Pb(e){return e.setScreen}function Fb(e){return e.cookiesEnabled}function Ib(e){return e.toggleCookies}function Lb(e){return e.notifications}function Rb(e){return e.toggleNotifications}function zb(e){return e.expanded}function Bb(e){return e.screen}function Vb(e){return!e.cta}function Hb(e){return e.color?` ${e.label} [${e.key}] `:`${e.label} [${e.key}]`}function Ub(e){return ze(e.map(Hb).join(` `))}function Wb(e){return e.cta}function Gb(e){return e.key!==`ctrl+p`}function Kb(e,t){let n=U(O,{children:[t>0?` `:``,e.color?U(O,{backgroundColor:e.color,color:`black`,children:[` `,H(O,{bold:!0,children:e.label}),` `,U(O,{children:[`[`,e.key,`]`]}),` `]}):U(O,{children:[U(O,{color:J.textMuted,children:[e.label,` `]}),U(O,{color:J.textMuted,children:[`[`,e.key,`]`]})]})]},e.key+e.label);return e.onClick?H(It,{onClick:e.onClick,fullWidth:!1,children:n},e.key+e.label):n}let qb=null;const Jb=e=>{qb=e},Yb=()=>qb?.clear(),Xb=e=>{let t=re(34);if(t[0]!==`e6ac87aa0f631766a38fac7cfbcee5d6c83ce6fd1edd967a6457097df0e89416`){for(let e=0;e<34;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e6ac87aa0f631766a38fac7cfbcee5d6c83ce6fd1edd967a6457097df0e89416`}let{agent:n}=e,r=Xm(Zb),i=Xm(Qb),a=Xm($b),{data:o}=ib(),s=it($v),c,l;t[1]!==n||t[2]!==s?(c=()=>{s(_.some(n))},l=[n,s],t[1]=n,t[2]=s,t[3]=c,t[4]=l):(c=t[3],l=t[4]),oe(c,l);let u;t[5]!==r._tag||t[6]!==i?(u=()=>{if(r._tag===`CookieSyncConfirm`){i(Jm.Main());return}if(r._tag===`PortPicker`){i(Jm.Main());return}if(r._tag===`Results`){Mv.getState().setExecutedPlan(void 0),i(Jm.Main());return}r._tag!==`Testing`&&i(Jm.Main())},t[5]=r._tag,t[6]=i,t[7]=u):u=t[7];let d=u,{updateAvailable:f}=Ab(),{exit:p}=A(),[,m]=R(0),[,h]=At(),g;t[8]!==p||t[9]!==o?.isGitRepo||t[10]!==d||t[11]!==a||t[12]!==r._tag||t[13]!==m||t[14]!==f?(g=(e,t)=>{if(t.ctrl&&e===`l`){Yb(),m(ex);return}if(t.ctrl&&e===`u`&&f){p(),process.stdout.write(gt),V(`npm`,[`install`,`-g`,`${yt}@latest`],{stdio:`inherit`});return}t.escape&&r._tag!==`Main`&&d(),t.ctrl&&e===`p`&&r._tag===`Main`&&o?.isGitRepo&&a(Jm.SelectPr()),t.ctrl&&e===`r`&&r._tag===`Main`&&a(Jm.SavedFlowPicker())},t[8]=p,t[9]=o?.isGitRepo,t[10]=d,t[11]=a,t[12]=r._tag,t[13]=m,t[14]=f,t[15]=g):g=t[15],te(g);let v;t[16]!==o||t[17]!==r._tag||t[18]!==r.baseUrls||t[19]!==r.changesFor||t[20]!==r.instruction||t[21]!==r.localReplayUrl||t[22]!==r.replayUrl||t[23]!==r.report||t[24]!==r.requiresCookies||t[25]!==r.savedFlow||t[26]!==r.videoUrl?(v=()=>{if(!o)return H(wb,{gitState:void 0});switch(r._tag){case`PortPicker`:return H(yv,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow,requiresCookies:r.requiresCookies});case`Testing`:return H(jy,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow,requiresCookies:r.requiresCookies,baseUrls:r.baseUrls});case`Results`:return H(Qy,{report:r.report,replayUrl:r.replayUrl,localReplayUrl:r.localReplayUrl,videoUrl:r.videoUrl});case`SelectPr`:return H($m,{});case`CookieSyncConfirm`:return H(rv,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow});case`SavedFlowPicker`:return H(sb,{});default:return H(wb,{gitState:o})}},t[16]=o,t[17]=r._tag,t[18]=r.baseUrls,t[19]=r.changesFor,t[20]=r.instruction,t[21]=r.localReplayUrl,t[22]=r.replayUrl,t[23]=r.report,t[24]=r.requiresCookies,t[25]=r.savedFlow,t[26]=r.videoUrl,t[27]=v):v=t[27];let y=v,b;t[28]===y?b=t[29]:(b=H(E,{flexGrow:1,children:y()}),t[28]=y,t[29]=b);let x;t[30]===Symbol.for(`react.memo_cache_sentinel`)?(x=H(Nb,{}),t[30]=x):x=t[30];let S;return t[31]!==h||t[32]!==b?(S=H(wt,{children:U(E,{flexDirection:`column`,width:`100%`,height:h,children:[b,x]})}),t[31]=h,t[32]=b,t[33]=S):S=t[33],S};function Zb(e){return e.screen}function Qb(e){return e.setScreen}function $b(e){return e.navigateTo}function ex(e){return e+1}const tx=()=>{let e=je();return e===`darwin`?`afplay /System/Library/Sounds/Glass.aiff`:e===`win32`?`powershell -c (New-Object Media.SoundPlayer 'C:\\Windows\\Media\\chimes.wav').PlaySync()`:`paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null || aplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null`},nx=()=>new Promise(e=>{B(tx(),()=>e())}),rx=e=>u.runPromise(ty(u.gen(function*(){let t=yield*Zp,n=yield*Qp,r=yield*q_,i=Date.now();yield*r.capture(`session:started`,{mode:`headless`,skip_planning:!1,browser_headed:e.headed}),console.log(`expect v${ht}`),console.log(`Testing ${gn(e.changesFor)}`),console.log(`Starting browser test...`);let a=Date.now();yield*r.capture(`run:started`,{plan_id:`direct`});let o=new Set,s=e=>{for(let t of e.events)if(!o.has(t.id))switch(o.add(t.id),t._tag){case`RunStarted`:console.log(`Starting ${t.plan.title}`);break;case`StepStarted`:console.log(`${W.arrowRight} ${t.stepId} ${t.title}`);break;case`StepCompleted`:console.log(` ${W.tick} ${t.stepId} ${t.summary}`);break;case`StepFailed`:console.log(` ${W.cross} ${t.stepId} ${t.message}`);break;case`StepSkipped`:console.log(` ${W.arrowRight} ${t.stepId} [skipped] ${t.reason}`);break}},c=yield*t.execute({changesFor:e.changesFor,instruction:e.instruction,isHeadless:!e.headed,requiresCookies:!1}).pipe(w.tap(e=>u.sync(()=>s(e))),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Zn({id:``,changesFor:e.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.instruction,baseUrl:void 0,isHeadless:!e.headed,requiresCookies:!1,testCoverage:_.none(),title:e.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock()));s(c);let l=yield*n.report(c),d=l.steps.filter(e=>l.stepStatuses.get(e.id)?.status===`passed`).length,f=l.steps.filter(e=>l.stepStatuses.get(e.id)?.status===`failed`).length;yield*r.capture(`run:completed`,{plan_id:c.id??`direct`,passed:d,failed:f,step_count:c.steps.length,file_count:0,duration_ms:Date.now()-a}),yield*r.capture(`session:ended`,{session_ms:Date.now()-i}),yield*r.flush,console.error(`\n${l.toPlainText}`),yield*u.promise(()=>nx()),process.exit(l.status===`passed`?0:1)}).pipe(u.provide(Qv({verbose:e.verbose,agent:e.agent}))))),ix={error:G.red,warn:G.yellow,info:G.cyan,success:G.green,dim:G.dim},$={error:(...e)=>{console.log(ix.error(e.join(` `)))},warn:(...e)=>{console.log(ix.warn(e.join(` `)))},info:(...e)=>{console.log(ix.info(e.join(` `)))},success:(...e)=>{console.log(ix.success(e.join(` `)))},dim:(...e)=>{console.log(ix.dim(e.join(` `)))},log:(...e)=>{console.log(e.join(` `))},break:()=>{console.log(``)}},ax=()=>{$.break(),$.log(`Cancelled.`),$.break(),process.exit(0)},ox=e=>pt(e,{onCancel:ax}),sx=(e,t)=>mt({text:e,isSilent:t?.silent}),cx=[`CI`,`CLAUDECODE`,`CURSOR_AGENT`,`CODEX_CI`,`OPENCODE`,`AMP_HOME`,`AMI`],lx=()=>cx.some(e=>!!process.env[e]),ux=()=>!process.stdin.isTTY,dx={npm:`npm install -g expect-cli@latest`,pnpm:`pnpm add -g expect-cli@latest`,yarn:`yarn global add expect-cli@latest`,bun:`bun add -g expect-cli@latest`,vp:`vp install -g expect-cli@latest`},fx={npm:`npx -y skills add https://github.com/millionco/expect --skill expect`,pnpm:`pnpm dlx skills add https://github.com/millionco/expect --skill expect`,yarn:`npx -y skills add https://github.com/millionco/expect --skill expect`,bun:`bunx skills add https://github.com/millionco/expect --skill expect`,vp:`npx -y skills add https://github.com/millionco/expect --skill expect`},px=()=>{if(process.env.VITE_PLUS_CLI_BIN)return`vp`;let e=process.env.npm_config_user_agent;if(e){if(e.startsWith(`pnpm`))return`pnpm`;if(e.startsWith(`yarn`))return`yarn`;if(e.startsWith(`bun`))return`bun`;if(e.startsWith(`npm`))return`npm`}return`npm`},mx=e=>e||lx()||ux(),hx=e=>new Promise(t=>{B(e,{timeout:1e4},e=>{t(!e)}).stdin?.end()}),gx=async(e={})=>{let t=mx(e.yes??!1),n=px(),r=dx[n];$.break(),$.log(` ${G.red(W.cross)}${G.green(W.tick)} ${G.bold(`Expect`)} ${ix.dim(`v${ht}`)}`),$.dim(` Let agents test your code in a real browser.`),$.break(),Ja().length===0&&($.error(`No supported coding agent found. expect requires one of: Claude Code, Codex, or Cursor.`),$.break(),$.log(` Install one to get started:`),$.log(` ${ix.info(`Claude Code`)} ${ix.dim(`https://docs.anthropic.com/en/docs/claude-code`)}`),$.log(` ${ix.info(`Codex`)} ${ix.dim(`https://github.com/openai/codex`)}`),$.log(` ${ix.info(`Cursor`)} ${ix.dim(`https://cursor.com`)}`),$.break(),process.exit(1));let i=sx(`Installing expect-cli globally...`).start();await hx(r)?i.succeed(`Installed! ${ix.info(`expect-cli`)} is now available globally.`):(i.fail(`Failed to install globally.`),$.dim(` Run manually: ${ix.info(r)}`)),$.break();let a=t;if(t||(a=(await ox({type:`confirm`,name:`installSkill`,message:`Install the ${ix.info(`expect`)} skill for your coding agent?`,initial:!0})).installSkill),a){let e=fx[n],t=sx(`Installing skill...`).start();await hx(e)?t.succeed(`Skill installed.`):(t.fail(`Failed to install skill.`),$.dim(` Run manually: ${ix.info(e)}`))}$.break(),$.success(`Setup complete! Here's how to get started:`),$.break(),$.log(` 1. ${ix.info(`cd`)} into your project directory`),$.log(` 2. Start your dev server (e.g. ${ix.dim(`npm run dev`)})`),$.log(` 3. Run ${ix.info(`expect-cli`)} to open the interactive test runner`),$.break(),$.log(` Or run headlessly from your coding agent:`),$.break(),$.log(` ${ix.dim(`$`)} ${ix.info(`expect-cli -m "test the login flow" -y`)}`),$.break(),$.log(` Set ${ix.info(`EXPECT_BASE_URL`)} if your app is not on localhost:3000:`),$.break(),$.log(` ${ix.dim(`$`)} ${ix.info(`EXPECT_BASE_URL=http://localhost:5173 expect-cli -m "test the homepage" -y`)}`),$.break()},_x=[`packages/*`,`apps/*`],vx=e=>vt.some(t=>e.includes(t)),yx=u.fn(`detectAgent`)(function*(e){let t=yield*p.FileSystem;for(let[n,r]of Object.entries(bt)){let i=K.join(e,n);if(yield*t.exists(i).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))return r}let n=K.join(e,`package.json`),r=yield*t.readFileString(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(r){let e=yield*u.try({try:()=>JSON.parse(r),catch:()=>({_tag:`JsonParseError`})}).pipe(u.catchTag(`JsonParseError`,()=>u.succeed(void 0)));if(e?.packageManager){let t=e.packageManager.split(`@`)[0];if(t)return t}}return`npm`}),bx=u.fn(`readPackageJson`)(function*(e){let t=yield*p.FileSystem,n=K.join(e,`package.json`),r=yield*t.readFileString(n);return yield*u.try({try:()=>JSON.parse(r),catch:()=>({_tag:`JsonParseError`})})}),xx=u.fn(`listWorkspaceDirectories`)(function*(e){let t=yield*p.FileSystem,n=[];for(let r of _x){let i=K.join(e,K.dirname(r)),a=yield*t.readDirectory(i).pipe(u.catchTag(`PlatformError`,()=>u.succeed([])));for(let e of a){let r=K.join(i,e);(yield*t.stat(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(void 0))))?.type===`Directory`&&n.push(r)}}return n}),Sx=(e,t,n)=>new Promise(r=>{se(e,[`run`,n],{cwd:t,timeout:12e4,maxBuffer:5*1024*1024},(e,t,i)=>{let a=(t+`
44
- `+i).trim();r({script:n,passed:!e,output:a})})}),Cx=u.fn(`discoverPackages`)(function*(e){let t=yield*xx(e),n=[];for(let e of t){let t=yield*bx(e).pipe(u.catchTag(`PlatformError`,()=>u.succeed(void 0)),u.catchTag(`JsonParseError`,()=>u.succeed(void 0)));if(!t?.scripts)continue;let r=Object.keys(t.scripts).filter(vx);r.length!==0&&n.push({packageName:t.name??K.basename(e),directory:e,scripts:r})}return n}),wx=async(e,t)=>{let n=u.gen(function*(){let n=yield*yx(e),r=yield*Cx(e);return yield*u.forEach(r,e=>u.gen(function*(){t.onPackageStart(e.packageName,e.scripts);let r=[];for(let i of e.scripts){let a=yield*u.promise(()=>Sx(n,e.directory,i));t.onScriptDone(e.packageName,a),r.push(a)}return{packageName:e.packageName,directory:e.directory,results:r}}),{concurrency:4})});return u.runPromise(n.pipe(u.provide(ye.layer)))},Tx=e=>{let t=re(5);if(t[0]!==`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`){for(let e=0;e<5;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`}let{statusMap:n}=e,r;if(t[1]!==n){let e=Array.from(n.entries()),i,a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(i=H(O,{bold:!0,children:`expect audit`}),a=H(O,{children:` `}),t[3]=i,t[4]=a):(i=t[3],a=t[4]),r=U(E,{flexDirection:`column`,paddingY:1,children:[i,a,e.map(Nx)]}),t[1]=n,t[2]=r}else r=t[2];return r},Ex=e=>{let t=re(12);if(t[0]!==`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`){for(let e=0;e<12;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`}let{results:n}=e,r=0,i=0;for(let e of n)for(let t of e.results)t.passed?r++:i++;let a=`${r} passed, ${i} failed`,o=i>0?Mt.RED:Mt.GREEN,s;t[1]!==a||t[2]!==o?(s=H(O,{bold:!0,color:o,children:a}),t[1]=a,t[2]=o,t[3]=s):s=t[3];let c;t[4]===i?c=t[5]:(c=i>0&&U(O,{color:Mt.YELLOW,children:[`Run `,H(O,{bold:!0,children:`expect`}),` to test your changes in a real browser and catch issues before they ship.`]}),t[4]=i,t[5]=c);let l;t[6]===i?l=t[7]:(l=i===0&&U(O,{color:Mt.GREEN,children:[`Looking good! Run `,H(O,{bold:!0,children:`expect`}),` to verify your changes work end-to-end in the browser.`]}),t[6]=i,t[7]=l);let u;return t[8]!==s||t[9]!==c||t[10]!==l?(u=U(E,{flexDirection:`column`,gap:1,children:[s,c,l]}),t[8]=s,t[9]=c,t[10]=l,t[11]=u):u=t[11],u},Dx=async()=>{let e=process.cwd(),t={current:new Map},n,r,i=k(H(()=>{let[e,t]=R(new Map),[i,a]=R();return n=e=>t(new Map(e)),r=a,U(E,{flexDirection:`column`,children:[H(Tx,{statusMap:e}),i&&H(Ex,{results:i})]})},{})),a=await wx(e,{onPackageStart:(e,r)=>{t.current.set(e,{scripts:r,completed:[],done:!1}),n?.(t.current)},onScriptDone:(e,r)=>{let i=t.current.get(e);i&&(i.completed.push(r),i.done=i.completed.length===i.scripts.length),n?.(t.current)}});r?.(a),setTimeout(()=>{i.unmount(),a.reduce((e,t)=>e+t.results.filter(e=>!e.passed).length,0)>0&&process.exit(1)},100)},Ox=async()=>{let e=process.cwd();console.log(``),console.log(G.bold(`expect audit`)),console.log(``);let t=await wx(e,{onPackageStart:(e,t)=>{console.log(`${W.arrowRight} ${G.bold(e)} (${t.join(`, `)})`)},onScriptDone:(e,t)=>{let n=t.passed?G.green(W.tick):G.red(W.cross);if(console.log(` ${n} ${t.script}`),!t.passed){let e=t.output.split(`
17
+ `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(e){e.inspectOpts={};let n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]}n.exports=no()(t);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
18
+ `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),so=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=ro():t.exports=oo()})),co=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0});let r=e(`fs`),i=n(so()).default(`@kwsites/file-exists`);function a(e,t,n){i(`checking %s`,e);try{let a=r.statSync(e);return a.isFile()&&t?(i(`[OK] path represents a file`),!0):a.isDirectory()&&n?(i(`[OK] path represents a directory`),!0):(i(`[FAIL] path represents something other than a file or directory`),!1)}catch(e){if(e.code===`ENOENT`)return i(`[FAIL] path is not accessible: %o`,e),!1;throw i(`[FATAL] %o`,e),e}}function o(e,n=t.READABLE){return a(e,(n&t.FILE)>0,(n&t.FOLDER)>0)}t.exists=o,t.FILE=1,t.FOLDER=2,t.READABLE=t.FILE+t.FOLDER})),lo=n((e=>{function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,`__esModule`,{value:!0}),t(co())})),uo=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDeferred=e.deferred=void 0;function t(){let e,t,n=`pending`;return{promise:new Promise((n,r)=>{e=n,t=r}),done(t){n===`pending`&&(n=`resolved`,e(t))},fail(e){n===`pending`&&(n=`rejected`,t(e))},get fulfilled(){return n!==`pending`},get status(){return n}}}e.deferred=t,e.createDeferred=t})),fo=lo(),po=t(so(),1),mo=uo(),ho=Object.defineProperty,go=Object.getOwnPropertyDescriptor,_o=Object.getOwnPropertyNames,vo=Object.prototype.hasOwnProperty,Y=(e,t)=>function(){return e&&(t=(0,e[_o(e)[0]])(e=0)),t},yo=(e,t)=>function(){return t||(0,e[_o(e)[0]])((t={exports:{}}).exports,t),t.exports},bo=(e,t)=>{for(var n in t)ho(e,n,{get:t[n],enumerable:!0})},xo=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of _o(t))!vo.call(e,i)&&i!==n&&ho(e,i,{get:()=>t[i],enumerable:!(r=go(t,i))||r.enumerable});return e},So=e=>xo(ho({},`__esModule`,{value:!0}),e);function Co(...e){let t=new String(e);return Eo.set(t,e),t}function wo(e){return e instanceof String&&Eo.has(e)}function To(e){return Eo.get(e)||[]}var Eo,Do=Y({"src/lib/args/pathspec.ts"(){Eo=new WeakMap}}),Oo,ko=Y({"src/lib/errors/git-error.ts"(){Oo=class extends Error{constructor(e,t){super(t),this.task=e,Object.setPrototypeOf(this,new.target.prototype)}}}}),Ao,jo=Y({"src/lib/errors/git-response-error.ts"(){ko(),Ao=class extends Oo{constructor(e,t){super(void 0,t||String(e)),this.git=e}}}}),Mo,No=Y({"src/lib/errors/task-configuration-error.ts"(){ko(),Mo=class extends Oo{constructor(e){super(void 0,e)}}}});function Po(e){return typeof e==`function`?e:ns}function Fo(e){return typeof e==`function`&&e!==ns}function Io(e,t){let n=e.indexOf(t);return n<=0?[e,``]:[e.substr(0,n),e.substr(n+1)]}function Lo(e,t=0){return zo(e)&&e.length>t?e[t]:void 0}function Ro(e,t=0){if(zo(e)&&e.length>t)return e[e.length-1-t]}function zo(e){return ps(e)}function Bo(e=``,t=!0,n=`
19
+ `){return e.split(n).reduce((e,n)=>{let r=t?n.trim():n;return r&&e.push(r),e},[])}function Vo(e,t){return Bo(e,!0).map(e=>t(e))}function Ho(e){return(0,fo.exists)(e,fo.FOLDER)}function Uo(e,t){return Array.isArray(e)?e.includes(t)||e.push(t):e.add(t),t}function Wo(e,t){return Array.isArray(e)&&!e.includes(t)&&e.push(t),e}function Go(e,t){if(Array.isArray(e)){let n=e.indexOf(t);n>=0&&e.splice(n,1)}else e.delete(t);return t}function Ko(e){return Array.isArray(e)?e:[e]}function qo(e){return e.replace(/[\s-]+(.)/g,(e,t)=>t.toUpperCase())}function Jo(e){return Ko(e).map(e=>e instanceof String?e:String(e))}function Yo(e,t=0){if(e==null)return t;let n=parseInt(e,10);return Number.isNaN(n)?t:n}function Xo(e,t){let n=[];for(let r=0,i=e.length;r<i;r++)n.push(t,e[r]);return n}function Zo(e){return(Array.isArray(e)?Te.concat(e):e).toString(`utf-8`)}function Qo(e,t){let n={};return t.forEach(t=>{e[t]!==void 0&&(n[t]=e[t])}),n}function $o(e=0){return new Promise(t=>setTimeout(t,e))}function es(e){if(e!==!1)return e}var ts,ns,rs,is=Y({"src/lib/utils/util.ts"(){ms(),ts=`\0`,ns=()=>{},rs=Object.prototype.toString.call.bind(Object.prototype.toString)}});function as(e,t,n){return t(e)?e:arguments.length>2?n:void 0}function os(e,t){let n=wo(e)?`string`:typeof e;return/number|string|boolean/.test(n)&&(!t||!t.includes(n))}function ss(e){return!!e&&rs(e)===`[object Object]`}function cs(e){return typeof e==`function`}var ls,us,ds,fs,ps,ms=Y({"src/lib/utils/argument-filters.ts"(){Do(),is(),ls=e=>Array.isArray(e),us=e=>typeof e==`number`,ds=e=>typeof e==`string`||wo(e),fs=e=>ds(e)||Array.isArray(e)&&e.every(ds),ps=e=>e==null||`number|boolean|function`.includes(typeof e)?!1:typeof e.length==`number`}}),hs,gs=Y({"src/lib/utils/exit-codes.ts"(){hs=(e=>(e[e.SUCCESS=0]=`SUCCESS`,e[e.ERROR=1]=`ERROR`,e[e.NOT_FOUND=-2]=`NOT_FOUND`,e[e.UNCLEAN=128]=`UNCLEAN`,e))(hs||{})}}),_s,vs=Y({"src/lib/utils/git-output-streams.ts"(){_s=class e{constructor(e,t){this.stdOut=e,this.stdErr=t}asStrings(){return new e(this.stdOut.toString(`utf8`),this.stdErr.toString(`utf8`))}}}});function ys(){throw Error(`LineParser:useMatches not implemented`)}var X,bs,xs=Y({"src/lib/utils/line-parser.ts"(){X=class{constructor(e,t){this.matches=[],this.useMatches=ys,this.parse=(e,t)=>(this.resetMatches(),this._regExp.every((t,n)=>this.addMatch(t,n,e(n)))?this.useMatches(t,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(e)?e:[e],t&&(this.useMatches=t)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(e,t,n){let r=n&&e.exec(n);return r&&this.pushMatch(t,r),!!r}pushMatch(e,t){this.matches.push(...t.slice(1))}},bs=class extends X{addMatch(e,t,n){return/^remote:\s/.test(String(n))&&super.addMatch(e,t,n)}pushMatch(e,t){(e>0||t.length>1)&&super.pushMatch(e,t)}}}});function Ss(...e){let t=process.cwd(),n=Object.assign({baseDir:t,...Cs},...e.filter(e=>typeof e==`object`&&e));return n.baseDir=n.baseDir||t,n.trimmed=n.trimmed===!0,n}var Cs,ws=Y({"src/lib/utils/simple-git-options.ts"(){Cs={binary:`git`,maxConcurrentProcesses:5,config:[],trimmed:!1}}});function Ts(e,t=[]){return ss(e)?Object.keys(e).reduce((t,n)=>{let r=e[n];if(wo(r))t.push(r);else if(os(r,[`boolean`]))t.push(n+`=`+r);else if(Array.isArray(r))for(let e of r)os(e,[`string`,`number`])||t.push(n+`=`+e);else t.push(n);return t},t):t}function Es(e,t=0,n=!1){let r=[];for(let n=0,i=t<0?e.length:t;n<i;n++)`string|number`.includes(typeof e[n])&&r.push(String(e[n]));return Ts(Os(e),r),n||r.push(...Ds(e)),r}function Ds(e){return Jo(as(Ro(e,typeof Ro(e)==`function`?1:0),ls,[]))}function Os(e){return as(Ro(e,cs(Ro(e))?1:0),ss)}function ks(e,t=!0){let n=Po(Ro(e));return t||Fo(n)?n:void 0}var As=Y({"src/lib/utils/task-options.ts"(){ms(),is(),Do()}});function js(e,t){return e(t.stdOut,t.stdErr)}function Ms(e,t,n,r=!0){return Ko(n).forEach(n=>{for(let i=Bo(n,r),a=0,o=i.length;a<o;a++){let n=(e=0)=>{if(!(a+e>=o))return i[a+e]};t.some(({parse:t})=>t(n,e))}}),e}var Ns=Y({"src/lib/utils/task-parser.ts"(){is()}}),Ps={};bo(Ps,{ExitCodes:()=>hs,GitOutputStreams:()=>_s,LineParser:()=>X,NOOP:()=>ns,NULL:()=>ts,RemoteLineParser:()=>bs,append:()=>Uo,appendTaskOptions:()=>Ts,asArray:()=>Ko,asCamelCase:()=>qo,asFunction:()=>Po,asNumber:()=>Yo,asStringArray:()=>Jo,bufferToString:()=>Zo,callTaskParser:()=>js,createInstanceConfig:()=>Ss,delay:()=>$o,filterArray:()=>ls,filterFunction:()=>cs,filterHasLength:()=>ps,filterNumber:()=>us,filterPlainObject:()=>ss,filterPrimitives:()=>os,filterString:()=>ds,filterStringOrStringArray:()=>fs,filterType:()=>as,first:()=>Lo,folderExists:()=>Ho,forEachLineWithContent:()=>Vo,getTrailingOptions:()=>Es,including:()=>Wo,isUserFunction:()=>Fo,last:()=>Ro,objectToString:()=>rs,orVoid:()=>es,parseStringResponse:()=>Ms,pick:()=>Qo,prefixedArray:()=>Xo,remove:()=>Go,splitOn:()=>Io,toLinesWithContent:()=>Bo,trailingFunctionArgument:()=>ks,trailingOptionsArgument:()=>Os});var Z=Y({"src/lib/utils/index.ts"(){ms(),gs(),vs(),xs(),ws(),As(),Ns(),is()}}),Fs={};bo(Fs,{CheckRepoActions:()=>Bs,checkIsBareRepoTask:()=>Rs,checkIsRepoRootTask:()=>Ls,checkIsRepoTask:()=>Is});function Is(e){switch(e){case`bare`:return Rs();case`root`:return Ls()}return{commands:[`rev-parse`,`--is-inside-work-tree`],format:`utf-8`,onError:Vs,parser:Hs}}function Ls(){return{commands:[`rev-parse`,`--git-dir`],format:`utf-8`,onError:Vs,parser(e){return/^\.(git)?$/.test(e.trim())}}}function Rs(){return{commands:[`rev-parse`,`--is-bare-repository`],format:`utf-8`,onError:Vs,parser:Hs}}function zs(e){return/(Not a git repository|Kein Git-Repository)/i.test(String(e))}var Bs,Vs,Hs,Us=Y({"src/lib/tasks/check-is-repo.ts"(){Z(),Bs=(e=>(e.BARE=`bare`,e.IN_TREE=`tree`,e.IS_REPO_ROOT=`root`,e))(Bs||{}),Vs=({exitCode:e},t,n,r)=>{if(e===128&&zs(t))return n(Buffer.from(`false`));r(t)},Hs=e=>e.trim()===`true`}});function Ws(e,t){let n=new Gs(e),r=e?qs:Ks;return Bo(t).forEach(e=>{let t=e.replace(r,``);n.paths.push(t),(Js.test(t)?n.folders:n.files).push(t)}),n}var Gs,Ks,qs,Js,Ys=Y({"src/lib/responses/CleanSummary.ts"(){Z(),Gs=class{constructor(e){this.dryRun=e,this.paths=[],this.files=[],this.folders=[]}},Ks=/^[a-z]+\s*/i,qs=/^[a-z]+\s+[a-z]+\s*/i,Js=/\/$/}}),Xs={};bo(Xs,{EMPTY_COMMANDS:()=>rc,adhocExecTask:()=>Zs,configurationErrorTask:()=>Qs,isBufferTask:()=>tc,isEmptyTask:()=>nc,straightThroughBufferTask:()=>ec,straightThroughStringTask:()=>$s});function Zs(e){return{commands:rc,format:`empty`,parser:e}}function Qs(e){return{commands:rc,format:`empty`,parser(){throw typeof e==`string`?new Mo(e):e}}}function $s(e,t=!1){return{commands:e,format:`utf-8`,parser(e){return t?String(e).trim():e}}}function ec(e){return{commands:e,format:`buffer`,parser(e){return e}}}function tc(e){return e.format===`buffer`}function nc(e){return e.format===`empty`||!e.commands.length}var rc,ic=Y({"src/lib/tasks/task.ts"(){No(),rc=[]}}),ac={};bo(ac,{CONFIG_ERROR_INTERACTIVE_MODE:()=>pc,CONFIG_ERROR_MODE_REQUIRED:()=>mc,CONFIG_ERROR_UNKNOWN_OPTION:()=>hc,CleanOptions:()=>gc,cleanTask:()=>sc,cleanWithOptionsTask:()=>oc,isCleanOptionsArray:()=>cc});function oc(e,t){let{cleanMode:n,options:r,valid:i}=lc(e);return n?i.options?(r.push(...t),r.some(fc)?Qs(pc):sc(n,r)):Qs(hc+JSON.stringify(e)):Qs(mc)}function sc(e,t){return{commands:[`clean`,`-${e}`,...t],format:`utf-8`,parser(t){return Ws(e===`n`,t)}}}function cc(e){return Array.isArray(e)&&e.every(e=>_c.has(e))}function lc(e){let t,n=[],r={cleanMode:!1,options:!0};return e.replace(/[^a-z]i/g,``).split(``).forEach(e=>{uc(e)?(t=e,r.cleanMode=!0):r.options=r.options&&dc(n[n.length]=`-${e}`)}),{cleanMode:t,options:n,valid:r}}function uc(e){return e===`f`||e===`n`}function dc(e){return/^-[a-z]$/i.test(e)&&_c.has(e.charAt(1))}function fc(e){return/^-[^\-]/.test(e)?e.indexOf(`i`)>0:e===`--interactive`}var pc,mc,hc,gc,_c,vc=Y({"src/lib/tasks/clean.ts"(){Ys(),Z(),ic(),pc=`Git clean interactive mode is not supported`,mc=`Git clean mode parameter ("n" or "f") is required`,hc=`Git clean unknown option found in: `,gc=(e=>(e.DRY_RUN=`n`,e.FORCE=`f`,e.IGNORED_INCLUDED=`x`,e.IGNORED_ONLY=`X`,e.EXCLUDING=`e`,e.QUIET=`q`,e.RECURSIVE=`d`,e))(gc||{}),_c=new Set([`i`,...Jo(Object.values(gc))])}});function yc(e){let t=new Cc;for(let n of Sc(e))t.addValue(n.file,String(n.key),n.value);return t}function bc(e,t){let n=null,r=[],i=new Map;for(let a of Sc(e,t))a.key===t&&(r.push(n=a.value),i.has(a.file)||i.set(a.file,[]),i.get(a.file).push(n));return{key:t,paths:Array.from(i.keys()),scopes:i,value:n,values:r}}function xc(e){return e.replace(/^(file):/,``)}function*Sc(e,t=null){let n=e.split(`\0`);for(let e=0,r=n.length-1;e<r;){let r=xc(n[e++]),i=n[e++],a=t;if(i.includes(`
20
+ `)){let e=Io(i,`
21
+ `);a=e[0],i=e[1]}yield{file:r,key:a,value:i}}}var Cc,wc=Y({"src/lib/responses/ConfigList.ts"(){Z(),Cc=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){return this._all||=this.files.reduce((e,t)=>Object.assign(e,this.values[t]),{}),this._all}addFile(e){if(!(e in this.values)){let t=Ro(this.files);this.values[e]=t?Object.create(this.values[t]):{},this.files.push(e)}return this.values[e]}addValue(e,t,n){let r=this.addFile(e);Object.hasOwn(r,t)?Array.isArray(r[t])?r[t].push(n):r[t]=[r[t],n]:r[t]=n,this._all=void 0}}}});function Tc(e,t){return typeof e==`string`&&Object.hasOwn(Ac,e)?e:t}function Ec(e,t,n,r){let i=[`config`,`--${r}`];return n&&i.push(`--add`),i.push(e,t),{commands:i,format:`utf-8`,parser(e){return e}}}function Dc(e,t){let n=[`config`,`--null`,`--show-origin`,`--get-all`,e];return t&&n.splice(1,0,`--${t}`),{commands:n,format:`utf-8`,parser(t){return bc(t,e)}}}function Oc(e){let t=[`config`,`--list`,`--show-origin`,`--null`];return e&&t.push(`--${e}`),{commands:t,format:`utf-8`,parser(e){return yc(e)}}}function kc(){return{addConfig(e,t,...n){return this._runTask(Ec(e,t,n[0]===!0,Tc(n[1],`local`)),ks(arguments))},getConfig(e,t){return this._runTask(Dc(e,Tc(t,void 0)),ks(arguments))},listConfig(...e){return this._runTask(Oc(Tc(e[0],void 0)),ks(arguments))}}}var Ac,jc=Y({"src/lib/tasks/config.ts"(){wc(),Z(),Ac=(e=>(e.system=`system`,e.global=`global`,e.local=`local`,e.worktree=`worktree`,e))(Ac||{})}});function Mc(e){return Pc.has(e)}var Nc,Pc,Fc=Y({"src/lib/tasks/diff-name-status.ts"(){Nc=(e=>(e.ADDED=`A`,e.COPIED=`C`,e.DELETED=`D`,e.MODIFIED=`M`,e.RENAMED=`R`,e.CHANGED=`T`,e.UNMERGED=`U`,e.UNKNOWN=`X`,e.BROKEN=`B`,e))(Nc||{}),Pc=new Set(Object.values(Nc))}});function Ic(...e){return new Hc().param(...e)}function Lc(e){let t=new Set,n={};return Vo(e,e=>{let[r,i,a]=e.split(ts);t.add(r),(n[r]=n[r]||[]).push({line:Yo(i),path:r,preview:a})}),{paths:t,results:n}}function Rc(){return{grep(e){let t=ks(arguments),n=Es(arguments);for(let e of zc)if(n.includes(e))return this._runTask(Qs(`git.grep: use of "${e}" is not supported.`),t);typeof e==`string`&&(e=Ic().param(e));let r=[`grep`,`--null`,`-n`,`--full-name`,...n,...e];return this._runTask({commands:r,format:`utf-8`,parser(e){return Lc(e)}},t)}}}var zc,Bc,Vc,Hc,Uc=Y({"src/lib/tasks/grep.ts"(){Z(),ic(),zc=[`-h`],Bc=Symbol(`grepQuery`),Hc=class{constructor(){this[Vc]=[]}*[(Vc=Bc,Symbol.iterator)](){for(let e of this[Bc])yield e}and(...e){return e.length&&this[Bc].push(`--and`,`(`,...Xo(e,`-e`),`)`),this}param(...e){return this[Bc].push(...Xo(e,`-e`)),this}}}}),Wc={};bo(Wc,{ResetMode:()=>Jc,getResetMode:()=>Kc,resetTask:()=>Gc});function Gc(e,t){let n=[`reset`];return qc(e)&&n.push(`--${e}`),n.push(...t),$s(n)}function Kc(e){if(qc(e))return e;switch(typeof e){case`string`:case`undefined`:return`soft`}}function qc(e){return typeof e==`string`&&Yc.includes(e)}var Jc,Yc,Xc=Y({"src/lib/tasks/reset.ts"(){Z(),ic(),Jc=(e=>(e.MIXED=`mixed`,e.SOFT=`soft`,e.HARD=`hard`,e.MERGE=`merge`,e.KEEP=`keep`,e))(Jc||{}),Yc=Jo(Object.values(Jc))}});function Zc(){return(0,po.default)(`simple-git`)}function Qc(e,t,n){return!t||!String(t).replace(/\s*/,``)?n?(t,...r)=>{e(t,...r),n(t,...r)}:e:(r,...i)=>{e(`%s ${r}`,t,...i),n&&n(r,...i)}}function $c(e,t,{namespace:n}){if(typeof e==`string`)return e;let r=t&&t.namespace||``;return r.startsWith(n)?r.substr(n.length+1):r||n}function el(e,t,n,r=Zc()){let i=e&&`[${e}]`||``,a=[],o=typeof t==`string`?r.extend(t):t,s=$c(as(t,ds),o,r);return l(n);function c(t,n){return Uo(a,el(e,s.replace(/^[^:]+/,t),n,r))}function l(t){let n=t&&`[${t}]`||``,a=o&&Qc(o,n)||ns,s=Qc(r,`${i} ${n}`,a);return Object.assign(o?a:s,{label:e,sibling:c,info:s,step:l})}}var tl=Y({"src/lib/git-logger.ts"(){Z(),po.default.formatters.L=e=>String(ps(e)?e.length:`-`),po.default.formatters.B=e=>Buffer.isBuffer(e)?e.toString(`utf8`):rs(e)}}),nl,rl=Y({"src/lib/runners/tasks-pending-queue.ts"(){ko(),tl(),nl=class e{constructor(e=`GitExecutor`){this.logLabel=e,this._queue=new Map}withProgress(e){return this._queue.get(e)}createProgress(t){let n=e.getName(t.commands[0]);return{task:t,logger:el(this.logLabel,n),name:n}}push(e){let t=this.createProgress(e);return t.logger(`Adding task to the queue, commands = %o`,e.commands),this._queue.set(e,t),t}fatal(e){for(let[t,{logger:n}]of Array.from(this._queue.entries()))t===e.task?(n.info(`Failed %o`,e),n(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`)):n.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`,e.message),this.complete(t);if(this._queue.size!==0)throw Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(e){this.withProgress(e)&&this._queue.delete(e)}attempt(e){let t=this.withProgress(e);if(!t)throw new Oo(void 0,`TasksPendingQueue: attempt called for an unknown task`);return t.logger(`Starting task`),t}static getName(t=`empty`){return`task:${t}:${++e.counter}`}static{this.counter=0}}}});function il(e,t){return{method:Lo(e.commands)||``,commands:t}}function al(e,t){return n=>{t(`[ERROR] child process exception %o`,n),e.push(Buffer.from(String(n.stack),`ascii`))}}function ol(e,t,n,r){return i=>{n(`%s received %L bytes`,t,i),r(`%B`,i),e.push(i)}}var sl,cl=Y({"src/lib/runners/git-executor-chain.ts"(){ko(),ic(),Z(),rl(),sl=class{constructor(e,t,n){this._executor=e,this._scheduler=t,this._plugins=n,this._chain=Promise.resolve(),this._queue=new nl}get cwd(){return this._cwd||this._executor.cwd}set cwd(e){this._cwd=e}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(e){return this._queue.push(e),this._chain=this._chain.then(()=>this.attemptTask(e))}async attemptTask(e){let t=await this._scheduler.next(),n=()=>this._queue.complete(e);try{let{logger:t}=this._queue.attempt(e);return await(nc(e)?this.attemptEmptyTask(e,t):this.attemptRemoteTask(e,t))}catch(t){throw this.onFatalException(e,t)}finally{n(),t()}}onFatalException(e,t){let n=t instanceof Oo?Object.assign(t,{task:e}):new Oo(e,t&&String(t));return this._chain=Promise.resolve(),this._queue.fatal(n),n}async attemptRemoteTask(e,t){let n=this._plugins.exec(`spawn.binary`,``,il(e,e.commands)),r=this._plugins.exec(`spawn.args`,[...e.commands],il(e,e.commands)),i=await this.gitResponse(e,n,r,this.outputHandler,t.step(`SPAWN`)),a=await this.handleTaskData(e,r,i,t.step(`HANDLE`));return t(`passing response to task's parser as a %s`,e.format),tc(e)?js(e.parser,a):js(e.parser,a.asStrings())}async attemptEmptyTask(e,t){return t(`empty task bypassing child process to call to task's parser`),e.parser(this)}handleTaskData(e,t,n,r){let{exitCode:i,rejection:a,stdOut:o,stdErr:s}=n;return new Promise((c,l)=>{r(`Preparing to handle process response exitCode=%d stdOut=`,i);let{error:u}=this._plugins.exec(`task.error`,{error:a},{...il(e,t),...n});if(u&&e.onError)return r.info(`exitCode=%s handling with custom error handler`),e.onError(n,u,e=>{r.info(`custom error handler treated as success`),r(`custom error returned a %s`,rs(e)),c(new _s(Array.isArray(e)?Buffer.concat(e):e,Buffer.concat(s)))},l);if(u)return r.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`,i,s.length,a),l(u);r.info(`retrieving task output complete`),c(new _s(Buffer.concat(o),Buffer.concat(s)))})}async gitResponse(e,t,n,r,i){let a=i.sibling(`output`),o=this._plugins.exec(`spawn.options`,{cwd:this.cwd,env:this.env,windowsHide:!0},il(e,e.commands));return new Promise(s=>{let c=[],l=[];i.info(`%s %o`,t,n),i(`%O`,o);let u=this._beforeSpawn(e,n);if(u)return s({stdOut:c,stdErr:l,exitCode:9901,rejection:u});this._plugins.exec(`spawn.before`,void 0,{...il(e,n),kill(e){u=e||u}});let d=De(t,n,o);d.stdout.on(`data`,ol(c,`stdOut`,i,a.step(`stdOut`))),d.stderr.on(`data`,ol(l,`stdErr`,i,a.step(`stdErr`))),d.on(`error`,al(l,i)),r&&(i(`Passing child process stdOut/stdErr to custom outputHandler`),r(t,d.stdout,d.stderr,[...n])),this._plugins.exec(`spawn.after`,void 0,{...il(e,n),spawned:d,close(e,t){s({stdOut:c,stdErr:l,exitCode:e,rejection:u||t})},kill(e){d.killed||(u=e,d.kill(`SIGINT`))}})})}_beforeSpawn(e,t){let n;return this._plugins.exec(`spawn.before`,void 0,{...il(e,t),kill(e){n=e||n}}),n}}}}),ll={};bo(ll,{GitExecutor:()=>ul});var ul,dl=Y({"src/lib/runners/git-executor.ts"(){cl(),ul=class{constructor(e,t,n){this.cwd=e,this._scheduler=t,this._plugins=n,this._chain=new sl(this,this._scheduler,this._plugins)}chain(){return new sl(this,this._scheduler,this._plugins)}push(e){return this._chain.push(e)}}}});function fl(e,t,n=ns){t.then(e=>{n(null,e)},t=>{t?.task===e&&n(t instanceof Ao?pl(t):t,void 0)})}function pl(e){let t=e=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${e} should be GitResponseError.git.${e}, this will no longer be available in version 3`),t=ns};return Object.create(e,Object.getOwnPropertyNames(e.git).reduce(n,{}));function n(n,r){return r in e||(n[r]={enumerable:!1,configurable:!1,get(){return t(r),e.git[r]}}),n}}var ml=Y({"src/lib/task-callback.ts"(){jo(),Z()}});function hl(e,t){return Zs(n=>{if(!Ho(e))throw Error(`Git.cwd: cannot change to non-directory "${e}"`);return(t||n).cwd=e})}var gl=Y({"src/lib/tasks/change-working-directory.ts"(){Z(),ic()}});function _l(e){let t=[`checkout`,...e];return t[1]===`-b`&&t.includes(`-B`)&&(t[1]=Go(t,`-B`)),$s(t)}function vl(){return{checkout(){return this._runTask(_l(Es(arguments,1)),ks(arguments))},checkoutBranch(e,t){return this._runTask(_l([`-b`,e,t,...Es(arguments)]),ks(arguments))},checkoutLocalBranch(e){return this._runTask(_l([`-b`,e,...Es(arguments)]),ks(arguments))}}}var yl=Y({"src/lib/tasks/checkout.ts"(){Z(),ic()}});function bl(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function xl(){return{countObjects(){return this._runTask({commands:[`count-objects`,`--verbose`],format:`utf-8`,parser(e){return Ms(bl(),[Sl],e)}})}}}var Sl,Cl=Y({"src/lib/tasks/count-objects.ts"(){Z(),Sl=new X(/([a-z-]+): (\d+)$/,(e,[t,n])=>{let r=qo(t);Object.hasOwn(e,r)&&(e[r]=Yo(n))})}});function wl(e){return Ms({author:null,branch:``,commit:``,root:!1,summary:{changes:0,insertions:0,deletions:0}},Tl,e)}var Tl,El=Y({"src/lib/parsers/parse-commit.ts"(){Z(),Tl=[new X(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(e,[t,n,r])=>{e.branch=t,e.commit=r,e.root=!!n}),new X(/\s*Author:\s(.+)/i,(e,[t])=>{let n=t.split(`<`),r=n.pop();!r||!r.includes(`@`)||(e.author={email:r.substr(0,r.length-1),name:n.join(`<`).trim()})}),new X(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0,e.summary.insertions=parseInt(n,10)||0,e.summary.deletions=parseInt(r,10)||0}),new X(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(e,[t,n,r])=>{e.summary.changes=parseInt(t,10)||0;let i=parseInt(n,10)||0;r===`-`?e.summary.deletions=i:r===`+`&&(e.summary.insertions=i)})]}});function Dl(e,t,n){return{commands:[`-c`,`core.abbrev=40`,`commit`,...Xo(e,`-m`),...t,...n],format:`utf-8`,parser:wl}}function Ol(){return{commit(t,...n){let r=ks(arguments),i=e(t)||Dl(Ko(t),Ko(as(n[0],fs,[])),[...Jo(as(n[1],ls,[])),...Es(arguments,0,!0)]);return this._runTask(i,r)}};function e(e){return!fs(e)&&Qs(`git.commit: requires the commit message to be supplied as a string/string[]`)}}var kl=Y({"src/lib/tasks/commit.ts"(){El(),Z(),ic()}});function Al(){return{firstCommit(){return this._runTask($s([`rev-list`,`--max-parents=0`,`HEAD`],!0),ks(arguments))}}}var jl=Y({"src/lib/tasks/first-commit.ts"(){Z(),ic()}});function Ml(e,t){let n=[`hash-object`,e];return t&&n.push(`-w`),$s(n,!0)}var Nl=Y({"src/lib/tasks/hash-object.ts"(){ic()}});function Pl(e,t,n){let r=String(n).trim(),i;if(i=Il.exec(r))return new Fl(e,t,!1,i[1]);if(i=Ll.exec(r))return new Fl(e,t,!0,i[1]);let a=``,o=r.split(` `);for(;o.length;)if(o.shift()===`in`){a=o.join(` `);break}return new Fl(e,t,/^re/i.test(r),a)}var Fl,Il,Ll,Rl=Y({"src/lib/responses/InitSummary.ts"(){Fl=class{constructor(e,t,n,r){this.bare=e,this.path=t,this.existing=n,this.gitDir=r}},Il=/^Init.+ repository in (.+)$/,Ll=/^Rein.+ in (.+)$/}});function zl(e){return e.includes(Vl)}function Bl(e=!1,t,n){let r=[`init`,...n];return e&&!zl(r)&&r.splice(1,0,Vl),{commands:r,format:`utf-8`,parser(e){return Pl(r.includes(`--bare`),t,e)}}}var Vl,Hl=Y({"src/lib/tasks/init.ts"(){Rl(),Vl=`--bare`}});function Ul(e){for(let t=0;t<e.length;t++){let n=Gl.exec(e[t]);if(n)return`--${n[1]}`}return``}function Wl(e){return Gl.test(e)}var Gl,Kl=Y({"src/lib/args/log-format.ts"(){Gl=/^--(stat|numstat|name-only|name-status)(=|$)/}}),ql,Jl=Y({"src/lib/responses/DiffSummary.ts"(){ql=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function Yl(e=``){let t=eu[e];return e=>Ms(new ql,t,e,!1)}var Xl,Zl,Ql,$l,eu,tu=Y({"src/lib/parsers/parse-diff-summary.ts"(){Kl(),Jl(),Fc(),Z(),Xl=[new X(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(e,[t,n,r=``])=>{e.files.push({file:t.trim(),changes:Yo(n),insertions:r.replace(/[^+]/g,``).length,deletions:r.replace(/[^-]/g,``).length,binary:!1})}),new X(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(e,[t,n,r])=>{e.files.push({file:t.trim(),before:Yo(n),after:Yo(r),binary:!0})}),new X(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(e,[t,n])=>{let r=/(\d+) i/.exec(n),i=/(\d+) d/.exec(n);e.changed=Yo(t),e.insertions=Yo(r?.[1]),e.deletions=Yo(i?.[1])})],Zl=[new X(/(\d+)\t(\d+)\t(.+)$/,(e,[t,n,r])=>{let i=Yo(t),a=Yo(n);e.changed++,e.insertions+=i,e.deletions+=a,e.files.push({file:r,changes:i+a,insertions:i,deletions:a,binary:!1})}),new X(/-\t-\t(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,after:0,before:0,binary:!0})})],Ql=[new X(/(.+)$/,(e,[t])=>{e.changed++,e.files.push({file:t,changes:0,insertions:0,deletions:0,binary:!1})})],$l=[new X(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(e,[t,n,r,i,a])=>{e.changed++,e.files.push({file:a??r,changes:0,insertions:0,deletions:0,binary:!1,status:es(Mc(t)&&t),from:es(!!a&&r!==a&&r),similarity:Yo(n)})})],eu={"":Xl,"--stat":Xl,"--numstat":Zl,"--name-status":$l,"--name-only":Ql}}});function nu(e,t){return t.reduce((t,n,r)=>(t[n]=e[r]||``,t),Object.create({diff:null}))}function ru(e=ou,t=su,n=``){let r=Yl(n);return function(n){let i=Bo(n.trim(),!1,iu).map(function(n){let i=n.split(au),a=nu(i[0].split(e),t);return i.length>1&&i[1].trim()&&(a.diff=r(i[1])),a});return{all:i,latest:i.length&&i[0]||null,total:i.length}}}var iu,au,ou,su,cu=Y({"src/lib/parsers/parse-list-log-summary.ts"(){Z(),tu(),Kl(),iu=`òòòòòò `,au=` òò`,ou=` ò `,su=[`hash`,`date`,`message`,`refs`,`author_name`,`author_email`]}}),lu={};bo(lu,{diffSummaryTask:()=>uu,validateLogFormatConfig:()=>du});function uu(e){let t=Ul(e),n=[`diff`];return t===``&&(t=`--stat`,n.push(`--stat=4096`)),n.push(...e),du(n)||{commands:n,format:`utf-8`,parser:Yl(t)}}function du(e){let t=e.filter(Wl);if(t.length>1)return Qs(`Summary flags are mutually exclusive - pick one of ${t.join(`,`)}`);if(t.length&&e.includes(`-z`))return Qs(`Summary flag ${t} parsing is not compatible with null termination option '-z'`)}var fu=Y({"src/lib/tasks/diff.ts"(){Kl(),tu(),ic()}});function pu(e,t){let n=[],r=[];return Object.keys(e).forEach(t=>{n.push(t),r.push(String(e[t]))}),[n,r.join(t)]}function mu(e){return Object.keys(e).reduce((t,n)=>(n in vu||(t[n]=e[n]),t),{})}function hu(e={},t=[]){let n=as(e.splitter,ds,ou),[r,i]=pu(ss(e.format)?e.format:{hash:`%H`,date:e.strictDate===!1?`%ai`:`%aI`,message:`%s`,refs:`%D`,body:e.multiLine?`%B`:`%b`,author_name:e.mailMap===!1?`%an`:`%aN`,author_email:e.mailMap===!1?`%ae`:`%aE`},n),a=[],o=[`--pretty=format:${iu}${i}${au}`,...t],s=e.n||e[`max-count`]||e.maxCount;if(s&&o.push(`--max-count=${s}`),e.from||e.to){let t=e.symmetric===!1?`..`:`...`;a.push(`${e.from||``}${t}${e.to||``}`)}return ds(e.file)&&o.push(`--follow`,Co(e.file)),Ts(mu(e),o),{fields:r,splitter:n,commands:[...o,...a]}}function gu(e,t,n){let r=ru(e,t,Ul(n));return{commands:[`log`,...n],format:`utf-8`,parser:r}}function _u(){return{log(...n){let r=ks(arguments),i=hu(Os(arguments),Jo(as(arguments[0],ls,[]))),a=t(...n)||du(i.commands)||e(i);return this._runTask(a,r)}};function e(e){return gu(e.splitter,e.fields,e.commands)}function t(e,t){return ds(e)&&ds(t)&&Qs(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`)}}var vu,yu=Y({"src/lib/tasks/log.ts"(){Kl(),Do(),cu(),Z(),ic(),fu(),vu=(e=>(e[e[`--pretty`]=0]=`--pretty`,e[e[`max-count`]=1]=`max-count`,e[e.maxCount=2]=`maxCount`,e[e.n=3]=`n`,e[e.file=4]=`file`,e[e.format=5]=`format`,e[e.from=6]=`from`,e[e.to=7]=`to`,e[e.splitter=8]=`splitter`,e[e.symmetric=9]=`symmetric`,e[e.mailMap=10]=`mailMap`,e[e.multiLine=11]=`multiLine`,e[e.strictDate=12]=`strictDate`,e))(vu||{})}}),bu,xu,Su=Y({"src/lib/responses/MergeSummary.ts"(){bu=class{constructor(e,t=null,n){this.reason=e,this.file=t,this.meta=n}toString(){return`${this.file}:${this.reason}`}},xu=class{constructor(){this.conflicts=[],this.merges=[],this.result=`success`}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(`, `)}`:`OK`}}}}),Cu,wu,Tu=Y({"src/lib/responses/PullSummary.ts"(){Cu=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},wu=class{constructor(){this.remote=``,this.hash={local:``,remote:``},this.branch={local:``,remote:``},this.message=``}toString(){return this.message}}}});function Eu(e){return e.objects=e.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function Du(e){let t=/^\s*(\d+)/.exec(e),n=/delta (\d+)/i.exec(e);return{count:Yo(t&&t[1]||`0`),delta:Yo(n&&n[1]||`0`)}}var Ou,ku=Y({"src/lib/parsers/parse-remote-objects.ts"(){Z(),Ou=[new bs(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(e,[t,n])=>{let r=t.toLowerCase(),i=Eu(e.remoteMessages);Object.assign(i,{[r]:Yo(n)})}),new bs(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(e,[t,n])=>{let r=t.toLowerCase(),i=Eu(e.remoteMessages);Object.assign(i,{[r]:Yo(n)})}),new bs(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(e,[t,n,r])=>{let i=Eu(e.remoteMessages);i.total=Du(t),i.reused=Du(n),i.packReused=Yo(r)})]}});function Au(e,t){return Ms({remoteMessages:new Mu},ju,t)}var ju,Mu,Nu=Y({"src/lib/parsers/parse-remote-messages.ts"(){Z(),ku(),ju=[new bs(/^remote:\s*(.+)$/,(e,[t])=>(e.remoteMessages.all.push(t.trim()),!1)),...Ou,new bs([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(e,[t])=>{e.remoteMessages.pullRequestUrl=t}),new bs([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(e,[t,n,r])=>{e.remoteMessages.vulnerabilities={count:Yo(t),summary:n,url:r}})],Mu=class{constructor(){this.all=[]}}}});function Pu(e,t){let n=Ms(new wu,zu,[e,t]);return n.message&&n}var Fu,Iu,Lu,Ru,zu,Bu,Vu,Hu=Y({"src/lib/parsers/parse-pull.ts"(){Tu(),Z(),Nu(),Fu=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,Iu=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,Lu=/^(create|delete) mode \d+ (.+)/,Ru=[new X(Fu,(e,[t,n,r])=>{e.files.push(t),n&&(e.insertions[t]=n.length),r&&(e.deletions[t]=r.length)}),new X(Iu,(e,[t,,n,,r])=>n!==void 0||r!==void 0?(e.summary.changes=+t||0,e.summary.insertions=+n||0,e.summary.deletions=+r||0,!0):!1),new X(Lu,(e,[t,n])=>{Uo(e.files,n),Uo(t===`create`?e.created:e.deleted,n)})],zu=[new X(/^from\s(.+)$/i,(e,[t])=>void(e.remote=t)),new X(/^fatal:\s(.+)$/,(e,[t])=>void(e.message=t)),new X(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(e,[t,n,r,i])=>{e.branch.local=r,e.hash.local=t,e.branch.remote=i,e.hash.remote=n})],Bu=(e,t)=>Ms(new Cu,Ru,[e,t]),Vu=(e,t)=>Object.assign(new Cu,Bu(e,t),Au(e,t))}}),Uu,Wu,Gu,Ku=Y({"src/lib/parsers/parse-merge.ts"(){Su(),Z(),Hu(),Uu=[new X(/^Auto-merging\s+(.+)$/,(e,[t])=>{e.merges.push(t)}),new X(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(e,[t,n])=>{e.conflicts.push(new bu(t,n))}),new X(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(e,[t,n,r])=>{e.conflicts.push(new bu(t,n,{deleteRef:r}))}),new X(/^CONFLICT\s+\((.+)\):/,(e,[t])=>{e.conflicts.push(new bu(t,null))}),new X(/^Automatic merge failed;\s+(.+)$/,(e,[t])=>{e.result=t})],Wu=(e,t)=>Object.assign(Gu(e,t),Vu(e,t)),Gu=e=>Ms(new xu,Uu,e)}});function qu(e){return e.length?{commands:[`merge`,...e],format:`utf-8`,parser(e,t){let n=Wu(e,t);if(n.failed)throw new Ao(n);return n}}:Qs(`Git.merge requires at least one option`)}var Ju=Y({"src/lib/tasks/merge.ts"(){jo(),Ku(),ic()}});function Yu(e,t,n){let r=n.includes(`deleted`),i=n.includes(`tag`)||/^refs\/tags/.test(e),a=!n.includes(`new`);return{deleted:r,tag:i,branch:!i,new:!a,alreadyUpdated:a,local:e,remote:t}}var Xu,Zu,Qu,$u=Y({"src/lib/parsers/parse-push.ts"(){Z(),Nu(),Xu=[new X(/^Pushing to (.+)$/,(e,[t])=>{e.repo=t}),new X(/^updating local tracking ref '(.+)'/,(e,[t])=>{e.ref={...e.ref||{},local:t}}),new X(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(e,[t,n,r])=>{e.pushed.push(Yu(t,n,r))}),new X(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(e,[t,n,r])=>{e.branch={...e.branch||{},local:t,remote:n,remoteName:r}}),new X(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(e,[t,n,r,i])=>{e.update={head:{local:t,remote:n},hash:{from:r,to:i}}})],Zu=(e,t)=>{let n=Qu(e,t),r=Au(e,t);return{...n,...r}},Qu=(e,t)=>Ms({pushed:[]},Xu,[e,t])}}),ed={};bo(ed,{pushTagsTask:()=>td,pushTask:()=>nd});function td(e={},t){return Uo(t,`--tags`),nd(e,t)}function nd(e={},t){let n=[`push`,...t];return e.branch&&n.splice(1,0,e.branch),e.remote&&n.splice(1,0,e.remote),Go(n,`-v`),Uo(n,`--verbose`),Uo(n,`--porcelain`),{commands:n,format:`utf-8`,parser:Zu}}var rd=Y({"src/lib/tasks/push.ts"(){$u(),Z()}});function id(){return{showBuffer(){let e=[`show`,...Es(arguments,1)];return e.includes(`--binary`)||e.splice(1,0,`--binary`),this._runTask(ec(e),ks(arguments))},show(){let e=[`show`,...Es(arguments,1)];return this._runTask($s(e),ks(arguments))}}}var ad=Y({"src/lib/tasks/show.ts"(){Z(),ic()}}),od,sd,cd=Y({"src/lib/responses/FileStatusSummary.ts"(){od=/^(.+)\0(.+)$/,sd=class{constructor(e,t,n){if(this.path=e,this.index=t,this.working_dir=n,t===`R`||n===`R`){let t=od.exec(e)||[null,e,e];this.from=t[2]||``,this.path=t[1]||``}}}}});function ld(e){let[t,n]=e.split(ts);return{from:n||t,to:t}}function ud(e,t,n){return[`${e}${t}`,n]}function dd(e,...t){return t.map(t=>ud(e,t,(e,t)=>e.conflicted.push(t)))}function fd(e,t){let n=t.trim();switch(` `){case n.charAt(2):return r(n.charAt(0),n.charAt(1),n.slice(3));case n.charAt(1):return r(` `,n.charAt(0),n.slice(2));default:return}function r(t,n,r){let i=`${t}${n}`,a=md.get(i);a&&a(e,r),i!==`##`&&i!==`!!`&&e.files.push(new sd(r,t,n))}}var pd,md,hd,gd=Y({"src/lib/responses/StatusSummary.ts"(){Z(),cd(),pd=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},md=new Map([ud(` `,`A`,(e,t)=>e.created.push(t)),ud(` `,`D`,(e,t)=>e.deleted.push(t)),ud(` `,`M`,(e,t)=>e.modified.push(t)),ud(`A`,` `,(e,t)=>{e.created.push(t),e.staged.push(t)}),ud(`A`,`M`,(e,t)=>{e.created.push(t),e.staged.push(t),e.modified.push(t)}),ud(`D`,` `,(e,t)=>{e.deleted.push(t),e.staged.push(t)}),ud(`M`,` `,(e,t)=>{e.modified.push(t),e.staged.push(t)}),ud(`M`,`M`,(e,t)=>{e.modified.push(t),e.staged.push(t)}),ud(`R`,` `,(e,t)=>{e.renamed.push(ld(t))}),ud(`R`,`M`,(e,t)=>{let n=ld(t);e.renamed.push(n),e.modified.push(n.to)}),ud(`!`,`!`,(e,t)=>{(e.ignored=e.ignored||[]).push(t)}),ud(`?`,`?`,(e,t)=>e.not_added.push(t)),...dd(`A`,`A`,`U`),...dd(`D`,`D`,`U`),...dd(`U`,`A`,`D`,`U`),[`##`,(e,t)=>{let n=/ahead (\d+)/,r=/behind (\d+)/,i=/^(.+?(?=(?:\.{3}|\s|$)))/,a=/\.{3}(\S*)/,o=/\son\s(\S+?)(?=\.{3}|$)/,s=n.exec(t);e.ahead=s&&+s[1]||0,s=r.exec(t),e.behind=s&&+s[1]||0,s=i.exec(t),e.current=as(s?.[1],ds,null),s=a.exec(t),e.tracking=as(s?.[1],ds,null),s=o.exec(t),s&&(e.current=as(s?.[1],ds,e.current)),e.detached=/\(no branch\)/.test(t)}]]),hd=function(e){let t=e.split(ts),n=new pd;for(let e=0,r=t.length;e<r;){let r=t[e++].trim();r&&(r.charAt(0)===`R`&&(r+=ts+(t[e++]||``)),fd(n,r))}return n}}});function _d(e){return{format:`utf-8`,commands:[`status`,`--porcelain`,`-b`,`-u`,`--null`,...e.filter(e=>!vd.includes(e))],parser(e){return hd(e)}}}var vd,yd=Y({"src/lib/tasks/status.ts"(){gd(),vd=[`--null`,`-z`]}});function bd(e=0,t=0,n=0,r=``,i=!0){return Object.defineProperty({major:e,minor:t,patch:n,agent:r,installed:i},`toString`,{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function xd(){return bd(0,0,0,``,!1)}function Sd(){return{version(){return this._runTask({commands:[`--version`],format:`utf-8`,parser:Cd,onError(e,t,n,r){if(e.exitCode===-2)return n(Buffer.from(wd));r(t)}})}}}function Cd(e){return e===wd?xd():Ms(bd(0,0,0,e),Td,e)}var wd,Td,Ed=Y({"src/lib/tasks/version.ts"(){Z(),wd=`installed=false`,Td=[new X(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(e,[t,n,r,i=``])=>{Object.assign(e,bd(Yo(t),Yo(n),Yo(r),i))}),new X(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(e,[t,n,r,i=``])=>{Object.assign(e,bd(Yo(t),Yo(n),r,i))})]}});function Dd(e,t,n,...r){return ds(n)?t(n,as(r[0],ds),Es(arguments)):Qs(`git.${e}() requires a string 'repoPath'`)}function Od(){return{clone(e,...t){return this._runTask(Dd(`clone`,kd,as(e,ds),...t),ks(arguments))},mirror(e,...t){return this._runTask(Dd(`mirror`,Ad,as(e,ds),...t),ks(arguments))}}}var kd,Ad,jd=Y({"src/lib/tasks/clone.ts"(){ic(),Z(),Do(),kd=(e,t,n)=>{let r=[`clone`,...n];return ds(e)&&r.push(Co(e)),ds(t)&&r.push(Co(t)),$s(r)},Ad=(e,t,n)=>(Uo(n,`--mirror`),kd(e,t,n))}}),Md={};bo(Md,{SimpleGitApi:()=>Nd});var Nd,Pd=Y({"src/lib/simple-git-api.ts"(){ml(),gl(),yl(),Cl(),kl(),jc(),jl(),Uc(),Nl(),Hl(),yu(),Ju(),rd(),ad(),yd(),ic(),Ed(),Z(),jd(),Nd=class{constructor(e){this._executor=e}_runTask(e,t){let n=this._executor.chain(),r=n.push(e);return t&&fl(e,r,t),Object.create(this,{then:{value:r.then.bind(r)},catch:{value:r.catch.bind(r)},_executor:{value:n}})}add(e){return this._runTask($s([`add`,...Ko(e)]),ks(arguments))}cwd(e){let t=ks(arguments);return typeof e==`string`?this._runTask(hl(e,this._executor),t):typeof e?.path==`string`?this._runTask(hl(e.path,e.root&&this._executor||void 0),t):this._runTask(Qs(`Git.cwd: workingDirectory must be supplied as a string`),t)}hashObject(e,t){return this._runTask(Ml(e,t===!0),ks(arguments))}init(e){return this._runTask(Bl(e===!0,this._executor.cwd,Es(arguments)),ks(arguments))}merge(){return this._runTask(qu(Es(arguments)),ks(arguments))}mergeFromTo(e,t){return ds(e)&&ds(t)?this._runTask(qu([e,t,...Es(arguments)]),ks(arguments,!1)):this._runTask(Qs(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`))}outputHandler(e){return this._executor.outputHandler=e,this}push(){let e=nd({remote:as(arguments[0],ds),branch:as(arguments[1],ds)},Es(arguments));return this._runTask(e,ks(arguments))}stash(){return this._runTask($s([`stash`,...Es(arguments)]),ks(arguments))}status(){return this._runTask(_d(Es(arguments)),ks(arguments))}},Object.assign(Nd.prototype,vl(),Od(),Ol(),kc(),xl(),Al(),Rc(),_u(),id(),Sd())}}),Fd={};bo(Fd,{Scheduler:()=>Ld});var Id,Ld,Rd=Y({"src/lib/runners/scheduler.ts"(){Z(),tl(),Id=(()=>{let e=0;return()=>{e++;let{promise:t,done:n}=(0,mo.createDeferred)();return{promise:t,done:n,id:e}}})(),Ld=class{constructor(e=2){this.concurrency=e,this.logger=el(``,`scheduler`),this.pending=[],this.running=[],this.logger(`Constructed, concurrency=%s`,e)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger(`Schedule attempt ignored, pending=%s running=%s concurrency=%s`,this.pending.length,this.running.length,this.concurrency);return}let e=Uo(this.running,this.pending.shift());this.logger(`Attempting id=%s`,e.id),e.done(()=>{this.logger(`Completing id=`,e.id),Go(this.running,e),this.schedule()})}next(){let{promise:e,id:t}=Uo(this.pending,Id());return this.logger(`Scheduling id=%s`,t),this.schedule(),e}}}}),zd={};bo(zd,{applyPatchTask:()=>Bd});function Bd(e,t){return $s([`apply`,...t,...e])}var Vd=Y({"src/lib/tasks/apply-patch.ts"(){ic()}});function Hd(e,t){return{branch:e,hash:t,success:!0}}function Ud(e){return{branch:e,hash:null,success:!1}}var Wd,Gd=Y({"src/lib/responses/BranchDeleteSummary.ts"(){Wd=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function Kd(e,t){return t===1&&Jd.test(e)}var qd,Jd,Yd,Xd,Zd=Y({"src/lib/parsers/parse-branch-delete.ts"(){Gd(),Z(),qd=/(\S+)\s+\(\S+\s([^)]+)\)/,Jd=/^error[^']+'([^']+)'/m,Yd=[new X(qd,(e,[t,n])=>{let r=Hd(t,n);e.all.push(r),e.branches[t]=r}),new X(Jd,(e,[t])=>{let n=Ud(t);e.errors.push(n),e.all.push(n),e.branches[t]=n})],Xd=(e,t)=>Ms(new Wd,Yd,[e,t])}}),Qd,$d=Y({"src/lib/responses/BranchSummary.ts"(){Qd=class{constructor(){this.all=[],this.branches={},this.current=``,this.detached=!1}push(e,t,n,r,i){e===`*`&&(this.detached=t,this.current=n),this.all.push(n),this.branches[n]={current:e===`*`,linkedWorkTree:e===`+`,name:n,commit:r,label:i}}}}});function ef(e){return e?e.charAt(0):``}function tf(e,t=!1){return Ms(new Qd,t?[rf]:nf,e)}var nf,rf,af=Y({"src/lib/parsers/parse-branch.ts"(){$d(),Z(),nf=[new X(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(e,[t,n,r,i])=>{e.push(ef(t),!0,n,r,i)}),new X(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(e,[t,n,r,i])=>{e.push(ef(t),!1,n,r,i)})],rf=new X(/^(\S+)$/s,(e,[t])=>{e.push(`*`,!1,t,``,``)})}}),of={};bo(of,{branchLocalTask:()=>lf,branchTask:()=>cf,containsDeleteBranchCommand:()=>sf,deleteBranchTask:()=>df,deleteBranchesTask:()=>uf});function sf(e){let t=[`-d`,`-D`,`--delete`];return e.some(e=>t.includes(e))}function cf(e){let t=sf(e),n=e.includes(`--show-current`),r=[`branch`,...e];return r.length===1&&r.push(`-a`),r.includes(`-v`)||r.splice(1,0,`-v`),{format:`utf-8`,commands:r,parser(e,r){return t?Xd(e,r).all[0]:tf(e,n)}}}function lf(){return{format:`utf-8`,commands:[`branch`,`-v`],parser(e){return tf(e)}}}function uf(e,t=!1){return{format:`utf-8`,commands:[`branch`,`-v`,t?`-D`:`-d`,...e],parser(e,t){return Xd(e,t)},onError({exitCode:e,stdOut:t},n,r,i){if(!Kd(String(n),e))return i(n);r(t)}}}function df(e,t=!1){let n={format:`utf-8`,commands:[`branch`,`-v`,t?`-D`:`-d`,e],parser(t,n){return Xd(t,n).branches[e]},onError({exitCode:e,stdErr:t,stdOut:r},i,a,o){if(!Kd(String(i),e))return o(i);throw new Ao(n.parser(Zo(r),Zo(t)),String(i))}};return n}var ff=Y({"src/lib/tasks/branch.ts"(){jo(),Zd(),af(),Z()}});function pf(e){let t=e.trim().replace(/^["']|["']$/g,``);return t&&pe(t)}var mf,hf=Y({"src/lib/responses/CheckIgnore.ts"(){mf=e=>e.split(/\n/g).map(pf).filter(Boolean)}}),gf={};bo(gf,{checkIgnoreTask:()=>_f});function _f(e){return{commands:[`check-ignore`,...e],format:`utf-8`,parser:mf}}var vf=Y({"src/lib/tasks/check-ignore.ts"(){hf()}});function yf(e,t){return Ms({raw:e,remote:null,branches:[],tags:[],updated:[],deleted:[]},bf,[e,t])}var bf,xf=Y({"src/lib/parsers/parse-fetch.ts"(){Z(),bf=[new X(/From (.+)$/,(e,[t])=>{e.remote=t}),new X(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.branches.push({name:t,tracking:n})}),new X(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(e,[t,n])=>{e.tags.push({name:t,tracking:n})}),new X(/- \[deleted]\s+\S+\s*-> (.+)$/,(e,[t])=>{e.deleted.push({tracking:t})}),new X(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(e,[t,n,r,i])=>{e.updated.push({name:r,tracking:i,to:n,from:t})})]}}),Sf={};bo(Sf,{fetchTask:()=>wf});function Cf(e){return/^--upload-pack(=|$)/.test(e)}function wf(e,t,n){let r=[`fetch`,...n];return e&&t&&r.push(e,t),r.find(Cf)?Qs(`git.fetch: potential exploit argument blocked.`):{commands:r,format:`utf-8`,parser:yf}}var Tf=Y({"src/lib/tasks/fetch.ts"(){xf(),ic()}});function Ef(e){return Ms({moves:[]},Df,e)}var Df,Of=Y({"src/lib/parsers/parse-move.ts"(){Z(),Df=[new X(/^Renaming (.+) to (.+)$/,(e,[t,n])=>{e.moves.push({from:t,to:n})})]}}),kf={};bo(kf,{moveTask:()=>Af});function Af(e,t){return{commands:[`mv`,`-v`,...Ko(e),t],format:`utf-8`,parser:Ef}}var jf=Y({"src/lib/tasks/move.ts"(){Of(),Z()}}),Mf={};bo(Mf,{pullTask:()=>Nf});function Nf(e,t,n){let r=[`pull`,...n];return e&&t&&r.splice(1,0,e,t),{commands:r,format:`utf-8`,parser(e,t){return Vu(e,t)},onError(e,t,n,r){let i=Pu(Zo(e.stdOut),Zo(e.stdErr));if(i)return r(new Ao(i));r(t)}}}var Pf=Y({"src/lib/tasks/pull.ts"(){jo(),Hu(),Z()}});function Ff(e){let t={};return Lf(e,([e])=>t[e]={name:e}),Object.values(t)}function If(e){let t={};return Lf(e,([e,n,r])=>{Object.hasOwn(t,e)||(t[e]={name:e,refs:{fetch:``,push:``}}),r&&n&&(t[e].refs[r.replace(/[^a-z]/g,``)]=n)}),Object.values(t)}function Lf(e,t){Vo(e,e=>t(e.split(/\s+/)))}var Rf=Y({"src/lib/responses/GetRemoteSummary.ts"(){Z()}}),zf={};bo(zf,{addRemoteTask:()=>Bf,getRemotesTask:()=>Vf,listRemotesTask:()=>Hf,remoteTask:()=>Uf,removeRemoteTask:()=>Wf});function Bf(e,t,n){return $s([`remote`,`add`,...n,e,t])}function Vf(e){let t=[`remote`];return e&&t.push(`-v`),{commands:t,format:`utf-8`,parser:e?If:Ff}}function Hf(e){let t=[...e];return t[0]!==`ls-remote`&&t.unshift(`ls-remote`),$s(t)}function Uf(e){let t=[...e];return t[0]!==`remote`&&t.unshift(`remote`),$s(t)}function Wf(e){return $s([`remote`,`remove`,e])}var Gf=Y({"src/lib/tasks/remote.ts"(){Rf(),ic()}}),Kf={};bo(Kf,{stashListTask:()=>qf});function qf(e={},t){let n=hu(e),r=[`stash`,`list`,...n.commands,...t],i=ru(n.splitter,n.fields,Ul(r));return du(r)||{commands:r,format:`utf-8`,parser:i}}var Jf=Y({"src/lib/tasks/stash-list.ts"(){Kl(),cu(),fu(),yu()}}),Yf={};bo(Yf,{addSubModuleTask:()=>Xf,initSubModuleTask:()=>Zf,subModuleTask:()=>Qf,updateSubModuleTask:()=>$f});function Xf(e,t){return Qf([`add`,e,t])}function Zf(e){return Qf([`init`,...e])}function Qf(e){let t=[...e];return t[0]!==`submodule`&&t.unshift(`submodule`),$s(t)}function $f(e){return Qf([`update`,...e])}var ep=Y({"src/lib/tasks/sub-module.ts"(){ic()}});function tp(e,t){let n=Number.isNaN(e);return n===Number.isNaN(t)?n?np(e,t):0:n?1:-1}function np(e,t){return e===t?0:e>t?1:-1}function rp(e){return e.trim()}function ip(e){return typeof e==`string`&&parseInt(e.replace(/^\D+/g,``),10)||0}var ap,op,sp=Y({"src/lib/responses/TagList.ts"(){ap=class{constructor(e,t){this.all=e,this.latest=t}},op=function(e,t=!1){let n=e.split(`
22
+ `).map(rp).filter(Boolean);t||n.sort(function(e,t){let n=e.split(`.`),r=t.split(`.`);if(n.length===1||r.length===1)return tp(ip(n[0]),ip(r[0]));for(let e=0,t=Math.max(n.length,r.length);e<t;e++){let t=np(ip(n[e]),ip(r[e]));if(t)return t}return 0});let r=t?n[0]:[...n].reverse().find(e=>e.indexOf(`.`)>=0);return new ap(n,r)}}}),cp={};bo(cp,{addAnnotatedTagTask:()=>dp,addTagTask:()=>up,tagListTask:()=>lp});function lp(e=[]){let t=e.some(e=>/^--sort=/.test(e));return{format:`utf-8`,commands:[`tag`,`-l`,...e],parser(e){return op(e,t)}}}function up(e){return{format:`utf-8`,commands:[`tag`,e],parser(){return{name:e}}}}function dp(e,t){return{format:`utf-8`,commands:[`tag`,`-a`,`-m`,t,e],parser(){return{name:e}}}}var fp=Y({"src/lib/tasks/tag.ts"(){sp()}}),pp=yo({"src/git.js"(e,t){var{GitExecutor:n}=(dl(),So(ll)),{SimpleGitApi:r}=(Pd(),So(Md)),{Scheduler:i}=(Rd(),So(Fd)),{adhocExecTask:a,configurationErrorTask:o}=(ic(),So(Xs)),{asArray:s,filterArray:c,filterPrimitives:l,filterString:u,filterStringOrStringArray:d,filterType:f,getTrailingOptions:p,trailingFunctionArgument:m,trailingOptionsArgument:h}=(Z(),So(Ps)),{applyPatchTask:g}=(Vd(),So(zd)),{branchTask:_,branchLocalTask:v,deleteBranchesTask:y,deleteBranchTask:b}=(ff(),So(of)),{checkIgnoreTask:x}=(vf(),So(gf)),{checkIsRepoTask:S}=(Us(),So(Fs)),{cleanWithOptionsTask:C,isCleanOptionsArray:w}=(vc(),So(ac)),{diffSummaryTask:ee}=(fu(),So(lu)),{fetchTask:T}=(Tf(),So(Sf)),{moveTask:E}=(jf(),So(kf)),{pullTask:D}=(Pf(),So(Mf)),{pushTagsTask:O}=(rd(),So(ed)),{addRemoteTask:k,getRemotesTask:A,listRemotesTask:te,remoteTask:ne,removeRemoteTask:re}=(Gf(),So(zf)),{getResetMode:j,resetTask:M}=(Xc(),So(Wc)),{stashListTask:N}=(Jf(),So(Kf)),{addSubModuleTask:ie,initSubModuleTask:ae,subModuleTask:oe,updateSubModuleTask:P}=(ep(),So(Yf)),{addAnnotatedTagTask:se,addTagTask:F,tagListTask:I}=(fp(),So(cp)),{straightThroughBufferTask:L,straightThroughStringTask:R}=(ic(),So(Xs));function z(e,t){this._plugins=t,this._executor=new n(e.baseDir,new i(e.maxConcurrentProcesses),t),this._trimmed=e.trimmed}(z.prototype=Object.create(r.prototype)).constructor=z,z.prototype.customBinary=function(e){return this._plugins.reconfigure(`binary`,e),this},z.prototype.env=function(e,t){return arguments.length===1&&typeof e==`object`?this._executor.env=e:(this._executor.env=this._executor.env||{})[e]=t,this},z.prototype.stashList=function(e){return this._runTask(N(h(arguments)||{},c(e)&&e||[]),m(arguments))},z.prototype.mv=function(e,t){return this._runTask(E(e,t),m(arguments))},z.prototype.checkoutLatestTag=function(e){var t=this;return this.pull(function(){t.tags(function(n,r){t.checkout(r.latest,e)})})},z.prototype.pull=function(e,t,n,r){return this._runTask(D(f(e,u),f(t,u),p(arguments)),m(arguments))},z.prototype.fetch=function(e,t){return this._runTask(T(f(e,u),f(t,u),p(arguments)),m(arguments))},z.prototype.silent=function(e){return this._runTask(a(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},z.prototype.tags=function(e,t){return this._runTask(I(p(arguments)),m(arguments))},z.prototype.rebase=function(){return this._runTask(R([`rebase`,...p(arguments)]),m(arguments))},z.prototype.reset=function(e){return this._runTask(M(j(e),p(arguments)),m(arguments))},z.prototype.revert=function(e){let t=m(arguments);return typeof e==`string`?this._runTask(R([`revert`,...p(arguments,0,!0),e]),t):this._runTask(o(`Commit must be a string`),t)},z.prototype.addTag=function(e){let t=typeof e==`string`?F(e):o(`Git.addTag requires a tag name`);return this._runTask(t,m(arguments))},z.prototype.addAnnotatedTag=function(e,t){return this._runTask(se(e,t),m(arguments))},z.prototype.deleteLocalBranch=function(e,t,n){return this._runTask(b(e,typeof t==`boolean`?t:!1),m(arguments))},z.prototype.deleteLocalBranches=function(e,t,n){return this._runTask(y(e,typeof t==`boolean`?t:!1),m(arguments))},z.prototype.branch=function(e,t){return this._runTask(_(p(arguments)),m(arguments))},z.prototype.branchLocal=function(e){return this._runTask(v(),m(arguments))},z.prototype.raw=function(e){let t=!Array.isArray(e),n=[].slice.call(t?arguments:e,0);for(let e=0;e<n.length&&t;e++)if(!l(n[e])){n.splice(e,n.length-e);break}n.push(...p(arguments,0,!0));var r=m(arguments);return n.length?this._runTask(R(n,this._trimmed),r):this._runTask(o(`Raw: must supply one or more command to execute`),r)},z.prototype.submoduleAdd=function(e,t,n){return this._runTask(ie(e,t),m(arguments))},z.prototype.submoduleUpdate=function(e,t){return this._runTask(P(p(arguments,!0)),m(arguments))},z.prototype.submoduleInit=function(e,t){return this._runTask(ae(p(arguments,!0)),m(arguments))},z.prototype.subModule=function(e,t){return this._runTask(oe(p(arguments)),m(arguments))},z.prototype.listRemote=function(){return this._runTask(te(p(arguments)),m(arguments))},z.prototype.addRemote=function(e,t,n){return this._runTask(k(e,t,p(arguments)),m(arguments))},z.prototype.removeRemote=function(e,t){return this._runTask(re(e),m(arguments))},z.prototype.getRemotes=function(e,t){return this._runTask(A(e===!0),m(arguments))},z.prototype.remote=function(e,t){return this._runTask(ne(p(arguments)),m(arguments))},z.prototype.tag=function(e,t){let n=p(arguments);return n[0]!==`tag`&&n.unshift(`tag`),this._runTask(R(n),m(arguments))},z.prototype.updateServerInfo=function(e){return this._runTask(R([`update-server-info`]),m(arguments))},z.prototype.pushTags=function(e,t){let n=O({remote:f(e,u)},p(arguments));return this._runTask(n,m(arguments))},z.prototype.rm=function(e){return this._runTask(R([`rm`,`-f`,...s(e)]),m(arguments))},z.prototype.rmKeepLocal=function(e){return this._runTask(R([`rm`,`--cached`,...s(e)]),m(arguments))},z.prototype.catFile=function(e,t){return this._catFile(`utf-8`,arguments)},z.prototype.binaryCatFile=function(){return this._catFile(`buffer`,arguments)},z.prototype._catFile=function(e,t){var n=m(t),r=[`cat-file`],i=t[0];if(typeof i==`string`)return this._runTask(o(`Git.catFile: options must be supplied as an array of strings`),n);Array.isArray(i)&&r.push.apply(r,i);let a=e===`buffer`?L(r):R(r);return this._runTask(a,n)},z.prototype.diff=function(e,t){let n=u(e)?o(`git.diff: supplying options as a single string is no longer supported, switch to an array of strings`):R([`diff`,...p(arguments)]);return this._runTask(n,m(arguments))},z.prototype.diffSummary=function(){return this._runTask(ee(p(arguments,1)),m(arguments))},z.prototype.applyPatch=function(e){let t=d(e)?g(s(e),p([].slice.call(arguments,1))):o(`git.applyPatch requires one or more string patches as the first argument`);return this._runTask(t,m(arguments))},z.prototype.revparse=function(){let e=[`rev-parse`,...p(arguments,!0)];return this._runTask(R(e,!0),m(arguments))},z.prototype.clean=function(e,t,n){let r=w(e),i=r&&e.join(``)||f(e,u)||``,a=p([].slice.call(arguments,r?1:0));return this._runTask(C(i,a),m(arguments))},z.prototype.exec=function(e){return this._runTask({commands:[],format:`utf-8`,parser(){typeof e==`function`&&e()}})},z.prototype.clearQueue=function(){return this._runTask(a(()=>console.warn(`simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.`)))},z.prototype.checkIgnore=function(e,t){return this._runTask(x(s(f(e,d,[]))),m(arguments))},z.prototype.checkIsRepo=function(e,t){return this._runTask(S(f(e,u)),m(arguments))},t.exports=z}});Do(),ko();var mp=class extends Oo{constructor(e,t){super(void 0,t),this.config=e}};ko(),ko();var hp=class extends Oo{constructor(e,t,n){super(e,n),this.task=e,this.plugin=t,Object.setPrototypeOf(this,new.target.prototype)}};jo(),No(),Us(),vc(),jc(),Fc(),Uc(),Xc();function gp(e){if(e)return[{type:`spawn.before`,action(t,n){e.aborted&&n.kill(new hp(void 0,`abort`,`Abort already signaled`))}},{type:`spawn.after`,action(t,n){function r(){n.kill(new hp(void 0,`abort`,`Abort signal received`))}e.addEventListener(`abort`,r),n.spawned.on(`close`,()=>e.removeEventListener(`abort`,r))}}]}function _p(e){return typeof e==`string`&&e.trim().toLowerCase()===`-c`}function vp(e,t){if(typeof t!=`string`||!t.includes(e))return!1;let n=t.trim().replace(/\0/g,``);return/^(--no)?-{1,2}[\dlsqvnobucj]+(\s|$)/.test(n)}function yp(e,t,n=String(e)){let r=typeof e==`string`?RegExp(`\\s*${e}`,`i`):e;return function(e,i,a){if(e[t]!==!0&&_p(i)&&r.test(a))throw new hp(void 0,`unsafe`,`Configuring ${n} is not permitted without enabling ${t}`)}}var bp=[yp(/^\s*protocol(.[a-z]+)?.allow/i,`allowUnsafeProtocolOverride`,`protocol.allow`),yp(`core.sshCommand`,`allowUnsafeSshCommand`),yp(`core.gitProxy`,`allowUnsafeGitProxy`),yp(`core.hooksPath`,`allowUnsafeHooksPath`),yp(`diff.external`,`allowUnsafeDiffExternal`)];function xp(e,t){if(/^\s*--(upload|receive)-pack/.test(e))throw new hp(void 0,`unsafe`,`Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`);if(t===`clone`&&vp(`u`,e))throw new hp(void 0,`unsafe`,`Use of clone with option -u is not permitted without enabling allowUnsafePack`);if(t===`push`&&/^\s*--exec\b/.test(e))throw new hp(void 0,`unsafe`,`Use of push with option --exec is not permitted without enabling allowUnsafePack`)}function Sp({allowUnsafePack:e=!1,...t}={}){return{type:`spawn.args`,action(n,r){return n.forEach((i,a)=>{let o=a<n.length?n[a+1]:``;e||xp(i,r.method),bp.forEach(e=>e(t,i,o))}),n}}}Z();function Cp(e){let t=Xo(e,`-c`);return{type:`spawn.args`,action(e){return[...t,...e]}}}Z();var wp=(0,mo.deferred)().promise;function Tp({onClose:e=!0,onExit:t=50}={}){function n(){let n=-1,i={close:(0,mo.deferred)(),closeTimeout:(0,mo.deferred)(),exit:(0,mo.deferred)(),exitTimeout:(0,mo.deferred)()},a=Promise.race([e===!1?wp:i.closeTimeout.promise,t===!1?wp:i.exitTimeout.promise]);return r(e,i.close,i.closeTimeout),r(t,i.exit,i.exitTimeout),{close(e){n=e,i.close.done()},exit(e){n=e,i.exit.done()},get exitCode(){return n},result:a}}function r(e,t,n){e!==!1&&(e===!0?t.promise:t.promise.then(()=>$o(e))).then(n.done)}return{type:`spawn.after`,async action(e,{spawned:t,close:r}){let i=n(),a=!0,o=()=>void(a=!1);t.stdout?.on(`data`,o),t.stderr?.on(`data`,o),t.on(`error`,o),t.on(`close`,e=>i.close(e)),t.on(`exit`,e=>i.exit(e));try{await i.result,a&&await $o(50),r(i.exitCode)}catch(e){r(i.exitCode,e)}}}}Z();var Ep=`Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`,Dp=`Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;function Op(e){return!e||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(e)}function kp(e,t){if(e.length<1||e.length>2)throw new hp(void 0,`binary`,Ep);if(e.some(Op))if(t)console.warn(Dp);else throw new hp(void 0,`binary`,Dp);let[n,r]=e;return{binary:n,prefix:r}}function Ap(e,t=[`git`],n=!1){let r=kp(Ko(t),n);e.on(`binary`,e=>{r=kp(Ko(e),n)}),e.append(`spawn.binary`,()=>r.binary),e.append(`spawn.args`,e=>r.prefix?[r.prefix,...e]:e)}ko();function jp(e){return!!(e.exitCode&&e.stdErr.length)}function Mp(e){return Buffer.concat([...e.stdOut,...e.stdErr])}function Np(e=!1,t=jp,n=Mp){return(r,i)=>!e&&r||!t(i)?r:n(i)}function Pp(e){return{type:`task.error`,action(t,n){let r=e(t.error,{stdErr:n.stdErr,stdOut:n.stdOut,exitCode:n.exitCode});return Buffer.isBuffer(r)?{error:new Oo(void 0,r.toString(`utf-8`))}:{error:r}}}}Z();var Fp=class{constructor(){this.plugins=new Set,this.events=new Oe}on(e,t){this.events.on(e,t)}reconfigure(e,t){this.events.emit(e,t)}append(e,t){let n=Uo(this.plugins,{type:e,action:t});return()=>this.plugins.delete(n)}add(e){let t=[];return Ko(e).forEach(e=>e&&this.plugins.add(Uo(t,e))),()=>{t.forEach(e=>this.plugins.delete(e))}}exec(e,t,n){let r=t,i=Object.freeze(Object.create(n));for(let t of this.plugins)t.type===e&&(r=t.action(r,i));return r}};Z();function Ip(e){let t=`--progress`,n=[`checkout`,`clone`,`fetch`,`pull`,`push`];return[{type:`spawn.args`,action(e,r){return n.includes(r.method)?Wo(e,t):e}},{type:`spawn.after`,action(n,r){r.commands.includes(t)&&r.spawned.stderr?.on(`data`,t=>{let n=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(t.toString(`utf8`));n&&e({method:r.method,stage:Lp(n[1]),progress:Yo(n[2]),processed:Yo(n[3]),total:Yo(n[4])})})}}]}function Lp(e){return String(e.toLowerCase().split(` `,1))||`unknown`}Z();function Rp(e){let t=Qo(e,[`uid`,`gid`]);return{type:`spawn.options`,action(e){return{...t,...e}}}}function zp({block:e,stdErr:t=!0,stdOut:n=!0}){if(e>0)return{type:`spawn.after`,action(r,i){let a;function o(){a&&clearTimeout(a),a=setTimeout(c,e)}function s(){i.spawned.stdout?.off(`data`,o),i.spawned.stderr?.off(`data`,o),i.spawned.off(`exit`,s),i.spawned.off(`close`,s),a&&clearTimeout(a)}function c(){s(),i.kill(new hp(void 0,`timeout`,`block timeout reached`))}n&&i.spawned.stdout?.on(`data`,o),t&&i.spawned.stderr?.on(`data`,o),i.spawned.on(`exit`,s),i.spawned.on(`close`,s),o()}}}Do();function Bp(){return{type:`spawn.args`,action(e){let t=[],n;function r(e){(n||=[]).push(...e)}for(let n=0;n<e.length;n++){let i=e[n];if(wo(i)){r(To(i));continue}if(i===`--`){r(e.slice(n+1).flatMap(e=>wo(e)&&To(e)||e));break}t.push(i)}return n?[...t,`--`,...n.map(String)]:t}}}Z();var Vp=pp();function Hp(e,t){let n=new Fp,r=Ss(e&&(typeof e==`string`?{baseDir:e}:e)||{},t);if(!Ho(r.baseDir))throw new mp(r,`Cannot use simple-git on a directory that does not exist`);return Array.isArray(r.config)&&n.add(Cp(r.config)),n.add(Sp(r.unsafe)),n.add(Tp(r.completion)),r.abort&&n.add(gp(r.abort)),r.progress&&n.add(Ip(r.progress)),r.timeout&&n.add(zp(r.timeout)),r.spawnOptions&&n.add(Rp(r.spawnOptions)),n.add(Bp()),n.add(Pp(Np(!0))),r.errors&&n.add(Pp(r.errors)),Ap(n,r.binary,r.unsafe?.allowUnsafeCustomBinary),new Vp(r,n)}jo();var Up=Hp;const Wp=`.expect`,Gp=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`,`.cts`,`.cjs`],Kp=new Set([`node_modules`,`dist`,`build`,`.git`,`.next`,`.turbo`,`coverage`,`.nyc_output`,`.cache`,`.repos`,`.specs`,`__snapshots__`,`__fixtures__`]);var qp=class extends S.ErrorClass(`GitError`)({_tag:S.tag(`GitError`),operation:S.String,cause:S.Defect}){message=`Git error during "${this.operation}"`},Jp=class extends S.ErrorClass(`FindRepoRootError`)({_tag:S.tag(`FindRepoRootError`),cause:S.Defect}){message=`Could not find git repository root`},Yp=class extends C.Service()(`@supervisor/GitRepoRoot`){},Xp=class e extends C.Service()(`@supervisor/Git`,{make:u.gen(function*(){let e=yield*p.FileSystem,t=e=>u.gen(function*(){let t=yield*Yp;return yield*u.tryPromise({try:()=>Up(t).raw(e.args),catch:t=>new qp({operation:e.operation,cause:t})}).pipe(u.map(e.trim?q.trim:Se.identity))}),n=e=>u.tryPromise({try:()=>Up(e).revparse([`--show-toplevel`]),catch:e=>new Jp({cause:e})}).pipe(u.map(q.trim)),r=e=>t=>u.gen(function*(){let r=yield*n(e);return yield*t.pipe(u.provideService(Yp,r))}),i=t({args:[`symbolic-ref`,`refs/remotes/origin/HEAD`],operation:`getting main branch`,trim:!0}).pipe(u.map(e=>e.replace(`refs/remotes/origin/`,``)),u.catchTag(`GitError`,()=>t({args:[`revparse`,`--verify`,`origin/main`],operation:`getting main branch (origin/main)`,trim:!0}).pipe(u.as(`main`))),u.catchTag(`GitError`,()=>t({args:[`rev-parse`,`--verify`,`main`],operation:`getting main branch (main)`,trim:!0}).pipe(u.as(`main`))),u.catchTag(`GitError`,()=>u.succeed(`main`))),a=t({args:[`rev-parse`,`--abbrev-ref`,`HEAD`],operation:`getting current branch`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(`HEAD`))),o=t({args:[`rev-parse`,`--is-inside-work-tree`],operation:`checking if inside work tree`,trim:!0}).pipe(u.map(e=>e===`true`),u.catchTag(`GitError`,()=>u.succeed(!1))),s=e=>{let[t,n,r]=e.split(` `);return new fn({relativePath:r??``,added:Number.parseInt(t??`0`,10)||0,removed:Number.parseInt(n??`0`,10)||0})},c=u.fn(`Git.getFileStats`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`diff`,`HEAD`,`--numstat`],operation:`getting working tree file stats`}).pipe(u.map(q.split(`
23
+ `)),u.map(xe.map(q.trim)),u.map(xe.filter(q.isNonEmpty)),u.map(xe.map(s)),u.catchTag(`GitError`,()=>u.succeed([]))):yield*t({args:[`diff`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`,`--numstat`],operation:`getting file stats`}).pipe(u.map(q.split(`
24
+ `)),u.map(xe.map(q.trim)),u.map(xe.filter(q.isNonEmpty)),u.map(xe.map(s)),u.catchTag(`GitError`,()=>u.succeed([])))}),l=e=>e===`A`?`A`:e===`D`?`D`:e===`R`?`R`:e===`C`?`C`:e===`?`?`?`:`M`,d=u.fn(`Git.getChangedFiles`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`status`,`--porcelain`],operation:`getting working tree changes`}).pipe(u.map(q.split(`
25
+ `)),u.map(xe.filter(q.isNonEmpty)),u.map(xe.map(e=>{let t=e.at(0)??`M`;return{path:e.slice(3).trim(),status:l(t)}})),u.catchTag(`GitError`,()=>u.succeed([]))):yield*t({args:[`diff`,`--name-status`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`],operation:`getting changed files`,trim:!0}).pipe(u.map(q.split(`
26
+ `)),u.map(xe.map(q.trim)),u.map(xe.filter(q.isNonEmpty)),u.map(xe.map(e=>{let t=e.split(` `),n=(t[0]??`M`).at(0)??`M`;return{path:(n===`R`||n===`C`?t[2]:t[1])??``,status:l(n)}})),u.catchTag(`GitError`,()=>u.succeed([])))}),f=u.fn(`Git.getDiffPreview`)(function*(e){return e._tag===`WorkingTree`?yield*t({args:[`diff`,`HEAD`],operation:`getting diff preview`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``))):yield*t({args:[`diff`,e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:`${e.hash}^..${e.hash}`],operation:`getting diff preview`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)))}),m=u.fn(`Git.getRecentCommits`)(function*(e){return yield*t({args:[`log`,`--format=%H %h %s`,e],operation:`getting recent commits`,trim:!0}).pipe(u.map(q.split(`
27
+ `)),u.map(xe.map(q.trim)),u.map(xe.filter(q.isNonEmpty)),u.map(xe.map(e=>{let[t,n,...r]=e.split(` `);return{hash:t??``,shortHash:n??``,subject:r.join(` `)}})),u.catchTag(`GitError`,()=>u.succeed([])))}),h=u.fn(`Git.getCommitSummary`)(function*(e){return yield*t({args:[`log`,`-1`,`--format=%H %h %s`,e],operation:`getting commit summary`,trim:!0}).pipe(u.map(e=>{let[t,n,...r]=e.split(` `);if(!(!t||!n))return{hash:t,shortHash:n,subject:r.join(` `)}}),u.catchTag(`GitError`,()=>u.succeed(void 0)))}),g=u.fn(`Git.computeFingerprint`)(function*(){let e=yield*t({args:[`rev-parse`,`HEAD`],operation:`getting HEAD for fingerprint`,trim:!0}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)));if(!e)return;let n=yield*t({args:[`diff`],operation:`getting unstaged diff for fingerprint`}).pipe(u.catchTag(`GitError`,()=>u.succeed(``))),r=yield*t({args:[`diff`,`--cached`],operation:`getting staged diff for fingerprint`}).pipe(u.catchTag(`GitError`,()=>u.succeed(``)));return Ce.createHash(`sha256`).update(e).update(`\0`).update(n).update(`\0`).update(r).digest(`hex`)}),_=u.fn(`ensureStateDir`)(function*(t){let n=G.join(t,Wp);yield*e.makeDirectory(n,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void));let r=G.join(n,`.gitignore`);return(yield*e.exists(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))||(yield*e.writeFileString(r,`*
28
+ `).pipe(u.catchTag(`PlatformError`,()=>u.void))),n}),v=u.gen(function*(){let e=yield*_(yield*Yp);return G.join(e,`last-tested`)}),y=u.fn(`Git.loadSavedFingerprint`)(function*(){let t=yield*v;return yield*e.readFileString(t).pipe(u.map(q.trim),u.catchTag(`PlatformError`,()=>u.succeed(void 0)))}),b=u.fn(`Git.saveTestedFingerprint`)(function*(){let t=yield*g();if(!t)return;let n=yield*v;yield*e.writeFileString(n,t)});return{withRepoRoot:r,getMainBranch:i,getCurrentBranch:a,isInsideWorkTree:o,getFileStats:c,getChangedFiles:d,getDiffPreview:f,getRecentCommits:m,getCommitSummary:h,getState:u.fn(`Git.getState`)(function*(){if(!(yield*o))return new pn({isGitRepo:!1,currentBranch:`HEAD`,mainBranch:void 0,isOnMain:!1,hasChangesFromMain:!1,hasUnstagedChanges:!1,hasBranchCommits:!1,branchCommitCount:0,fileStats:[],workingTreeFileStats:[],fingerprint:void 0,savedFingerprint:void 0});let[e,t,n,r]=yield*u.all([a,i,g(),y()],{concurrency:`unbounded`}),s=e===t,[l,d,f]=yield*u.all([c(gn.makeUnsafe({_tag:`Changes`,mainBranch:t})),c(gn.makeUnsafe({_tag:`WorkingTree`})),m(`${t}..HEAD`)],{concurrency:`unbounded`});return new pn({isGitRepo:!0,currentBranch:e,mainBranch:t,isOnMain:s,hasChangesFromMain:l.length>0,hasUnstagedChanges:d.length>0,hasBranchCommits:f.length>0,branchCommitCount:f.length,fileStats:l,workingTreeFileStats:d,fingerprint:n,savedFingerprint:r})}),computeFingerprint:g,saveTestedFingerprint:b}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer));static withRepoRoot=t=>{let n=m.effect(Yp)(u.tryPromise({try:()=>Up(t).revparse([`--show-toplevel`]),catch:e=>new Jp({cause:e})}).pipe(u.map(e=>e.trim())));return m.mergeAll(e.layer.pipe(m.provide(n)),n)}},Zp=class extends S.ErrorClass(`@supervisor/ExecutionError`)({_tag:S.tag(`ExecutionError`),reason:S.Union([Ia,Ba,Ra,za])}){displayName=this.reason.displayName??`Browser testing failed`;message=this.reason.message},Qp=class extends C.Service()(`@supervisor/Executor`,{make:u.gen(function*(){let e=yield*Ga,t=yield*Xp,n=u.fn(`Executor.gatherContext`)(function*(e){let n=yield*t.getCurrentBranch,r=yield*t.getMainBranch,i=yield*t.getChangedFiles(e),a=yield*t.getDiffPreview(e),o=e._tag===`Branch`||e._tag===`Changes`?`${e.mainBranch}..HEAD`:e._tag===`Commit`?`-1 ${e.hash}`:`HEAD~5..HEAD`,s=yield*t.getRecentCommits(o);return{currentBranch:n,mainBranch:r,changedFiles:i.slice(0,12),recentCommits:s.slice(0,5),diffPreview:a}});return{execute:u.fn(`Executor.execute`)(function*(t){let a=yield*n(t.changesFor),o=eo({userInstruction:t.instruction,scope:t.changesFor._tag,currentBranch:a.currentBranch,mainBranch:a.mainBranch,changedFiles:a.changedFiles,recentCommits:a.recentCommits,diffPreview:a.diffPreview,baseUrl:t.baseUrl,isHeadless:t.isHeadless,requiresCookies:t.requiresCookies,savedFlow:t.savedFlow,learnings:t.learnings,testCoverage:t.testCoverage}),s=hn.makeUnsafe(crypto.randomUUID()),c=G.join(process.cwd(),Wp,`replays`,`${s}.ndjson`),l=new Dn({id:s,changesFor:t.changesFor,currentBranch:a.currentBranch,diffPreview:a.diffPreview,fileStats:[],instruction:t.instruction,baseUrl:t.baseUrl?_.some(t.baseUrl):_.none(),isHeadless:t.isHeadless,requiresCookies:t.requiresCookies,testCoverage:t.testCoverage?_.some(t.testCoverage):_.none(),title:t.instruction,rationale:`Direct execution`,steps:[]}),u=new Qn({...l,events:[new On({plan:l})]}),d=[{name:`EXPECT_REPLAY_OUTPUT_PATH`,value:c}];t.liveViewUrl&&d.push({name:i,value:t.liveViewUrl}),t.requiresCookies||d.push({name:r,value:`1`});let f=new nr({cwd:process.cwd(),sessionId:_.none(),prompt:o,systemPrompt:_.none(),mcpEnv:d});return e.stream(f).pipe(w.mapAccum(()=>u,(e,t)=>{let n=e.addEvent(t);return[n,[n]]}),w.mapError(e=>new Zp({reason:e})))},w.unwrap)}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer))},$p=class extends C.Service()(`@supervisor/Reporter`,{make:u.gen(function*(){return{report:u.fn(`Reporter.report`)(function*(e){let t=e.events.filter(e=>e._tag===`StepFailed`),n=e.events.filter(e=>e._tag===`StepCompleted`),r=e.events.find(e=>e._tag===`RunFinished`),i=r?r.summary:t.length>0?`${t.length} step(s) failed, ${n.length} passed`:`${n.length} step(s) completed`,a=e.events.filter(e=>e._tag===`ToolResult`&&e.toolName.endsWith(`__screenshot`)&&!e.isError).map(e=>e._tag===`ToolResult`?e.result:``).filter(Boolean);return new $n({...e,summary:i,screenshotPaths:a,pullRequest:_.none(),testCoverageReport:e.testCoverage})})}})}){static layer=m.effect(this)(this.make)};const em=e=>{let t=[`format_version: ${e.formatVersion}`,`title: ${JSON.stringify(e.title)}`,`description: ${JSON.stringify(e.description)}`,`slug: ${JSON.stringify(e.slug)}`,`saved_target_scope: ${JSON.stringify(e.savedTargetScope)}`,`saved_target_display_name: ${JSON.stringify(e.savedTargetDisplayName)}`];return e.selectedCommit!==void 0&&t.push(`selected_commit: ${JSON.stringify(e.selectedCommit)}`),t.push(`flow: ${JSON.stringify(e.flow)}`),t.push(`environment: ${JSON.stringify(e.environment)}`),t.join(`
29
+ `)},tm=e=>`---\n${em(e)}\n---\n`,nm=e=>e.startsWith(`"`)&&e.endsWith(`"`)?JSON.parse(e):e,rm=e=>v.isObject(e)&&typeof e.id==`string`&&typeof e.title==`string`&&typeof e.instruction==`string`&&typeof e.expectedOutcome==`string`,im=e=>v.isObject(e)?{title:typeof e.title==`string`?e.title:``,userInstruction:typeof e.userInstruction==`string`?e.userInstruction:``,steps:Array.isArray(e.steps)?e.steps.filter(rm):[]}:{title:``,userInstruction:``,steps:[]},am=e=>v.isObject(e)?{baseUrl:typeof e.baseUrl==`string`?e.baseUrl:``,cookies:typeof e.cookies==`boolean`?e.cookies:!1}:{baseUrl:``,cookies:!1},om=e=>{let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)throw Error(`Invalid saved flow file: no frontmatter found`);let n=t[1],r=new Map;for(let e of n.split(`
30
+ `)){if(e===`selected_commit: undefined`)continue;let t=e.indexOf(`: `);if(t===-1)continue;let n=e.slice(0,t),i=e.slice(t+2);r.set(n,i)}let i={formatVersion:Number(r.get(`format_version`)),title:nm(r.get(`title`)??``),description:nm(r.get(`description`)??``),slug:nm(r.get(`slug`)??``),savedTargetScope:nm(r.get(`saved_target_scope`)??``),savedTargetDisplayName:nm(r.get(`saved_target_display_name`)??``),flow:im(JSON.parse(r.get(`flow`)??`{}`)),environment:am(JSON.parse(r.get(`environment`)??`{}`))},a=r.get(`selected_commit`);return a!==void 0&&(i.selectedCommit=nm(a)),i},sm=u.fn(`ensureStateDir`)(function*(e,t){let n=G.join(t,Wp);yield*e.makeDirectory(n,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void));let r=G.join(n,`.gitignore`);return(yield*e.exists(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))||(yield*e.writeFileString(r,`*
31
+ `).pipe(u.catchTag(`PlatformError`,()=>u.void))),n}),cm=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60).replace(/-$/,``),lm=e=>({formatVersion:3,title:e.title,description:e.instruction.slice(0,120),slug:cm(e.title),savedTargetScope:e.changesFor._tag,savedTargetDisplayName:_n(e.changesFor),flow:{title:e.title,userInstruction:e.instruction,steps:e.steps.map(e=>{let t=_.getOrElse(e.summary,()=>``);return{id:e.id,title:e.title,instruction:e.instruction===e.title?t||e.title:e.instruction,expectedOutcome:e.expectedOutcome||t}})},environment:{baseUrl:_.getOrElse(e.baseUrl,()=>``),cookies:e.requiresCookies}});var um=class extends C.Service()(`@supervisor/FlowStorage`,{make:u.gen(function*(){let e=yield*p.FileSystem,t=u.gen(function*(){let t=yield*sm(e,yield*Yp);return G.join(t,`flows`)});return{save:u.fn(`FlowStorage.save`)(function*(n){let r=lm(n),i=yield*t,a=G.join(i,`${r.slug}.md`);return yield*e.makeDirectory(i,{recursive:!0}).pipe(u.catchTag(`PlatformError`,()=>u.void)),yield*e.writeFileString(a,tm(r)),yield*u.logInfo(`Flow saved`,{slug:r.slug,stepCount:r.flow.steps.length,filePath:a}),r}),list:u.fn(`FlowStorage.list`)(function*(){let n=yield*t;if(!(yield*e.exists(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1)))))return[];let r=(yield*e.readDirectory(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed([])))).filter(e=>e.endsWith(`.md`)),i=[];for(let t of r){let r=yield*e.readFileString(G.join(n,t)).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(!r)continue;let a=yield*u.try({try:()=>om(r),catch:()=>({_tag:`FlowParseError`})}).pipe(u.catchTag(`FlowParseError`,()=>u.succeed(void 0)));a&&i.push(a)}return yield*u.logDebug(`Flows listed`,{count:i.length}),i})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer))};const dm=(e,t)=>{try{return le(`git checkout ${t}`,{cwd:e,encoding:`utf-8`,timeout:5e3,stdio:`pipe`}),!0}catch{return!1}};var fm=class extends S.ErrorClass(`GitHubCommandError`)({_tag:S.tag(`GitHubCommandError`),cause:S.String}){message=`GitHub CLI command failed: ${this.cause}`},pm=class extends C.Service()(`@supervisor/GitHub`,{make:u.gen(function*(){let e=yield*Pe,t=yield*ke,n=u.fn(`GitHub.runGhCommand`)(function*(t,n){return yield*e.string(ve.make(`gh`,n,{cwd:t})).pipe(u.timeout(15e3),u.catchTags({PlatformError:e=>u.fail(new fm({cause:e.message})),TimeoutError:()=>u.fail(new fm({cause:`command timed out`}))}),u.map(e=>e.trim()))}),r=u.fn(`GitHub.findPullRequest`)(function*(e,t){let r=yield*n(e,[`pr`,`list`,`--head`,g.value(t).pipe(g.when({_tag:`Branch`},e=>e.branchName),g.exhaustive),`--state`,`open`,`--limit`,`1`,`--json`,`number,url,title,headRefName`]);return yield*S.decodeEffect(S.fromJsonString(S.Array(Gn)))(r).pipe(u.map(o.head),u.catchTag(`SchemaError`,()=>u.succeed(_.none())))}),i=S.fromJsonString(S.Array(vn));return{findPullRequest:r,listPullRequests:u.fn(`GitHub.listPullRequests`)(function*(e){let t=yield*n(e,[`pr`,`list`,`--state`,`all`,`--json`,`number,headRefName,author,state,updatedAt`,`--limit`,`100`]).pipe(u.catchTag(`GitHubCommandError`,()=>u.succeed(`[]`)));return(yield*S.decodeEffect(i)(t).pipe(u.catchTag(`SchemaError`,u.die))).map(e=>new bn({name:e.headRefName,author:e.author.login,prNumber:e.number,prStatus:e.state===`OPEN`?`open`:e.state===`MERGED`||e.state===`CLOSED`?`merged`:null,updatedAt:e.updatedAt}))}),addComment:u.fn(`GitHub.addComment`)(function*(e,r,i){yield*u.scoped(u.gen(function*(){let a=fe(yield*t.makeTempDirectoryScoped({prefix:`expect-comment-`}),`pull-request-comment.md`);yield*t.writeFileString(a,i),yield*n(e,[`pr`,`comment`,String(r.number),`--body-file`,a])}))})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer))};const mm=e=>G.join(Ae.homedir(),Wp,`${e}.json`),hm=new Map,gm={getItem:async e=>{try{let t=await Ie.readFile(mm(e),`utf-8`);return hm.set(e,t),t}catch{return null}},setItem:async(e,t)=>{if(hm.get(e)===t)return;hm.set(e,t);let n=mm(e);await Ie.mkdir(G.dirname(n),{recursive:!0}),await Ie.writeFile(n,t,`utf-8`)},removeItem:async e=>{hm.delete(e);try{await Ie.unlink(mm(e))}catch{}}},_m=e=>G.join(process.cwd(),Wp,`${e}.json`),vm=new Map,ym={getItem:async e=>{try{let t=await Ie.readFile(_m(e),`utf-8`);return vm.set(e,t),t}catch{return null}},setItem:async(e,t)=>{if(vm.get(e)===t)return;vm.set(e,t);let n=_m(e);await Ie.mkdir(G.dirname(n),{recursive:!0}),await Ie.writeFile(n,t,`utf-8`)},removeItem:async e=>{vm.delete(e);try{await Ie.unlink(_m(e))}catch{}}},bm=[/from\s+["']([^"']+)["']/g,/import\s*\(\s*["']([^"']+)["']\s*\)/g,/require\s*\(\s*["']([^"']+)["']\s*\)/g],xm=/\.(?:test|spec|e2e)\.(?:ts|tsx|js|jsx|mts|mjs|cts|cjs)$/,Sm=/(?:^|[/\\])(?:__tests?__|tests?)[/\\]/,Cm=/\.(?:ts|tsx|js|jsx|mts|mjs|cts|cjs)$/,wm=e=>{let t=G.extname(e).toLowerCase();return Gp.includes(t)},Tm=e=>e.split(/[/\\]/).some(e=>Kp.has(e)),Em=e=>!!(xm.test(e)||Sm.test(e)&&Cm.test(e)),Dm=e=>{let t=[];for(let n of bm){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];e&&t.push(e)}}return t},Om=(e,t)=>{let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(n.has(t))continue;n.add(t);let i=e.get(t);if(i)for(let e of i)n.has(e)||r.push(e)}return n.delete(t),n},km=e=>u.tryPromise({try:()=>new Promise(t=>{ce(`git`,[`ls-files`,`--cached`,`--others`,`--exclude-standard`],{cwd:e,maxBuffer:10*1024*1024},(e,n)=>{if(e){t([]);return}t(n.split(`
32
+ `).map(e=>e.trim()).filter(e=>e.length>0))})}),catch:()=>[]}),Am=async e=>{try{let{ResolverFactory:t}=await import(`oxc-resolver`);return new t({tsconfig:{configFile:G.join(e,`tsconfig.json`),references:`auto`},extensions:[...Gp],mainFields:[`module`,`main`],conditionNames:[`import`,`require`,`default`]})}catch{return}},jm=(e,t,n)=>{try{return e.sync(t,n).path??void 0}catch{return}},Mm=(e,t,n)=>u.gen(function*(){let r=t.filter(e=>wm(e)&&!Tm(e)),i=yield*u.promise(()=>Am(e));if(!i)return new Map;let a=new Map;return yield*u.forEach(r,t=>u.gen(function*(){let r=G.join(e,t),o=yield*n.readFileString(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(!o)return;let s=Dm(o),c=new Set;for(let t of s)if(t.startsWith(`.`)||t.startsWith(`@`)||t.startsWith(`~`)){let n=jm(i,G.dirname(r),t);if(n){let t=G.relative(e,n);Tm(t)||c.add(t)}}c.size>0&&a.set(t,c)}),{concurrency:50}),a}),Nm=e=>e.filter(e=>!Tm(e)&&Em(e)).slice(0,200);var Pm=class extends C.Service()(`@supervisor/TestCoverage`,{make:u.gen(function*(){let e=yield*p.FileSystem;return{analyze:u.fn(`TestCoverage.analyze`)(function*(t){yield*u.annotateCurrentSpan({changedFileCount:t.length});let n=yield*Yp,r=yield*km(n),i=Nm(r),a=yield*Mm(n,r,e),o=new Map;for(let e of i){let t=Om(a,e);t.add(e);for(let n of t){let t=o.get(n)??[];t.push(e),o.set(n,t)}}let s=t.filter(e=>Cm.test(e.path)&&!Em(e.path)&&e.status!==`D`),c=s.map(e=>{let t=o.get(e.path)??[];return{path:e.path,testFiles:t,covered:t.length>0}}),l=c.filter(e=>e.covered).length,d=s.length,f=d>0?Math.round(l/d*100):100;return yield*u.logInfo(`Test coverage analyzed`,{coveredCount:l,totalCount:d,percent:f,testFileCount:i.length,graphEdgeCount:a.size}),{entries:c,coveredCount:l,totalCount:d,percent:f}})}})}){static layer=m.effect(this)(this.make).pipe(m.provide(be.layer))};const Fm=e=>e.pipe(u.provide(pm.layer)),Im=async e=>{let t=[];if(e.hasUntestedChanges&&t.push(Kn.makeUnsafe({_tag:`WorkingTree`})),e.mainBranch){let n=process.cwd(),r=await u.runPromise(u.gen(function*(){return yield*(yield*Xp).getRecentCommits(`${e.mainBranch}..HEAD`)}).pipe(u.provide(Xp.withRepoRoot(n))));for(let e of r)t.push(Kn.makeUnsafe({_tag:`Commit`,hash:e.hash,shortHash:e.shortHash,subject:e.subject}))}return t},Lm=e=>u.runPromise(Fm(pm.use(t=>t.listPullRequests(e)))),Rm=async e=>{let t=await Lm(process.cwd()),n=t.filter(e=>e.prNumber!==null&&e.prStatus===`open`).map(e=>Kn.makeUnsafe({_tag:`PullRequest`,branch:e})),r=t.filter(e=>e.prNumber!==null&&e.prStatus===`merged`).slice(0,5).map(e=>Kn.makeUnsafe({_tag:`PullRequest`,branch:e})),i=t.filter(t=>t.name!==e.currentBranch&&t.prNumber===null).map(e=>Kn.makeUnsafe({_tag:`Branch`,branch:e}));return[...n,...r,...i]},zm=(e,t)=>e._tag===`WorkingTree`&&t&&!t.isOnMain?t.currentBranch:Yn(e),Bm=(e,t)=>{if(e._tag===`WorkingTree`&&t){let e=[];if(t.fileStats.length>0){let n=t.fileStats.reduce((e,t)=>e+t.added,0),r=t.fileStats.reduce((e,t)=>e+t.removed,0),i=t.fileStats.length,a=[];n>0&&a.push(`+${n}`),r>0&&a.push(`-${r}`),a.length>0?e.push(`${a.join(` `)} in ${i} file${i===1?``:`s`}`):e.push(`${i} file${i===1?``:`s`}`)}if(t.branchCommitCount>0&&e.push(`${t.branchCommitCount} commit${t.branchCommitCount===1?``:`s`}`),e.length>0)return e.join(`, `)}return Xn(e)},Vm=(e,t)=>e._tag===`WorkingTree`?zm(e,t):Zn(e),Hm=(e,t,n)=>{if(!t)return[...e];let r=t.toLowerCase();return e.filter(e=>(e._tag===`WorkingTree`?`local changes ${n?.currentBranch??``}`:Jn(e)).toLowerCase().includes(r))},Um=()=>N({queryKey:[`remote-branches`],queryFn:()=>Lm(process.cwd())}),Wm=e=>{let t=ie(10);if(t[0]!==`19aae044389a98cd743b540aea8d28df87ba20582cdcc28d3b06005d495ed4de`){for(let e=0;e<10;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`19aae044389a98cd743b540aea8d28df87ba20582cdcc28d3b06005d495ed4de`}let{message:n}=e,r=Pt(),i;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=V(Le,{type:`dots`}),t[1]=i):i=t[1];let a;t[2]===r.SELECTION?a=t[3]:(a=V(O,{color:r.SELECTION,children:i}),t[2]=r.SELECTION,t[3]=a);let o;t[4]===n?o=t[5]:(o=n?H(O,{children:[` `,n]}):null,t[4]=n,t[5]=o);let s;return t[6]!==r.DIM||t[7]!==a||t[8]!==o?(s=H(O,{color:r.DIM,children:[a,o]}),t[6]=r.DIM,t[7]=a,t[8]=o,t[9]=s):s=t[9],s},Gm=(e,t)=>{let n=Math.max(0,t-ze(e));return e+` `.repeat(n)},Km=({itemCount:e,visibleCount:t,initialIndex:n})=>{let[r,i]=L(n??0),a=I(e);return a.current!==e&&(a.current=e,i(t=>Math.min(t,Math.max(0,e-1)))),{highlightedIndex:r,setHighlightedIndex:i,scrollOffset:F(()=>{if(e<=t)return 0;let n=Math.floor(t/2),i=e-t;return Math.min(i,Math.max(0,r-n))},[e,t,r]),handleNavigation:oe((t,n)=>n.downArrow||t===`j`||n.ctrl&&t===`n`?(i(t=>Math.min(e-1,t+1)),!0):n.upArrow||t===`k`||n.ctrl&&t===`p`?(i(e=>Math.max(0,e-1)),!0):!1,[e])}},qm=/(?:https?:\/\/|localhost[:/]|[\w-]+\.[\w-]+\.[\w]+|[\w-]+\.(com|org|net|io|dev|app|co|me|ai))\S*/i,Jm=e=>qm.test(e),Ym=Ve.taggedEnum(),Xm=e=>Jm(e.instruction)?Ym.Testing(e):Ym.PortPicker(e),Zm=Be(e=>({screen:Ym.Main(),previousScreen:Ym.Main(),navigateTo:t=>e(e=>({screen:t,previousScreen:e.screen})),setScreen:t=>e({screen:t})})),Qm=new re({defaultOptions:{queries:{staleTime:1/0,retry:!1}}}),$m=e=>{let t=ie(18);if(t[0]!==`ebd3be31f5201c04dd238bf1bd9d32bf671ecbefa6ad88d45037fbe949e8bb0c`){for(let e=0;e<18;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`ebd3be31f5201c04dd238bf1bd9d32bf671ecbefa6ad88d45037fbe949e8bb0c`}let{title:n,subtitle:r,showDivider:i}=e,a=i===void 0?!0:i,[o]=jt(),s,c,l;t[1]!==r||t[2]!==n?(l=n.toUpperCase(),s=r?` │ ${r}`:``,c=ze(l),t[1]=r,t[2]=n,t[3]=s,t[4]=c,t[5]=l):(s=t[3],c=t[4],l=t[5]);let u=c+ze(s),d=a?Math.max(0,o-u-3):0,f;t[6]===l?f=t[7]:(f=V(O,{bold:!0,color:J.text,children:l}),t[6]=l,t[7]=f);let p;t[8]!==r||t[9]!==s?(p=r?V(O,{color:J.textMuted,children:s}):null,t[8]=r,t[9]=s,t[10]=p):p=t[10];let m;t[11]!==d||t[12]!==a?(m=a?H(O,{color:J.border,children:[` `,`─`.repeat(d)]}):null,t[11]=d,t[12]=a,t[13]=m):m=t[13];let h;return t[14]!==f||t[15]!==p||t[16]!==m?(h=H(O,{children:[f,p,m]}),t[14]=f,t[15]=p,t[16]=m,t[17]=h):h=t[17],h},eh=()=>{let e=ie(39);if(e[0]!==`155bac1331928275f0977c44c5021af2a99f257236d72aa818a512bae62664a8`){for(let t=0;t<39;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`155bac1331928275f0977c44c5021af2a99f257236d72aa818a512bae62664a8`}let[t]=jt(),n=Zm(th),r=Pt(),[i,a]=L(null),[o,s]=L(``),[c,l]=L(`recent`),[u,d]=L(!1),[f,p]=L(void 0),{data:m,isLoading:h}=Um(),g=m===void 0?[]:m,_=bn.filterBranches(g,c,o),{highlightedIndex:v,setHighlightedIndex:y,scrollOffset:b,handleNavigation:x}=Km({itemCount:_.length,visibleCount:15}),S=t-2-32-16-2,C=_.slice(b,b+15),w;e[1]===y?w=e[2]:(w=e=>{s(Ot(e)),y(0)},e[1]=y,e[2]=w);let ee=w,T;e[3]===n?T=e[4]:(T=e=>{dm(process.cwd(),e)?(p(void 0),Qm.invalidateQueries({queryKey:[`git-state`]}),n(Ym.Main())):p(`Could not checkout "${e}". You may have uncommitted changes or the branch may not exist locally.`)},e[3]=n,e[4]=T);let D=T,k;e[5]!==c||e[6]!==y?(k=e=>{l(yn[(yn.indexOf(c)+e+yn.length)%yn.length]),y(0)},e[5]=c,e[6]=y,e[7]=k):k=e[7];let A=k;te((e,t)=>{if(u){t.escape&&d(!1);return}if(!x(e,t)){if(t.rightArrow&&A(1),t.leftArrow&&A(-1),t.return){let e=_[v];e&&(p(void 0),D(e.name))}e===`/`&&d(!0)}});let ne;e[8]!==i||e[9]!==D?(ne=(e,t)=>{i&&(e.toLowerCase()===`y`&&(p(void 0),D(i.name),a(null)),(e.toLowerCase()===`n`||t.escape)&&a(null))},e[8]=i,e[9]=D,e[10]=ne):ne=e[10];let re=i!==null,j;e[11]===re?j=e[12]:(j={isActive:re},e[11]=re,e[12]=j),te(ne,j);let M=E,N=`${_.length} branches`,ae;e[13]===N?ae=e[14]:(ae=V(E,{paddingX:1,children:V($m,{title:`Select a PR or branch to test`,subtitle:N})}),e[13]=N,e[14]=ae);let oe;e[15]!==r||e[16]!==c||e[17]!==y?(oe=yn.map((e,t)=>{let n=e===c,i=t<yn.length-1?` · `:``,a={recent:r.CYAN,all:r.TEXT,open:r.GREEN,draft:r.DIM,merged:r.PURPLE,"no-pr":r.YELLOW};return H(E,{children:[V(Lt,{fullWidth:!1,onClick:()=>{l(e),y(0)},children:V(O,{color:n?a[e]:r.DIM,children:n?`[${e}]`:e})}),V(O,{color:r.DIM,children:i})]},e)}),e[15]=r,e[16]=c,e[17]=y,e[18]=oe):oe=e[18];let P;e[19]===oe?P=e[20]:(P=V(E,{marginTop:1,paddingX:1,children:oe}),e[19]=oe,e[20]=P);let se=h?V(E,{marginTop:1,paddingX:1,children:V(Wm,{message:`Fetching PRs...`})}):H(E,{marginTop:1,flexDirection:`column`,height:15,overflow:`hidden`,paddingX:1,children:[C.map((e,t)=>{let n=t+b,i=n===v;return H(Lt,{onClick:()=>{y(n),D(e.name)},children:[V(O,{color:i?r.PRIMARY:r.DIM,children:i?`${U.pointer} `:` `}),V(O,{color:i?r.PRIMARY:r.DIM,bold:i,children:Gm(Re(e.name,31),32)}),V(O,{color:r.CYAN,children:Gm(Re(e.author||`—`,15),16)}),e.prNumber&&e.prStatus?V(O,{color:e.prStatus===`open`?r.GREEN:e.prStatus===`merged`?r.PURPLE:r.DIM,children:Re(`#${e.prNumber} ${e.prStatus}`,S)}):V(O,{color:r.DIM,children:`—`})]},e.name)}),_.length===0&&V(O,{color:r.DIM,children:`No matching branches`})]}),F;e[21]!==r||e[22]!==f?(F=f?V(E,{marginTop:1,paddingX:1,children:V(O,{color:r.RED,children:f})}):null,e[21]=r,e[22]=f,e[23]=F):F=e[23];let I;e[24]!==r||e[25]!==i?(I=i?H(Ft,{color:r.YELLOW,marginTop:1,children:[H(O,{color:r.YELLOW,bold:!0,children:[`Switch to `,i.name,`?`]}),H(O,{color:r.DIM,children:[`Press `,V(O,{color:r.PRIMARY,children:`y`}),` to continue or`,` `,V(O,{color:r.PRIMARY,children:`n`}),` to cancel.`]})]}):null,e[24]=r,e[25]=i,e[26]=I):I=e[26];let R;e[27]!==ee||e[28]!==u||e[29]!==o?(R=V(E,{paddingX:1,children:V(Wt,{isSearching:u,query:o,onChange:ee})}),e[27]=ee,e[28]=u,e[29]=o,e[30]=R):R=e[30];let z;return e[31]!==M||e[32]!==ae||e[33]!==P||e[34]!==se||e[35]!==F||e[36]!==I||e[37]!==R?(z=H(M,{flexDirection:`column`,width:`100%`,paddingY:1,children:[ae,P,se,F,I,R]}),e[31]=M,e[32]=ae,e[33]=P,e[34]=se,e[35]=F,e[36]=I,e[37]=R,e[38]=z):z=e[38],z};function th(e){return e.setScreen}const nh=de.join(process.cwd(),`.expect`,`logs.md`),rh=h.formatLogFmt.pipe(h.toFile(nh)),ih=m.effectDiscard(u.gen(function*(){let e=yield*p.FileSystem;yield*e.makeDirectory(de.dirname(nh),{recursive:!0}),yield*e.writeFileString(de.join(de.dirname(nh),`.gitignore`),`*
33
+ `)})),ah=m.mergeAll(ih,h.layer([rh])).pipe(m.provide(He.layer));var oh=n(((t,n)=>{(function(r,i){typeof t==`object`&&typeof n==`object`?n.exports=i(e(`child_process`),e(`crypto`)):typeof define==`function`&&define.amd?define([`child_process`,`crypto`],i):typeof t==`object`?t[`electron-machine-id`]=i(e(`child_process`),e(`crypto`)):r[`electron-machine-id`]=i(r.child_process,r.crypto)})(t,function(t,n){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p=``,t(0)}([function(e,t,n){e.exports=n(34)},function(e,t,n){var r=n(29)(`wks`),i=n(33),a=n(2).Symbol,o=typeof a==`function`,s=e.exports=function(e){return r[e]||(r[e]=o&&a[e]||(o?a:i)(`Symbol.`+e))};s.store=r},function(e,t){var n=e.exports=typeof window<`u`&&window.Math==Math?window:typeof self<`u`&&self.Math==Math?self:Function(`return this`)();typeof __g==`number`&&(__g=n)},function(e,t,n){var r=n(9);e.exports=function(e){if(!r(e))throw TypeError(e+` is not an object!`);return e}},function(e,t,n){e.exports=!n(24)(function(){return Object.defineProperty({},`a`,{get:function(){return 7}}).a!=7})},function(e,t,n){var r=n(12),i=n(17);e.exports=n(4)?function(e,t,n){return r.f(e,t,i(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){var n=e.exports={version:`2.4.0`};typeof __e==`number`&&(__e=n)},function(e,t,n){var r=n(14);e.exports=function(e,t,n){if(r(e),t===void 0)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t){e.exports=function(e){return typeof e==`object`?e!==null:typeof e==`function`}},function(e,t){e.exports={}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(3),i=n(26),a=n(32),o=Object.defineProperty;t.f=n(4)?Object.defineProperty:function(e,t,n){if(r(e),t=a(t,!0),r(n),i)try{return o(e,t,n)}catch{}if(`get`in n||`set`in n)throw TypeError(`Accessors not supported!`);return`value`in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(42),i=n(15);e.exports=function(e){return r(i(e))}},function(e,t){e.exports=function(e){if(typeof e!=`function`)throw TypeError(e+` is not a function!`);return e}},function(e,t){e.exports=function(e){if(e==null)throw TypeError(`Can't call method on `+e);return e}},function(e,t,n){var r=n(9),i=n(2).document,a=r(i)&&r(i.createElement);e.exports=function(e){return a?i.createElement(e):{}}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(12).f,i=n(8),a=n(1)(`toStringTag`);e.exports=function(e,t,n){e&&!i(e=n?e:e.prototype,a)&&r(e,a,{configurable:!0,value:t})}},function(e,t,n){var r=n(29)(`keys`),i=n(33);e.exports=function(e){return r[e]||(r[e]=i(e))}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(11),i=n(1)(`toStringTag`),a=r(function(){return arguments}())==`Arguments`,o=function(e,t){try{return e[t]}catch{}};e.exports=function(e){var t,n,s;return e===void 0?`Undefined`:e===null?`Null`:typeof(n=o(t=Object(e),i))==`string`?n:a?r(t):(s=r(t))==`Object`&&typeof t.callee==`function`?`Arguments`:s}},function(e,t){e.exports=`constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf`.split(`,`)},function(e,t,n){var r=n(2),i=n(6),a=n(7),o=n(5),s=`prototype`,c=function(e,t,n){var l,u,d,f=e&c.F,p=e&c.G,m=e&c.S,h=e&c.P,g=e&c.B,_=e&c.W,v=p?i:i[t]||(i[t]={}),y=v[s],b=p?r:m?r[t]:(r[t]||{})[s];for(l in p&&(n=t),n)u=!f&&b&&b[l]!==void 0,u&&l in v||(d=u?b[l]:n[l],v[l]=p&&typeof b[l]!=`function`?n[l]:g&&u?a(d,r):_&&b[l]==d?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[s]=e[s],t}(d):h&&typeof d==`function`?a(Function.call,d):d,h&&((v.virtual||={})[l]=d,e&c.R&&y&&!y[l]&&o(y,l,d)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t){e.exports=function(e){try{return!!e()}catch{return!0}}},function(e,t,n){e.exports=n(2).document&&document.documentElement},function(e,t,n){e.exports=!n(4)&&!n(24)(function(){return Object.defineProperty(n(16)(`div`),`a`,{get:function(){return 7}}).a!=7})},function(e,t,n){var r=n(28),i=n(23),a=n(57),o=n(5),s=n(8),c=n(10),l=n(45),u=n(18),d=n(52),f=n(1)(`iterator`),p=!([].keys&&`next`in[].keys()),m=`@@iterator`,h=`keys`,g=`values`,_=function(){return this};e.exports=function(e,t,n,v,y,b,x){l(n,t,v);var S,C,w,ee=function(e){if(!p&&e in O)return O[e];switch(e){case h:return function(){return new n(this,e)};case g:return function(){return new n(this,e)}}return function(){return new n(this,e)}},T=t+` Iterator`,E=y==g,D=!1,O=e.prototype,k=O[f]||O[m]||y&&O[y],A=k||ee(y),te=y?E?ee(`entries`):A:void 0,ne=t==`Array`&&O.entries||k;if(ne&&(w=d(ne.call(new e)),w!==Object.prototype&&(u(w,T,!0),r||s(w,f)||o(w,f,_))),E&&k&&k.name!==g&&(D=!0,A=function(){return k.call(this)}),r&&!x||!p&&!D&&O[f]||o(O,f,A),c[t]=A,c[T]=_,y)if(S={values:E?A:ee(g),keys:b?A:ee(h),entries:te},x)for(C in S)C in O||a(O,C,S[C]);else i(i.P+i.F*(p||D),t,S);return S}},function(e,t){e.exports=!0},function(e,t,n){var r=n(2),i=`__core-js_shared__`,a=r[i]||(r[i]={});e.exports=function(e){return a[e]||(a[e]={})}},function(e,t,n){var r,i,a,o=n(7),s=n(41),c=n(25),l=n(16),u=n(2),d=u.process,f=u.setImmediate,p=u.clearImmediate,m=u.MessageChannel,h=0,g={},_=`onreadystatechange`,v=function(){var e=+this;if(g.hasOwnProperty(e)){var t=g[e];delete g[e],t()}},y=function(e){v.call(e.data)};f&&p||(f=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return g[++h]=function(){s(typeof e==`function`?e:Function(e),t)},r(h),h},p=function(e){delete g[e]},n(11)(d)==`process`?r=function(e){d.nextTick(o(v,e,1))}:m?(i=new m,a=i.port2,i.port1.onmessage=y,r=o(a.postMessage,a,1)):u.addEventListener&&typeof postMessage==`function`&&!u.importScripts?(r=function(e){u.postMessage(e+``,`*`)},u.addEventListener(`message`,y,!1)):r=_ in l(`script`)?function(e){c.appendChild(l(`script`))[_]=function(){c.removeChild(this),v.call(e)}}:function(e){setTimeout(o(v,e,1),0)}),e.exports={set:f,clear:p}},function(e,t,n){var r=n(20),i=Math.min;e.exports=function(e){return e>0?i(r(e),9007199254740991):0}},function(e,t,n){var r=n(9);e.exports=function(e,t){if(!r(e))return e;var n,i;if(t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e))||typeof(n=e.valueOf)==`function`&&!r(i=n.call(e))||!t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e)))return i;throw TypeError(`Can't convert object to primitive value`)}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return`Symbol(${e===void 0?``:e})_${(++n+r).toString(36)}`}},function(e,t,n){function r(e){return e&&e.__esModule?e:{default:e}}function i(){return process.platform===`win32`?process.arch===`ia32`&&process.env.hasOwnProperty(`PROCESSOR_ARCHITEW6432`)?`mixed`:`native`:``}function a(e){return(0,d.createHash)(`sha256`).update(e).digest(`hex`)}function o(e){switch(f){case`darwin`:return e.split(`IOPlatformUUID`)[1].split(`
34
+ `)[0].replace(/\=|\s+|\"/gi,``).toLowerCase();case`win32`:return e.toString().split(`REG_SZ`)[1].replace(/\r+|\n+|\s+/gi,``).toLowerCase();case`linux`:return e.toString().replace(/\r+|\n+|\s+/gi,``).toLowerCase();case`freebsd`:return e.toString().replace(/\r+|\n+|\s+/gi,``).toLowerCase();default:throw Error(`Unsupported platform: `+process.platform)}}function s(e){var t=o((0,u.execSync)(p[f]).toString());return e?t:a(t)}function c(e){return new l.default(function(t,n){return(0,u.exec)(p[f],{},function(r,i,s){if(r)return n(Error(`Error while obtaining machine id: `+r.stack));var c=o(i.toString());return t(e?c:a(c))})})}Object.defineProperty(t,`__esModule`,{value:!0});var l=r(n(35));t.machineIdSync=s,t.machineId=c;var u=n(70),d=n(71),f=process.platform,p={darwin:`ioreg -rd1 -c IOPlatformExpertDevice`,win32:{native:`%windir%\\System32`,mixed:`%windir%\\sysnative\\cmd.exe /c %windir%\\System32`}[i()]+`\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`,linux:`( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :`,freebsd:`kenv -q smbios.system.uuid || sysctl -n kern.hostuuid`}},function(e,t,n){e.exports={default:n(36),__esModule:!0}},function(e,t,n){n(66),n(68),n(69),n(67),e.exports=n(6).Promise},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||r!==void 0&&r in e)throw TypeError(n+`: incorrect invocation!`);return e}},function(e,t,n){var r=n(13),i=n(31),a=n(62);e.exports=function(e){return function(t,n,o){var s,c=r(t),l=i(c.length),u=a(o,l);if(e&&n!=n){for(;l>u;)if(s=c[u++],s!=s)return!0}else for(;l>u;u++)if((e||u in c)&&c[u]===n)return e||u||0;return!e&&-1}}},function(e,t,n){var r=n(7),i=n(44),a=n(43),o=n(3),s=n(31),c=n(64),l={},u={},t=e.exports=function(e,t,n,d,f){var p,m,h,g,_=f?function(){return e}:c(e),v=r(n,d,t?2:1),y=0;if(typeof _!=`function`)throw TypeError(e+` is not iterable!`);if(a(_)){for(p=s(e.length);p>y;y++)if(g=t?v(o(m=e[y])[0],m[1]):v(e[y]),g===l||g===u)return g}else for(h=_.call(e);!(m=h.next()).done;)if(g=i(h,v,m.value,t),g===l||g===u)return g};t.BREAK=l,t.RETURN=u},function(e,t){e.exports=function(e,t,n){var r=n===void 0;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(11);e.exports=Object(`z`).propertyIsEnumerable(0)?Object:function(e){return r(e)==`String`?e.split(``):Object(e)}},function(e,t,n){var r=n(10),i=n(1)(`iterator`),a=Array.prototype;e.exports=function(e){return e!==void 0&&(r.Array===e||a[i]===e)}},function(e,t,n){var r=n(3);e.exports=function(e,t,n,i){try{return i?t(r(n)[0],n[1]):t(n)}catch(t){var a=e.return;throw a!==void 0&&r(a.call(e)),t}}},function(e,t,n){var r=n(49),i=n(17),a=n(18),o={};n(5)(o,n(1)(`iterator`),function(){return this}),e.exports=function(e,t,n){e.prototype=r(o,{next:i(1,n)}),a(e,t+` Iterator`)}},function(e,t,n){var r=n(1)(`iterator`),i=!1;try{var a=[7][r]();a.return=function(){i=!0},Array.from(a,function(){throw 2})}catch{}e.exports=function(e,t){if(!t&&!i)return!1;var n=!1;try{var a=[7],o=a[r]();o.next=function(){return{done:n=!0}},a[r]=function(){return o},e(a)}catch{}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(2),i=n(30).set,a=r.MutationObserver||r.WebKitMutationObserver,o=r.process,s=r.Promise,c=n(11)(o)==`process`;e.exports=function(){var e,t,n,l=function(){var r,i;for(c&&(r=o.domain)&&r.exit();e;){i=e.fn,e=e.next;try{i()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(c)n=function(){o.nextTick(l)};else if(a){var u=!0,d=document.createTextNode(``);new a(l).observe(d,{characterData:!0}),n=function(){d.data=u=!u}}else if(s&&s.resolve){var f=s.resolve();n=function(){f.then(l)}}else n=function(){i.call(r,l)};return function(r){var i={fn:r,next:void 0};t&&(t.next=i),e||(e=i,n()),t=i}}},function(e,t,n){var r=n(3),i=n(50),a=n(22),o=n(19)(`IE_PROTO`),s=function(){},c=`prototype`,l=function(){var e,t=n(16)(`iframe`),r=a.length,i=`>`;for(t.style.display=`none`,n(25).appendChild(t),t.src=`javascript:`,e=t.contentWindow.document,e.open(),e.write(`<script>document.F=Object<\/script`+i),e.close(),l=e.F;r--;)delete l[c][a[r]];return l()};e.exports=Object.create||function(e,t){var n;return e===null?n=l():(s[c]=r(e),n=new s,s[c]=null,n[o]=e),t===void 0?n:i(n,t)}},function(e,t,n){var r=n(12),i=n(3),a=n(54);e.exports=n(4)?Object.defineProperties:function(e,t){i(e);for(var n,o=a(t),s=o.length,c=0;s>c;)r.f(e,n=o[c++],t[n]);return e}},function(e,t,n){var r=n(55),i=n(17),a=n(13),o=n(32),s=n(8),c=n(26),l=Object.getOwnPropertyDescriptor;t.f=n(4)?l:function(e,t){if(e=a(e),t=o(t,!0),c)try{return l(e,t)}catch{}if(s(e,t))return i(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(8),i=n(63),a=n(19)(`IE_PROTO`),o=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=i(e),r(e,a)?e[a]:typeof e.constructor==`function`&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?o:null}},function(e,t,n){var r=n(8),i=n(13),a=n(39)(!1),o=n(19)(`IE_PROTO`);e.exports=function(e,t){var n,s=i(e),c=0,l=[];for(n in s)n!=o&&r(s,n)&&l.push(n);for(;t.length>c;)r(s,n=t[c++])&&(~a(l,n)||l.push(n));return l}},function(e,t,n){var r=n(53),i=n(22);e.exports=Object.keys||function(e){return r(e,i)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(5);e.exports=function(e,t,n){for(var i in t)n&&e[i]?e[i]=t[i]:r(e,i,t[i]);return e}},function(e,t,n){e.exports=n(5)},function(e,t,n){var r=n(9),i=n(3),a=function(e,t){if(i(e),!r(t)&&t!==null)throw TypeError(t+`: can't set as prototype!`)};e.exports={set:Object.setPrototypeOf||(`__proto__`in{}?function(e,t,r){try{r=n(7)(Function.call,n(51).f(Object.prototype,`__proto__`).set,2),r(e,[]),t=!(e instanceof Array)}catch{t=!0}return function(e,n){return a(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:a}},function(e,t,n){var r=n(2),i=n(6),a=n(12),o=n(4),s=n(1)(`species`);e.exports=function(e){var t=typeof i[e]==`function`?i[e]:r[e];o&&t&&!t[s]&&a.f(t,s,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(3),i=n(14),a=n(1)(`species`);e.exports=function(e,t){var n,o=r(e).constructor;return o===void 0||(n=r(o)[a])==null?t:i(n)}},function(e,t,n){var r=n(20),i=n(15);e.exports=function(e){return function(t,n){var a,o,s=String(i(t)),c=r(n),l=s.length;return c<0||c>=l?e?``:void 0:(a=s.charCodeAt(c),a<55296||a>56319||c+1===l||(o=s.charCodeAt(c+1))<56320||o>57343?e?s.charAt(c):a:e?s.slice(c,c+2):(a-55296<<10)+(o-56320)+65536)}}},function(e,t,n){var r=n(20),i=Math.max,a=Math.min;e.exports=function(e,t){return e=r(e),e<0?i(e+t,0):a(e,t)}},function(e,t,n){var r=n(15);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(21),i=n(1)(`iterator`),a=n(10);e.exports=n(6).getIteratorMethod=function(e){if(e!=null)return e[i]||e[`@@iterator`]||a[r(e)]}},function(e,t,n){var r=n(37),i=n(47),a=n(10),o=n(13);e.exports=n(27)(Array,`Array`,function(e,t){this._t=o(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,i(1)):t==`keys`?i(0,n):t==`values`?i(0,e[n]):i(0,[n,e[n]])},`values`),a.Arguments=a.Array,r(`keys`),r(`values`),r(`entries`)},function(e,t){},function(e,t,n){var r,i,a,o=n(28),s=n(2),c=n(7),l=n(21),u=n(23),d=n(9),f=(n(3),n(14)),p=n(38),m=n(40),h=(n(58).set,n(60)),g=n(30).set,_=n(48)(),v=`Promise`,y=s.TypeError,b=s.process,x=s[v],b=s.process,S=l(b)==`process`,C=function(){},w=!!function(){try{var e=x.resolve(1),t=(e.constructor={})[n(1)(`species`)]=function(e){e(C,C)};return(S||typeof PromiseRejectionEvent==`function`)&&e.then(C)instanceof t}catch{}}(),ee=function(e,t){return e===t||e===x&&t===a},T=function(e){var t;return!(!d(e)||typeof(t=e.then)!=`function`)&&t},E=function(e){return ee(x,e)?new D(e):new i(e)},D=i=function(e){var t,n;this.promise=new e(function(e,r){if(t!==void 0||n!==void 0)throw y(`Bad Promise constructor`);t=e,n=r}),this.resolve=f(t),this.reject=f(n)},O=function(e){try{e()}catch(e){return{error:e}}},k=function(e,t){if(!e._n){e._n=!0;var n=e._c;_(function(){for(var r=e._v,i=e._s==1,a=0,o=function(t){var n,a,o=i?t.ok:t.fail,s=t.resolve,c=t.reject,l=t.domain;try{o?(i||(e._h==2&&ne(e),e._h=1),o===!0?n=r:(l&&l.enter(),n=o(r),l&&l.exit()),n===t.promise?c(y(`Promise-chain cycle`)):(a=T(n))?a.call(n,s,c):s(n)):c(r)}catch(e){c(e)}};n.length>a;)o(n[a++]);e._c=[],e._n=!1,t&&!e._h&&A(e)})}},A=function(e){g.call(s,function(){var t,n,r,i=e._v;if(te(e)&&(t=O(function(){S?b.emit(`unhandledRejection`,i,e):(n=s.onunhandledrejection)?n({promise:e,reason:i}):(r=s.console)&&r.error&&r.error(`Unhandled promise rejection`,i)}),e._h=S||te(e)?2:1),e._a=void 0,t)throw t.error})},te=function(e){if(e._h==1)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!te(t.promise))return!1;return!0},ne=function(e){g.call(s,function(){var t;S?b.emit(`rejectionHandled`,e):(t=s.onrejectionhandled)&&t({promise:e,reason:e._v})})},re=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||=t._c.slice(),k(t,!0))},j=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw y(`Promise can't be resolved itself`);(t=T(e))?_(function(){var r={_w:n,_d:!1};try{t.call(e,c(j,r,1),c(re,r,1))}catch(e){re.call(r,e)}}):(n._v=e,n._s=1,k(n,!1))}catch(e){re.call({_w:n,_d:!1},e)}}};w||(x=function(e){p(this,x,v,`_h`),f(e),r.call(this);try{e(c(j,this,1),c(re,this,1))}catch(e){re.call(this,e)}},r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(56)(x.prototype,{then:function(e,t){var n=E(h(this,x));return n.ok=typeof e!=`function`||e,n.fail=typeof t==`function`&&t,n.domain=S?b.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&k(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),D=function(){var e=new r;this.promise=e,this.resolve=c(j,e,1),this.reject=c(re,e,1)}),u(u.G+u.W+u.F*!w,{Promise:x}),n(18)(x,v),n(59)(v),a=n(6)[v],u(u.S+u.F*!w,v,{reject:function(e){var t=E(this),n=t.reject;return n(e),t.promise}}),u(u.S+u.F*(o||!w),v,{resolve:function(e){if(e instanceof x&&ee(e.constructor,this))return e;var t=E(this),n=t.resolve;return n(e),t.promise}}),u(u.S+u.F*!(w&&n(46)(function(e){x.all(e).catch(C)})),v,{all:function(e){var t=this,n=E(t),r=n.resolve,i=n.reject,a=O(function(){var n=[],a=0,o=1;m(e,!1,function(e){var s=a++,c=!1;n.push(void 0),o++,t.resolve(e).then(function(e){c||(c=!0,n[s]=e,--o||r(n))},i)}),--o||r(n)});return a&&i(a.error),n.promise},race:function(e){var t=this,n=E(t),r=n.reject,i=O(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return i&&r(i.error),n.promise}})},function(e,t,n){var r=n(61)(!0);n(27)(String,`String`,function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){n(65);for(var r=n(2),i=n(5),a=n(10),o=n(1)(`toStringTag`),s=[`NodeList`,`DOMTokenList`,`MediaList`,`StyleSheetList`,`CSSRuleList`],c=0;c<5;c++){var l=s[c],u=r[l],d=u&&u.prototype;d&&!d[o]&&i(d,o,l),a[l]=a.Array}},function(t,n){t.exports=e(`child_process`)},function(t,n){t.exports=e(`crypto`)}])})}))();function sh(e){return typeof e==`string`?`'${e}'`:new ch().serialize(e)}const ch=function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?e.localeCompare(t):n===`number`&&r===`number`?e-t:String.prototype.localeCompare.call(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}return this.serializeObjectEntries(r,Object.entries(e))}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t?.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`])e.prototype[`$`+t]=function(e){return`${t}[${e.join(`,`)}]`};for(let t of[`BigInt64Array`,`BigUint64Array`])e.prototype[`$`+t]=function(e){return`${t}[${e.join(`n,`)}${e.length>0?`n`:``}]`};return e}(),lh=globalThis.process?.getBuiltinModule?.(`crypto`)?.hash,uh=`sha256`,dh=`base64url`;function fh(e){if(lh)return lh(uh,e,dh);let t=we(uh).update(e);return globalThis.process?.versions?.webcontainer?t.digest().toString(dh):t.digest(dh)}function ph(e){return fh(sh(e))}function mh(){let e=hh();return async t=>{for(let n of t)n.module=e(n.filename);return t}}function hh(e=process.argv[1]?Ue(process.argv[1]):process.cwd(),t=Ge===`\\`){let n=t?gh(e):e;return e=>{if(!e)return;let r=t?gh(e):e,{dir:i,base:a,ext:o}=We.parse(r);(o===`.js`||o===`.mjs`||o===`.cjs`)&&(a=a.slice(0,-1*o.length));let s=decodeURIComponent(a);i||=`.`;let c=i.lastIndexOf(`/node_modules`);if(c>-1)return`${i.slice(c+14).replace(/\//g,`.`)}:${s}`;if(i.startsWith(n)){let e=i.slice(n.length+1).replace(/\//g,`.`);return e?`${e}:${s}`:s}return s}}function gh(e){return e.replace(/^[A-Z]:/,``).replace(/\\/g,`/`)}const _h=e=>{if(`flags`in e){let t=yh(e.flags),n=bh(e.flags);return{...e,featureFlags:t,featureFlagPayloads:n}}{let t=e.featureFlags??{},n=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,Sh(t)])),r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,vh(e,t,n[e])]));return{...e,featureFlags:t,featureFlagPayloads:n,flags:r}}};function vh(e,t,n){return{key:e,enabled:typeof t==`string`?!0:t,variant:typeof t==`string`?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:n?JSON.stringify(n):void 0,description:void 0}}}const yh=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,xh(t)]).filter(([,e])=>e!==void 0)),bh=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(e=>{let n=t[e];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(e=>{let n=t[e].metadata?.payload;return[e,n?Sh(n):void 0]}))},xh=e=>e===void 0?void 0:e.variant??e.enabled,Sh=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},Ch=`0123456789abcdef`;var wh=class e{constructor(e){this.bytes=e}static ofInner(t){if(t.length===16)return new e(t);throw TypeError(`not 128-bit length`)}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||t<0||n<0||r<0||i<0||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw RangeError(`invalid field value`);let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|n>>>8,a[7]=n,a[8]=128|r>>>24,a[9]=r>>>16,a[10]=r>>>8,a[11]=r,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,new e(a)}static parse(t){let n;switch(t.length){case 32:n=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:n=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join(``);break;case 38:n=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join(``);break;case 45:n=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join(``);break;default:break}if(n){let t=new Uint8Array(16);for(let e=0;e<16;e+=4){let r=parseInt(n.substring(2*e,2*e+8),16);t[e+0]=r>>>24,t[e+1]=r>>>16,t[e+2]=r>>>8,t[e+3]=r}return new e(t)}throw SyntaxError(`could not parse UUID string`)}toString(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=Ch.charAt(this.bytes[t]>>>4),e+=Ch.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+=`-`);return e}toHex(){let e=``;for(let t=0;t<this.bytes.length;t++)e+=Ch.charAt(this.bytes[t]>>>4),e+=Ch.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error(`unreachable`);if(e<=7)return this.bytes.every(e=>e===0)?`NIL`:`VAR_0`;if(e<=11)return`VAR_10`;if(e<=13)return`VAR_110`;if(e<=15)return this.bytes.every(e=>e===255)?`MAX`:`VAR_RESERVED`;throw Error(`unreachable`)}getVersion(){return this.getVariant()===`VAR_10`?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},Th=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Eh()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return wh.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,wh.ofInner(e)}};const Eh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())});let Dh;const Oh=()=>kh().toString(),kh=()=>(Dh||=new Th).generate();var Ah=function(e){return e.AnonymousId=`anonymous_id`,e.DistinctId=`distinct_id`,e.Props=`props`,e.EnablePersonProcessing=`enable_person_processing`,e.PersonMode=`person_mode`,e.FeatureFlagDetails=`feature_flag_details`,e.FeatureFlags=`feature_flags`,e.FeatureFlagPayloads=`feature_flag_payloads`,e.BootstrapFeatureFlagDetails=`bootstrap_feature_flag_details`,e.BootstrapFeatureFlags=`bootstrap_feature_flags`,e.BootstrapFeatureFlagPayloads=`bootstrap_feature_flag_payloads`,e.OverrideFeatureFlags=`override_feature_flags`,e.Queue=`queue`,e.OptedOut=`opted_out`,e.SessionId=`session_id`,e.SessionStartTimestamp=`session_start_timestamp`,e.SessionLastTimestamp=`session_timestamp`,e.PersonProperties=`person_properties`,e.GroupProperties=`group_properties`,e.InstalledAppBuild=`installed_app_build`,e.InstalledAppVersion=`installed_app_version`,e.SessionReplay=`session_replay`,e.SurveyLastSeenDate=`survey_last_seen_date`,e.SurveysSeen=`surveys_seen`,e.Surveys=`surveys`,e.RemoteConfig=`remote_config`,e.FlagsEndpointWasHit=`flags_endpoint_was_hit`,e}({});const jh=`amazonbot,amazonproductbot,app.hypefactors.com,applebot,archive.org_bot,awariobot,backlinksextendedbot,baiduspider,bingbot,bingpreview,chrome-lighthouse,dataforseobot,deepscan,duckduckbot,facebookexternal,facebookcatalog,http://yandex.com/bots,hubspot,ia_archiver,leikibot,linkedinbot,meta-externalagent,mj12bot,msnbot,nessus,petalbot,pinterest,prerender,rogerbot,screaming frog,sebot-wa,sitebulb,slackbot,slurp,trendictionbot,turnitin,twitterbot,vercel-screenshot,vercelbot,yahoo! slurp,yandexbot,zoombot,bot.htm,bot.php,(bot;,bot/,crawler,ahrefsbot,ahrefssiteaudit,semrushbot,siteauditbot,splitsignalbot,gptbot,oai-searchbot,chatgpt-user,perplexitybot,better uptime bot,sentryuptimebot,uptimerobot,headlesschrome,cypress,google-hoteladsverifier,adsbot-google,apis-google,duplexweb-google,feedfetcher-google,google favicon,google web preview,google-read-aloud,googlebot,googleother,google-cloudvertexbot,googleweblight,mediapartners-google,storebot-google,google-inspectiontool,bytespider`.split(`,`),Mh=function(e,t=[]){if(!e)return!1;let n=e.toLowerCase();return jh.concat(t).some(e=>{let t=e.toLowerCase();return n.indexOf(t)!==-1})},Nh=Array.isArray,Ph=Object.prototype;Ph.hasOwnProperty;const Fh=Ph.toString,Ih=Nh||function(e){return Fh.call(e)===`[object Array]`},Lh=e=>e===Object(e)&&!Ih(e),Rh=e=>e===void 0,zh=e=>Fh.call(e)==`[object String]`,Bh=e=>zh(e)&&e.trim().length===0,Vh=e=>Fh.call(e)==`[object Number]`&&e===e,Hh=e=>e instanceof Error;function Uh(e){return typeof e!=`object`||!e}function Wh(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Gh(e){return!Rh(Event)&&qh(e,Event)}function Kh(e){return Wh(e,`Object`)}function qh(e,t){try{return e instanceof t}catch{return!1}}function Jh(e,t,n,r,i){return t>n&&(r.warn(`min cannot be greater than max.`),t=n),Vh(e)?e>n?(r.warn(` cannot be greater than max: `+n+`. Using max value instead.`),n):e<t?(r.warn(` cannot be less than min: `+t+`. Using min value instead.`),t):e:(r.warn(` must be a number. using max or fallback. max: `+n+`, fallback: `+i),Jh(i||n,t,n,r))}var Yh=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Jh(e.bucketSize,0,100,e._logger),this._refillRate=Jh(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Jh(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,r=Math.floor(n/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess+=r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),r=this._buckets[n];return r?this._applyRefill(r,t):(r={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=r),r.tokens===0?!0:(r.tokens--,r.tokens===0&&this._onBucketRateLimited?.(e),r.tokens===0)}stop(){this._buckets={}}},Xh=class{add(e){let t=Oh();return this.promiseByIds[t]=e,e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds),t=e.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function Zh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}const Qh=(e,t,n)=>{function r(r,...i){t(()=>{let t=n[r];t(e,...i)})}return{info:(...e)=>{r(`log`,...e)},warn:(...e)=>{r(`warn`,...e)},error:(...e)=>{r(`error`,...e)},critical:(...t)=>{n.error(e,...t)},createLogger:r=>Qh(`${e} ${r}`,t,n)}},$h=e=>e();function eg(e,t=$h){return Qh(e,t,Zh())}const tg=`Android`;tg+``;const ng=`BlackBerry`,rg=`Samsung`;rg+``,rg+``;const ig=`Chrome`;ig+``,ig+``;const ag=`Opera`;ag+``;const og=`Edge`;``+og;const sg=`Firefox`;sg+``;const cg=`Nintendo`,lg=`PlayStation`,ug=`Xbox`;tg+``;const dg=`Windows`;dg+``;const fg=`Generic`;fg+``,fg+``;const pg=`(\\d+(\\.\\d+)?)`;RegExp(`Version/`+pg),new RegExp(ug,`i`),RegExp(lg+` \\w+`,`i`),RegExp(cg+` \\w+`,`i`),RegExp(ng+`|PlayBook|BB10`,`i`),RegExp(`rv:`+pg),RegExp(og+`?\\/(\\d+(\\.\\d+)?)`),RegExp(`(`+ig+`|CrMo)\\/(\\d+(\\.\\d+)?)`),RegExp(`CriOS\\/`+pg),RegExp(`(UCBrowser|UCWEB)\\/`+pg),RegExp(`(`+ag+`|OPR)\\/(\\d+(\\.\\d+)?)`),RegExp(sg+`\\/(\\d+(\\.\\d+)?)`),RegExp(`FxiOS\\/`+pg),RegExp(`Konqueror[:/]?`+pg,`i`),RegExp(ng+` (\\d+(\\.\\d+)?)`),RegExp(`android\\s`+pg,`i`),RegExp(`(rv:|MSIE )`+pg),RegExp(`rv:`+pg),RegExp(ug+`; Xbox (.*?)[);]`,`i`),new RegExp(cg,`i`),new RegExp(lg,`i`),new RegExp(dg,`i`),RegExp(`(`+tg+` (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)`,`i`);function mg(e,t){if(!e||typeof e!=`string`||hg(e))throw Error(t)}function hg(e){return e.trim().length===0}function gg(e){return e?.replace(/\/+$/,``)}async function _g(e,t){let n=null;for(let r=0;r<t.retryCount+1;r++){r>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(n=e,!t.retryCheck(e))throw e}}throw n}function vg(){return new Date().toISOString()}function yg(e,t){let n=setTimeout(e,t);return n?.unref&&n?.unref(),n}const bg=e=>e instanceof Error;function xg(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}var Sg=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events[`*`]||[])n(e,t)}};function Cg(){return`CompressionStream`in globalThis}async function wg(e,t=!0){try{let t=new Blob([e],{type:`text/plain`}).stream().pipeThrough(new CompressionStream(`gzip`));return await new Response(t).blob()}catch(e){return t&&console.error(`Failed to gzip compress data`,e),null}}var Tg=class extends Error{constructor(e,t){super(`HTTP error while fetching PostHog: status=`+e.status+`, reqByteLength=`+t),this.response=e,this.reqByteLength=t,this.name=`PostHogFetchHttpError`}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},Eg=class extends Error{constructor(e){super(`Network error while fetching PostHog`,e instanceof Error?{cause:e}:{}),this.error=e,this.name=`PostHogFetchNetworkError`}};async function Dg(e){if(e instanceof Tg){let t=``;try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error(`Error while flushing PostHog`,e);return Promise.resolve()}function Og(e){return typeof e==`object`&&(e instanceof Tg||e instanceof Eg)}function kg(e){return typeof e==`object`&&e instanceof Tg&&e.status===413}var Ag=class{constructor(e,t={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Xh,this._events=new Sg,this._isInitialized=!1,mg(e,`You must pass your PostHog project's api key.`),this.apiKey=e,this.host=gg(t.host||`https://us.i.posthog.com`),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:Og},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=t.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=eg(`[PostHog]`,this.logMsgIfDebug.bind(this)),this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn(`evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.`),this.disableCompression=!Cg()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Ah.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ah.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ah.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on(`*`,(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};this.enqueue(`identify`,r,n)})}async identifyStatelessImmediate(e,t,n){let r={...this.buildPayload({distinct_id:e,event:`$identify`,properties:t})};await this.sendImmediate(`identify`,r,n)}captureStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue(`capture`,i,r)})}async captureStatelessImmediate(e,t,n,r){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate(`capture`,i,r)}aliasStateless(e,t,n,r){this.wrap(()=>{let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue(`alias`,i,r)})}async aliasStatelessImmediate(e,t,n,r){let i=this.buildPayload({event:`$create_alias`,distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate(`alias`,i,r)}groupIdentifyStateless(e,t,n,r,i,a){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:`$groupidentify`,properties:{$group_type:e,$group_key:t,$group_set:n||{},...a||{}}});this.enqueue(`capture`,o,r)})}async getRemoteConfig(){await this._initPromise;let e=this.host;e===`https://us.i.posthog.com`?e=`https://us-assets.i.posthog.com`:e===`https://eu.i.posthog.com`&&(e=`https://eu-assets.i.posthog.com`);let t=`${e}/array/${this.apiKey}/config`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this._logger.error(`Remote config could not be loaded`,e),this._events.emit(`error`,e)})}async getFlags(e,t={},n={},r={},i={},a=!1){await this._initPromise;let o=a?`&config=true`:``,s=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:r,...i};this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`},body:JSON.stringify(c)};return this._logger.info(`Flags URL`,s),this.fetchWithRetry(s,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:_h(e)})).catch(e=>(this._events.emit(`error`,e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof Tg)return{type:`api_error`,statusCode:e.status};if(e instanceof Eg){let t=e.error;return t instanceof Error&&(t.name===`AbortError`||t.name===`TimeoutError`)?{type:`timeout`}:{type:`connection_error`}}return{type:`unknown_error`}}async getFeatureFlagStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,n,r,i,a);if(o===void 0)return{response:void 0,requestId:void 0};let s=xh(o.response);return s===void 0&&(s=!1),{response:s,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,n,r,i,a,[e]);if(o!==void 0)return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},r={},i={},a){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,n,r,i,a,[e]);if(!o)return;let s=o[e];return s===void 0?null:s}async getFeatureFlagPayloadsStateless(e,t={},n={},r={},i,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)).payloads}async getFeatureFlagsStateless(e,t={},n={},r={},i,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,r,i,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,n,r,i,a);return o?{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},r={},i,a){await this._initPromise;let o={};(i??this.disableGeoip)&&(o.geoip_disable=!0),a&&(o.flag_keys_to_evaluate=a);let s=await this.getFlags(e,t,n,r,o);if(!s.success)return;let c=s.response;return c.errorsWhileComputingFlags&&console.error(`[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices`),c.quotaLimited?.includes(`feature_flags`)?(console.warn(`[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts`),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this._logger.info(`Loading surveys is disabled.`),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`}},n=(await this.fetchWithRetry(e,t).then(e=>{if(e.status!==200||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,n=Error(t);this._logger.error(n),this._events.emit(`error`,Error(t));return}return e.json()}).catch(e=>{this._logger.error(`Surveys API could not be loaded`,e),this._events.emit(`error`,e)}))?.surveys;return n&&this._logger.info(`Surveys fetched from API: `,JSON.stringify(n)),n??[]}get props(){return this._props||=this.getPersistedProperty(Ah.Props),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ah.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ah.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r=this.prepareMessage(e,t,n);if(r=this.processBeforeEnqueue(r),r===null)return;let i=this.getPersistedProperty(Ah.Queue)||[];i.length>=this.maxQueueSize&&(i.shift(),this._logger.info(`Queue is full, the oldest event is dropped.`)),i.push({message:r}),this.setPersistedProperty(Ah.Queue,i),this._events.emit(e,r),i.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=yg(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn(`The client is disabled`);if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,`Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);let r=this.prepareMessage(e,t,n);if(r=this.processBeforeEnqueue(r),r===null)return;let i={api_key:this.apiKey,batch:[r],sent_at:vg()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=`${this.host}/batch/`,s=this.disableCompression?null:await wg(a,this.isDebug),c={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...s!==null&&{"Content-Encoding":`gzip`}},body:s||a};try{await this.fetchWithRetry(o,c)}catch(e){this._events.emit(`error`,e)}}prepareMessage(e,t,n){let r={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:vg(),uuid:n?.uuid?n.uuid:Oh()};return(n?.disableGeoip??this.disableGeoip)&&(r.properties||={},r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&=(clearTimeout(this._flushTimer),void 0)}flushBackground(){this.flush().catch(async e=>{await Dg(e)})}async flush(){let e=xg([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),xg([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==``&&(t[`User-Agent`]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(Ah.Queue)||[];if(!e.length)return;let t=[],n=e.length;for(;e.length>0&&t.length<n;){let n=e.slice(0,this.maxBatchSize),r=n.map(e=>e.message),i=async()=>{let t=(this.getPersistedProperty(Ah.Queue)||[]).slice(n.length);this.setPersistedProperty(Ah.Queue,t),e=t,await this.flushStorage()},a={api_key:this.apiKey,batch:r,sent_at:vg()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),s=`${this.host}/batch/`,c=this.disableCompression?null:await wg(o,this.isDebug),l={method:`POST`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,...c!==null&&{"Content-Encoding":`gzip`}},body:c||o},u={retryCheck:e=>kg(e)?!1:Og(e)};try{await this.fetchWithRetry(s,l,u)}catch(e){if(kg(e)&&r.length>1){this.maxBatchSize=Math.max(1,Math.floor(r.length/2)),this._logger.warn(`Received 413 when sending batch of size ${r.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof Eg||await i(),this._events.emit(`error`,e),e}await i(),t.push(...r)}this._events.emit(`flush`,t)}async fetchWithRetry(e,t,n,r){let i=t.body?t.body:``,a=-1;try{a=i instanceof Blob?i.size:Buffer.byteLength(i,`utf8`)}catch{a=i instanceof Blob?i.size:new TextEncoder().encode(i).length}return await _g(async()=>{let n=new AbortController,i=yg(()=>n.abort(),r??this.requestTimeout),o=null;try{o=await this.fetch(e,{signal:n.signal,...t})}catch(e){throw new Eg(e)}finally{clearTimeout(i)}if(t.mode!==`no-cors`&&(o.status<200||o.status>=400))throw new Tg(o,a);return o},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(Ah.Queue)||[]).length===0||(await this.flush(),t)););}catch(e){if(!Og(e))throw e;await Dg(e)}},r;try{return await Promise.race([new Promise((n,i)=>{r=yg(()=>{this._logger.error(`Timed out while shutting down PostHog`),t=!0,i(`Timeout while shutting down PostHog. Some events may not have been sent.`)},e)}),n()])}finally{clearTimeout(r)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn(`shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup`):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};let jg,Mg,Ng;function Pg(e){let t=globalThis._posthogChunkIds;if(!t)return;let n=Object.keys(t);return Ng&&n.length===Mg?Ng:(Mg=n.length,Ng=n.reduce((n,r)=>{jg||={};let i=jg[r];if(i)n[i[0]]=i[1];else{let i=e(r);for(let e=i.length-1;e>=0;e--){let a=i[e]?.filename,o=t[r];if(a&&o){n[a]=o,jg[r]=[a,o];break}}}return n},{}),Ng)}var Fg=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:`generic`},r=this.buildCoercingContext(n,t,0).apply(e),i=this.buildParsingContext(t),a=this.parseStacktrace(r,i);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:`error`}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&Ih(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:`Error`,value:`Unknown error`,stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let r;return e.stack!=``&&e.stack!=null&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:r}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??`generic`,handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:`raw`,frames:e.stack});let r=[n];return e.cause!=null&&r.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),r}buildParsingContext(e){return{chunkIdMap:Pg(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let r=(n,r)=>{if(r<=4){let i=this.buildCoercingContext(e,t,r);return this.applyCoercers(n,i)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,n),next:e=>r(e,n+1)}}};const Ig=/^\s*[-]{4,}$/,Lg=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Rg=(e,t)=>{let n=e.match(Lg);if(n){let e,r,i,a,o;if(n[1]){i=n[1];let t=i.lastIndexOf(`.`);if(i[t-1]===`.`&&t--,t>0){e=i.slice(0,t),r=i.slice(t+1);let n=e.indexOf(`.Module`);n>0&&(i=i.slice(n+1),e=e.slice(0,n))}a=void 0}r&&(a=e,o=r),r===`<anonymous>`&&(o=void 0,i=void 0),i===void 0&&(o||=`?`,i=a?`${a}.${o}`:o);let s=n[2]?.startsWith(`file://`)?n[2].slice(7):n[2],c=n[5]===`native`;return s?.match(/\/[A-Z]:/)&&(s=s.slice(1)),!s&&n[5]&&!c&&(s=n[5]),{filename:s?decodeURI(s):void 0,module:void 0,function:i,lineno:Bg(n[3]),colno:Bg(n[4]),in_app:zg(s||``,c),platform:t}}if(e.match(Ig))return{filename:e,platform:t}};function zg(e,t=!1){return!(t||e&&!e.startsWith(`/`)&&!e.match(/^[A-Z]:/)&&!e.startsWith(`.`)&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes(`node_modules/`)}function Bg(e){return parseInt(e||``,10)||void 0}const Vg=/\(error: (.*)\)/;function Hg(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>({...e,filename:e.filename||Ug(t).filename,function:e.function||`?`}))}function Ug(e){return e[e.length-1]||{}}function Wg(e,...t){return(n,r=0)=>{let i=[],a=n.split(`
35
+ `);for(let n=r;n<a.length;n++){let r=a[n];if(r.length>1024)continue;let o=Vg.test(r)?r.replace(Vg,`$1`):r;if(!o.match(/\S*Error: /)){for(let n of t){let t=n(o,e);if(t){i.push(t);break}}if(i.length>=50)break}}return Hg(i)}}var Gg=class{match(e){return Hh(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message==`string`?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};const Kg=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var qg=class{match(e){return typeof e==`string`}coerce(e,t){let[n,r]=this.getInfos(e);return{type:n??`Error`,value:r??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t=`Error`,n=e,r=e.match(Kg);return r&&(t=r[1],n=r[2]),[t,n]}};const Jg=[`fatal`,`error`,`warning`,`log`,`info`,`debug`];function Yg(e,t=40){let n=Object.keys(e);if(n.sort(),!n.length)return`[object has no keys]`;for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`, `);if(!(r.length>t))return e===n.length||r.length<=t?r:`${r.slice(0,t)}...`}return``}var Xg=class{match(e){return typeof e==`object`&&!!e}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:`error`,synthetic:!0}}getType(e){return Gh(e)?e.constructor.name:`Error`}getValue(e){if(`name`in e&&typeof e.name==`string`){let t=`'${e.name}' captured as exception`;return`message`in e&&typeof e.message==`string`&&(t+=` with message: '${e.message}'`),t}if(`message`in e&&typeof e.message==`string`)return e.message;let t=this.getObjectClassName(e),n=Yg(e);return`${t&&t!==`Object`?`'${t}'`:`Object`} captured as exception with keys: ${n}`}isSeverityLevel(e){return zh(e)&&!Bh(e)&&Jg.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(bg(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Zg=class{match(e){return Gh(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Yg(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},Qg=class{match(e){return Uh(e)}coerce(e,t){return{type:`Error`,value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}},$g=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};const e_=new $g(25),t_=new $g(20);async function n_(e){let t={};for(let n=e.length-1;n>=0;n--){let r=e[n],i=r?.filename;!r||typeof i!=`string`||typeof r.lineno!=`number`||s_(i)||c_(r)||(t[i]||(t[i]=[]),t[i].push(r.lineno))}let n=Object.keys(t);if(n.length==0)return e;let r=[];for(let e of n){if(t_.get(e))continue;let n=t[e];if(!n)continue;n.sort((e,t)=>e-t);let i=u_(n);if(i.every(t=>l_(e,t)))continue;let a=m_(e_,e,{});r.push(r_(e,i,a))}return await Promise.all(r).catch(()=>{}),e&&e.length>0&&i_(e,e_),e_.reduce(),e}function r_(e,t,n){return new Promise(r=>{let i=Je(e),a=Ye({input:i});function o(){i.destroy(),r()}let s=0,c=0,l=t[c];if(l===void 0)return void o();let u=l[0],d=l[1];function f(){t_.set(e,1),a.close(),a.removeAllListeners(),o()}i.on(`error`,f),a.on(`error`,f),a.on(`close`,o),a.on(`line`,e=>{if(s++,!(s<u)&&(n[s]=h_(e,0),s>=d)){if(c===t.length-1){a.close(),a.removeAllListeners();return}c++;let e=t[c];if(e===void 0){a.close(),a.removeAllListeners();return}u=e[0],d=e[1]}})})}function i_(e,t){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno==`number`){let e=t.get(n.filename);if(e===void 0)continue;a_(n.lineno,n,e)}}function a_(e,t,n){if(t.lineno===void 0||n===void 0)return;t.pre_context=[];for(let r=f_(e);r<e;r++){let e=n[r];if(e===void 0)return void o_(t);t.pre_context.push(e)}if(n[e]===void 0)return void o_(t);t.context_line=n[e];let r=p_(e);t.post_context=[];for(let i=e+1;i<=r;i++){let e=n[i];if(e===void 0)break;t.post_context.push(e)}}function o_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function s_(e){return e.startsWith(`node:`)||e.endsWith(`.min.js`)||e.endsWith(`.min.cjs`)||e.endsWith(`.min.mjs`)||e.startsWith(`data:`)}function c_(e){return e.lineno!==void 0&&e.lineno>1e4||e.colno!==void 0&&e.colno>1e3}function l_(e,t){let n=e_.get(e);if(n===void 0)return!1;for(let e=t[0];e<=t[1];e++)if(n[e]===void 0)return!1;return!0}function u_(e){if(!e.length)return[];let t=0,n=e[0];if(typeof n!=`number`)return[];let r=d_(n),i=[];for(;;){if(t===e.length-1){i.push(r);break}let n=e[t+1];if(typeof n!=`number`)break;n<=r[1]?r[1]=n+7:(i.push(r),r=d_(n)),t++}return i}function d_(e){return[f_(e),p_(e)]}function f_(e){return Math.max(1,e-7)}function p_(e){return e+7}function m_(e,t,n){let r=e.get(t);return r===void 0?(e.set(t,n),n):r}function h_(e,t){let n=e,r=n.length;if(r<=150)return n;t>r&&(t=r);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,r);return a>r-5&&(a=r),a===r&&(i=Math.max(a-140,0)),n=n.slice(i,a),i>0&&(n=`...${n}`),a<r&&(n+=`...`),n}function g_(e,t){let n=!1;return Object.assign(r=>{let i=global.process.listeners(`uncaughtException`).filter(e=>e.name!==`domainUncaughtExceptionClear`&&!0!==e._posthogErrorHandler).length===0;e(r,{mechanism:{type:`onuncaughtexception`,handled:!1}}),!n&&i&&(n=!0,t(r))},{_posthogErrorHandler:!0})}function __(e,t){globalThis.process?.on(`uncaughtException`,g_(e,t))}function v_(e){globalThis.process?.on(`unhandledRejection`,t=>e(t,{mechanism:{type:`onunhandledrejection`,handled:!1}}))}var y_=class e{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Yh({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Lh(e)&&`__posthog_previously_captured_error`in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,n,r){let i={...r};n||(i.$process_person_profile=!1);let a=this.errorPropertiesBuilder.buildFromUnknown(e,t);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:`$exception`,distinctId:n||Oh(),properties:{...a,...i},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(__(this.onException.bind(this),this.onFatalError.bind(this)),v_(this.onException.bind(this)))}onException(t,n){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let r=await e.buildEventMessage(t,n),i=r.properties?.$exception_list[0]?.type??`Exception`;return this._rateLimiter.consumeRateLimit(i)?void this._logger.info(`Skipping exception capture because of client rate limiting.`,{exception:i}):this.client.capture(r)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};const b_={ERRORS_WHILE_COMPUTING:`errors_while_computing_flags`,FLAG_MISSING:`flag_missing`,QUOTA_LIMITED:`quota_limited`,UNKNOWN_ERROR:`unknown_error`};async function x_(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`SubtleCrypto API not available`);let n=await t.digest(`SHA-1`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const S_=[`is_not`];var C_=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name=`ClientError`,this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},w_=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},T_=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:r,host:i,customHeaders:a,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=r,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=a,this.onLoad=o.onLoad,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},r={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:r,evaluationCache:i}}async getFeatureFlag(e,t,n={},r={},i={}){await this.loadFeatureFlags();let a,o;if(!this.loadedSuccessfullyOnce)return a;if(o=this.featureFlagsByKey[e],o!==void 0){let s=this.createEvaluationContext(t,n,r,i);try{a=(await this.computeFlagAndPayloadLocally(o,s)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof w_||t instanceof Q?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},r={},i=this.featureFlags.length==0,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:i}=await this.computeFlagAndPayloadLocally(e,o);n[e.key]=t,i&&(r[e.key]=i)}catch(t){t instanceof w_||t instanceof Q?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),i=!0}})),{response:n,payloads:r,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:r,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let a;a=r===void 0?await this.computeFlagValueLocally(e,t):r;let o=this.getFeatureFlagPayload(e.key,a);return{value:a,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:r,personProperties:i,groupProperties:a}=t;if(e.ensure_experience_continuity)throw new Q(`Flag has experience continuity enabled`);if(!e.active)return!1;let o=(e.filters||{}).aggregation_group_type_index;if(o!=null){let n=this.groupTypeMapping[String(o)];if(!n)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${o} for feature flag ${e.key}`)),new Q(`Flag has unknown group type index`);if(!(n in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier===`device_id`&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id===``)&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let s=a[n];return await this.matchFeatureFlagProperties(e,r[n],s,t)}{let r=this.getBucketingValueForFlag(e,n,i);if(r===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new Q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,r,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier===`device_id`){let e=n?.$device_id;return e==null||e===``?void 0:e}return t}getFeatureFlagPayload(e,t){let n=null;if(!1!==t&&t!=null&&(typeof t==`boolean`?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t==`string`&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n==`object`)return n;if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:r}=n,i=e.key;if(!this.featureFlagsByKey)throw new Q(`Feature flags not available for dependency evaluation`);if(!(`dependency_chain`in e))throw new Q(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new Q(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(a.length===0)throw new Q(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let e of a){if(!(e in r)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{r[e]=await this.computeFlagValueLocally(t,n)}catch(t){throw new Q(`Error evaluating flag dependency '${e}' for flag '${i}': ${t}`)}else r[e]=!1;else throw new Q(`Missing flag dependency '${e}' for flag '${i}'`)}if(r[e]==null)throw new Q(`Dependency '${e}' could not be evaluated`)}let o=r[i];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return typeof e==`boolean`?e===t||typeof t==`string`&&t!==``&&!0===e:typeof e==`string`?t===e:!1}async matchFeatureFlagProperties(e,t,n,r){let i=e.filters||{},a=i.groups||[],o=!1,s;for(let c of a)try{if(await this.isConditionMatch(e,t,c,n,r)){let n=c.variant,r=i.multivariate?.variants||[];s=n&&r.some(e=>e.key===n)?n:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(e instanceof w_)throw e;if(e instanceof Q)o=!0;else throw e}if(s!==void 0)return s;if(o)throw new Q(`Can't determine if feature flag is enabled or not with given properties`);return!1}async isConditionMatch(e,t,n,r,i){let a=n.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((n.properties||[]).length>0){for(let e of n.properties){let t=e.type,n=!1;if(n=t===`cohort`?k_(e,r,this.cohorts,this.debugMode):t===`flag`?await this.evaluateFlagDependency(e,r,i):D_(e,r,o),!n)return!1}if(a==null)return!0}return!(a!=null&&await E_(e.key,t)>a/100)}async getMatchingVariant(e,t){let n=await E_(e.key,t,`variant`),r=this.variantLookupTable(e).find(e=>n>=e.valueMin&&n<e.valueMax);if(r)return r.key}variantLookupTable(e){let t=[],n=0,r=0;return((e.filters||{}).multivariate?.variants||[]).forEach(e=>{r=n+e.rollout_percentage/100,t.push({valueMin:n,valueMax:r,key:e.key}),n=r}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(`, `)}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping fetch, in backoff period`)):(this.loadingPromise||=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0}),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&=(clearTimeout(this.poller),void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache(`Loaded flags from cache (skipped fetch)`)||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Flags not modified (304), using cached data`)),this.flagsEtag=t.headers?.get(`ETag`)??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new C_(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn(`[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts`),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new C_(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new C_(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!(`flags`in n))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get(`ETag`)??void 0;let r={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(r),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(r)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags);break}default:return}}catch(e){e instanceof C_&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e=`GET`,t){let n={...this.customHeaders,"Content-Type":`application/json`,Authorization:`Bearer ${this.personalApiKey}`};return t&&(n[`If-None-Match`]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions(`GET`,this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout==`number`){let e=new AbortController;n=yg(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((t,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}};async function E_(e,t,n=``){let r=await x_(`${e}.${t}${n}`);return parseInt(r.slice(0,15),16)/0x1000000000000000}function D_(e,t,n){let r=e.key,i=e.value,a=e.operator||`exact`;if(r in t){if(a===`is_not_set`)throw new Q(`Operator is_not_set is not supported`)}else throw new Q(`Property ${r} not found in propertyValues`);let o=t[r];if(o==null&&!S_.includes(a))return n&&n(`Property ${r} cannot have a value of null/undefined with the ${a} operator`),!1;function s(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function c(e,t,n){if(n===`gt`)return e>t;if(n===`gte`)return e>=t;if(n===`lt`)return e<t;if(n===`lte`)return e<=t;throw Error(`Invalid operator: ${n}`)}switch(a){case`exact`:return s(i,o);case`is_not`:return!s(i,o);case`is_set`:return r in t;case`icontains`:return String(o).toLowerCase().includes(String(i).toLowerCase());case`not_icontains`:return!String(o).toLowerCase().includes(String(i).toLowerCase());case`regex`:return j_(String(i))&&String(o).match(String(i))!==null;case`not_regex`:return j_(String(i))&&String(o).match(String(i))===null;case`gt`:case`gte`:case`lt`:case`lte`:{let e=typeof i==`number`?i:null;if(typeof i==`string`)try{e=parseFloat(i)}catch{}return e==null||o==null?c(String(o),String(i),a):typeof o==`string`?c(o,String(i),a):c(o,e,a)}case`is_date_after`:case`is_date_before`:{if(typeof i==`boolean`)throw new Q(`Date operations cannot be performed on boolean values`);let e=R_(String(i));if(e??=L_(i),e==null)throw new Q(`Invalid date: ${i}`);let t=L_(o);return[`is_date_before`].includes(a)?t<e:t>e}case`semver_eq`:return N_(M_(String(o)),M_(String(i)))===0;case`semver_neq`:return N_(M_(String(o)),M_(String(i)))!==0;case`semver_gt`:return N_(M_(String(o)),M_(String(i)))>0;case`semver_gte`:return N_(M_(String(o)),M_(String(i)))>=0;case`semver_lt`:return N_(M_(String(o)),M_(String(i)))<0;case`semver_lte`:return N_(M_(String(o)),M_(String(i)))<=0;case`semver_tilde`:{let e=M_(String(o)),{lower:t,upper:n}=P_(String(i));return N_(e,t)>=0&&N_(e,n)<0}case`semver_caret`:{let e=M_(String(o)),{lower:t,upper:n}=F_(String(i));return N_(e,t)>=0&&N_(e,n)<0}case`semver_wildcard`:{let e=M_(String(o)),{lower:t,upper:n}=I_(String(i));return N_(e,t)>=0&&N_(e,n)<0}default:throw new Q(`Unknown operator: ${a}`)}}function O_(e,t){if(!(e in t))throw new w_(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function k_(e,t,n,r=!1){let i=String(e.value);O_(i,n);let a=n[i];return A_(a,t,n,r)}function A_(e,t,n,r=!1){if(!e)return!0;let i=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if(`values`in a[0]){for(let e of a)try{let a=A_(e,t,n,r);if(i===`AND`){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof w_)throw t;if(t instanceof Q)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Q(`Can't match cohort without a given cohort property value`);return i===`AND`}for(let e of a)try{let a;if(e.type===`cohort`)a=k_(e,t,n,r);else if(e.type===`flag`){r&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${e.key||`unknown`}'`);continue}else a=D_(e,t);let o=e.negation||!1;if(i===`AND`){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof w_)throw t;if(t instanceof Q)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new Q(`can't match cohort without a given cohort property value`);return i===`AND`}function j_(e){try{return new RegExp(e),!0}catch{return!1}}function M_(e){let t=String(e).trim().replace(/^[vV]/,``).split(`-`)[0].split(`+`)[0];if(!t||t.startsWith(`.`))throw new Q(`Invalid semver: ${e}`);let n=t.split(`.`),r=t=>{if(t===void 0||t===``)return 0;if(!/^\d+$/.test(t))throw new Q(`Invalid semver: ${e}`);return parseInt(t,10)};return[r(n[0]),r(n[1]),r(n[2])]}function N_(e,t){for(let n=0;n<3;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function P_(e){let t=M_(e);return{lower:[t[0],t[1],t[2]],upper:[t[0],t[1]+1,0]}}function F_(e){let[t,n,r]=M_(e),i=[t,n,r],a;return a=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:i,upper:a}}function I_(e){let t=String(e).trim().replace(/^[vV]/,``).replace(/\.\*$/,``).replace(/\*$/,``);if(!t)throw new Q(`Invalid wildcard semver: ${e}`);let n=t.split(`.`),r=parseInt(n[0],10);if(isNaN(r))throw new Q(`Invalid wildcard semver: ${e}`);let i,a;if(n.length===1)i=[r,0,0],a=[r+1,0,0];else{let t=parseInt(n[1],10);if(isNaN(t))throw new Q(`Invalid wildcard semver: ${e}`);i=[r,t,0],a=[r,t+1,0]}return{lower:i,upper:a}}function L_(e){if(e instanceof Date)return e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Q(`${e} is in an invalid date format`)}throw new Q(`The date provided ${e} must be a string, number, or date object`)}function R_(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let r=t.groups.interval;if(r==`h`)n.setUTCHours(n.getUTCHours()-e);else if(r==`d`)n.setUTCDate(n.getUTCDate()-e);else if(r==`w`)n.setUTCDate(n.getUTCDate()-7*e);else if(r==`m`)n.setUTCMonth(n.getUTCMonth()-e);else{if(r!=`y`)return null;n.setUTCFullYear(n.getUTCFullYear()-e)}return n}}var z_=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t===null?void 0:t}constructor(){this._memoryStorage={}}};const B_=3e4;var V_=class extends Ag{constructor(e,t={}){if(super(e,t),this._memoryStorage=new z_,this.options=t,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof t.featureFlagsPollingInterval==`number`?Math.max(t.featureFlagsPollingInterval,100):B_,typeof t.waitUntilDebounceMs==`number`&&(this.options.waitUntilDebounceMs=Math.max(t.waitUntilDebounceMs,0)),typeof t.waitUntilMaxWaitMs==`number`&&(this.options.waitUntilMaxWaitMs=Math.max(t.waitUntilMaxWaitMs,0)),t.personalApiKey){if(t.personalApiKey.includes(`phc_`))throw Error(`Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.`);!1!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new T_({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit(`error`,e)},onLoad:e=>{this._events.emit(`localEvaluationFlagsLoaded`,e)},customHeaders:this.getCustomHeaders(),cacheProvider:t.flagDefinitionCacheProvider,strictLocalEvaluation:t.strictLocalEvaluation}))}this.errorTracking=new y_(this,t,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||5e4}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=super.flush(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,n=new Promise(e=>{t=e});try{e(n)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt>=(this.options.waitUntilMaxWaitMs??500);if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),t)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=yg(()=>{this.resolveWaitUntilFlush()},n)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getLibraryVersion(){return`5.28.5`}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){typeof e==`string`&&this._logger.warn(`Called capture() with a string as the first argument when an object was expected.`),e.event===`$exception`&&!e._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStateless(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}async captureImmediate(e){return typeof e==`string`&&this._logger.warn(`Called captureImmediate() with a string as the first argument when an object was expected.`),e.event===`$exception`&&!e._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:n,options:r})=>super.captureStatelessImmediate(e,t,n,{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid})).catch(e=>{e&&console.error(e)}))}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:r,$set_once:i,$anon_distinct_id:a,...o}=t,s={$set:r||o,$set_once:i||{},$anon_distinct_id:a??void 0};super.identifyStateless(e,s,{disableGeoip:n})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:r,$set_once:i,$anon_distinct_id:a,...o}=t,s={$set:r||o,$set_once:i||{},$anon_distinct_id:a??void 0};super.identifyStatelessImmediate(e,s,{disableGeoip:n})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=B_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{r(),t(!1)},e),r=this._events.on(`localEvaluationFlagsLoaded`,e=>{clearTimeout(n),r(),t(e>0)})})}_resolveDistinctId(e,t){return typeof e==`string`?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},r){let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let t=this._flagOverrides[e];if(t===void 0)return;let n=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:typeof t==`string`?t:void 0,payload:n}}let{groups:a,disableGeoip:o}=n,{onlyEvaluateLocally:s,personProperties:c,groupProperties:l}=n,u=this.addLocalPersonAndGroupProperties(t,a,c,l);c=u.allPersonProperties,l=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,a,c,l);s??=this.options.strictLocalEvaluation??!1;let f,p=!1,m,h,g,_,v,y;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let n=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,d,{matchValue:r});if(n){p=!0;let r=n.value;_=t.id,y=`Evaluated locally`,f={key:e,enabled:!1!==r,variant:typeof r==`string`?r:void 0,payload:n.payload??void 0}}}catch(t){if(t instanceof w_||t instanceof Q)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!p&&!s){let t=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,o,[e]);if(t===void 0)g=b_.UNKNOWN_ERROR;else{m=t.requestId,h=t.evaluatedAt;let n=[];t.errorsWhileComputingFlags&&n.push(b_.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes(`feature_flags`)&&n.push(b_.QUOTA_LIMITED);let r=t.flags[e];if(r===void 0)n.push(b_.FLAG_MISSING);else{_=r.metadata?.id,v=r.metadata?.version,y=r.reason?.description??r.reason?.code;let t;if(r.metadata?.payload!==void 0)try{t=JSON.parse(r.metadata.payload)}catch{t=r.metadata.payload}f={key:e,enabled:r.enabled,variant:r.variant,payload:t}}n.length>0&&(g=n.join(`,`))}}if(i){let n=f===void 0?void 0:!1===f.enabled?!1:f.variant??!0,r=`${e}_${n}`;if(!(t in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[t].includes(r)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(r):this.distinctIdHasSentFlagCalls[t]=[r];let i={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:_,$feature_flag_version:v,$feature_flag_reason:y,locally_evaluated:p,[`$feature/${e}`]:n,$feature_flag_request_id:m,$feature_flag_evaluated_at:p?Date.now():h};if(p&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();e!==void 0&&(i.$feature_flag_definitions_loaded_at=e)}g&&(i.$feature_flag_error=g),this.capture({distinctId:t,event:`$feature_flag_called`,properties:i,groups:a,disableGeoip:o})}}return f!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[e]}),f}async getFeatureFlag(e,t,n){let r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(r!==void 0)return!1===r.enabled?!1:r.variant??!0}async getFeatureFlagPayload(e,t,n,r){if(this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:r,options:i}=this._resolveDistinctId(t,n);return r?this._getFeatureFlagResult(e,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn(`[PostHog] distinctId is required — pass it explicitly or use withContext()`)}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw Error(`Personal API key is required for remote config payload decryption`);let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n==`string`)try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){let r=await this.getFeatureFlag(e,t,n);if(r!==void 0)return!!r||!1}async getAllFlags(e,t){let{distinctId:n,options:r}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,r)).featureFlags||{}:(this._logger.warn(`[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()`),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:r}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn(`[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()`),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:a,flagKeys:o}=r||{},{onlyEvaluateLocally:s,personProperties:c,groupProperties:l}=r||{},u=this.addLocalPersonAndGroupProperties(n,i,c,l);c=u.allPersonProperties,l=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,i,c,l);s??=this.options.strictLocalEvaluation??!1;let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),p={},m={},h=!0;if(f&&(p=f.response,m=f.payloads,h=f.fallbackToFlags),h&&!s){let e=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,o);p={...p,...e.flags||{}},m={...m,...e.payloads||{}}}return this._flagOverrides!==void 0&&(p={...p,...this._flagOverrides}),this._payloadOverrides!==void 0&&(m={...m,...this._payloadOverrides}),{featureFlags:p,featureFlagPayloads:m}}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:r,disableGeoip:i}){super.groupIdentifyStateless(e,t,n,{disableGeoip:i},r)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){`flags`in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),`payloads`in e&&(!1===e.payloads?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(`flags`in t){let e=t.flags;if(!1===e||Array.isArray(e)||typeof e==`object`&&e)return!0}if(`payloads`in t){let e=t.payloads;if(!1===e||typeof e==`object`&&e)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown();try{return await super._shutdown(e)}finally{t?.()}}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:`GET`,headers:{...this.getCustomHeaders(),"Content-Type":`application/json`,Authorization:`Bearer ${this.options.personalApiKey}`}},r=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout==`number`){let e=new AbortController;r=yg(()=>{e.abort()},this.options.requestTimeout),n.signal=e.signal}try{return await this.fetch(t,n)}catch(e){this._events.emit(`error`,e);return}finally{r&&clearTimeout(r)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},r={};for(let[i,a]of Object.entries(e))if(Kh(a)&&t&&i in t){let e={};for(let[t,n]of Object.entries(a))e[String(t)]=String(n);r[String(i)]=e}else n[String(i)]=String(a);return{personProperties:n,groupProperties:r}}async getFeatureFlagsForEvent(e,t,n,r){let i=r?.personProperties||{},a=r?.groupProperties||{},o=r?.flagKeys;if(r?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,n]of Object.entries(t||{}))r[e]=String(n);return await this.getAllFlags(e,{groups:r,personProperties:i,groupProperties:a,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,a,n)).flags}addLocalPersonAndGroupProperties(e,t,n,r){let i={distinct_id:e,...n||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...r?.[e]||{}};return{allPersonProperties:i,allGroupProperties:a}}createFeatureFlagEvaluationContext(e,t,n,r){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:r||{},evaluationCache:{}}}captureException(e,t,n,r){if(!y_.isPreviouslyCapturedError(e)){let i=Error(`PostHog syntheticException`);this.addPendingPromise(y_.buildEventMessage(e,{syntheticException:i},t,n).then(e=>this.capture({...e,uuid:r})))}}async captureExceptionImmediate(e,t,n){if(!y_.isPreviouslyCapturedError(e)){let r=Error(`PostHog syntheticException`);return this.addPendingPromise(y_.buildEventMessage(e,{syntheticException:r},t,n).then(e=>this.captureImmediate(e)))}}async prepareEventMessage(e){let{distinctId:t,event:n,properties:r,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c}=e,l=this.context?.get(),u=t||l?.distinctId,d={...this.props,...l?.properties||{},...r||{}};u||(u=Oh(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:u,event:n,properties:d,groups:i,sendFeatureFlags:a,timestamp:o,disableGeoip:s,uuid:c});if(!f)return Promise.reject(null);let p=await Promise.resolve().then(async()=>{if(a){let e=typeof a==`object`?a:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,i,s,e)}return f.event,{}}).then(e=>{let t={};if(e)for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let n=Object.keys(e||{}).filter(t=>e?.[t]!==!1).sort();return n.length>0&&(t.$active_feature_flags=n),t}).catch(()=>({})).then(e=>({...e,...f.properties||{},$groups:f.groups||i}));return f.event===`$pageview`&&this.options.__preview_capture_bot_pageviews&&typeof p.$raw_user_agent==`string`&&Mh(p.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event=`$bot_pageview`,p.$browser_type=`bot`),{distinctId:f.distinctId,event:f.event,properties:p,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],r=e;for(let t of n){if(r=t(r),!r)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!r.properties||Object.keys(r.properties).length===0){let e=`Event '${r.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return r}},H_=class{constructor(){this.storage=new Xe}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};const U_=`posthog-node`;function W_(e,{organization:t,projectId:n,prefix:r,severityAllowList:i=[`error`],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(i===`*`||i.includes(o.level)))return o;o.tags||={};let s=o.tags[G_.POSTHOG_ID_TAG];if(s===void 0)return o;let c=e.options.host??`https://us.i.posthog.com`,l=new URL(`/project/${e.apiKey}/person/${s}`,c).toString();o.tags[`PostHog Person URL`]=l;let u=o.exception?.values||[],d=u.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:`raw`,frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:`node:javascript`}))}:void 0})),f={$exception_message:u[0]?.value||o.message,$exception_type:u[0]?.type,$exception_level:o.level,$exception_list:d,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:u[0]?.value||o.message,$sentry_exception_type:u[0]?.type,$sentry_tags:o.tags};return t&&n&&(f.$sentry_url=(r||`https://sentry.io/organizations/`)+t+`/issues/?project=`+n+`&query=`+o.event_id),a&&e.capture({event:`$exception`,distinctId:s,properties:f}),o}}var G_=class{static#e=this.POSTHOG_ID_TAG=`posthog_distinct_id`;constructor(e,t,n,r,i){this.name=U_,this.name=U_,this.setupOnce=function(a,o){let s=o()?.getClient()?.getDsn()?.projectId;a(W_(e,{organization:t,projectId:s,prefix:n,severityAllowList:r,sendExceptionsToPostHog:i??!0}))}}};y_.errorPropertiesBuilder=new Fg([new Zg,new Gg,new Xg,new qg,new Qg],Wg(`node:javascript`,Rg),[mh(),n_]);const K_=new class extends V_{getLibraryId(){return`posthog-node`}initializeContext(){return new H_}}(`phc_t5FKk9mlc4pKbbBimiIlrM5Acq9meRp1FSuNjmwxjAX`,{host:`https://us.i.posthog.com`});var q_=class extends C.Service()(`@expect/AnalyticsProvider`){static layerPostHog=m.succeed(this)({capture:e=>u.sync(()=>{K_.captureImmediate({event:e.eventName,properties:e.properties,distinctId:e.distinctId})}),identify:e=>u.sync(()=>{K_.identify({distinctId:e.distinctId,properties:{email:e.email,...e.name?{name:e.name}:{}}})}),flush:u.tryPromise({try:()=>K_.flush(),catch:e=>e}).pipe(u.ignore)});static layerDev=m.succeed(this)({capture:e=>u.logInfo(`Tracked event`,{eventName:e.eventName,distinctId:e.distinctId,...e.properties}).pipe(u.annotateLogs({module:`Analytics`})),identify:e=>u.logInfo(`Identified user`,{distinctId:e.distinctId,email:e.email,name:e.name}).pipe(u.annotateLogs({module:`Analytics`})),flush:u.void})},J_=class extends C.Service()(`@expect/Analytics`,{make:u.gen(function*(){let e=yield*q_,t=yield*c.option(c.string(`NO_TELEMETRY`)),n=yield*c.option(c.string(`NO_TELEMTRY`)),r=_.match(t,{onNone:()=>!1,onSome:e=>e===`1`})||_.match(n,{onNone:()=>!1,onSome:e=>e===`1`}),i=yield*u.tryPromise(()=>(0,oh.machineId)()).pipe(u.orDie),a=ph(process.cwd()),o=(t,...[n])=>r?u.void:u.gen(function*(){let r={timestamp:new Date().toISOString(),projectId:a};yield*e.capture({eventName:t,properties:{...r,...n??{}},distinctId:i})}).pipe(u.catchCause(e=>u.logWarning(`Analytics capture failed`,{eventName:t,cause:e}).pipe(u.annotateLogs({module:`Analytics`}))));return{capture:o,track:((e,t)=>n=>u.tap(n,n=>{let r=t?t(n):void 0;return o.call(void 0,e,...r===void 0?[]:[r])})),flush:r?u.void:e.flush}})}){static layerPostHog=m.effect(this)(this.make).pipe(m.provide(q_.layerPostHog),m.provide(be.layer));static layerDev=m.effect(this)(this.make).pipe(m.provide(q_.layerDev),m.provide(be.layer))};const Y_=e=>{let t=s.squash(e);return{error_tag:v.hasProperty(t,`_tag`)?String(t._tag):`Unknown`,error_message:s.pretty(e)}};(class extends C.Service()(`@expect/ErrorHandler`,{make:u.gen(function*(){let e=yield*J_;return{orDie:t=>t.pipe(u.tapCause(t=>e.capture(`error:unexpected`,Y_(t))),u.orDie),streamOrDie:t=>t.pipe(w.tapCause(t=>e.capture(`error:unexpected`,Y_(t))),w.orDie),tapCause:(...t)=>n=>n.pipe(u.tapCause(n=>u.all([e.capture(`error:expected`,Y_(n)),u.logError(...t,n)],{discard:!0})))}})}){static layer=m.effect(this)(this.make)}),Ze.layerWebSocket().pipe(m.provide(Ne.layerWebSocketConstructor));const X_=m.unwrap(u.gen(function*(){let e=`expect-cli`;return Qe.layerJson({baseUrl:`https://api.axiom.co`,resource:{serviceName:e},headers:{Authorization:`Bearer xaat-a6ce2fdb-d378-444e-9d72-bb458867187a`,"X-Axiom-Dataset":e}})})).pipe(m.provide(Me.layerUndici),m.orDie),Z_=Be()(et(e=>({agentBackend:`claude`,browserHeaded:!1,replayHost:`https://expect.dev`,autoSaveFlows:!0,notifications:void 0,instructionHistory:[],setAgentBackend:t=>e({agentBackend:t}),toggleAutoSave:()=>e(e=>({autoSaveFlows:!e.autoSaveFlows})),toggleNotifications:()=>e(e=>({notifications:e.notifications!==!0})),rememberInstruction:t=>{t&&e(e=>({instructionHistory:[t,...e.instructionHistory.filter(e=>e!==t)].slice(0,20)}))}}),{name:`prompt-history`,storage:$e(()=>gm),partialize:e=>({instructionHistory:e.instructionHistory,notifications:e.notifications})})),Q_=J_.layerPostHog,$_=(e,...[t])=>u.runPromise(u.gen(function*(){let n=yield*J_;yield*n.capture.call(n,e,...t===void 0?[]:[t])}).pipe(u.catchCause(()=>u.void),u.provide(Q_))),ev=()=>$_(`session:started`,{mode:`interactive`,skip_planning:!1,browser_headed:Z_.getState().browserHeaded}),tv=e=>u.runPromise(u.gen(function*(){let t=yield*J_;yield*t.capture(`session:ended`,{session_ms:Date.now()-e}),yield*t.flush}).pipe(u.provide(Q_))),nv=()=>{let e=ie(15);if(e[0]!==`d0800512c2dc78a7eda82a0b9a76ade6e9bb7fa0b8809da478275b21ba8ce62d`){for(let t=0;t<15;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`d0800512c2dc78a7eda82a0b9a76ade6e9bb7fa0b8809da478275b21ba8ce62d`}let t=Pt(),n;e[1]===t.RED?n=e[2]:(n=V(O,{color:t.RED,children:U.cross}),e[1]=t.RED,e[2]=n);let r;e[3]===t.GREEN?r=e[4]:(r=V(O,{color:t.GREEN,children:U.tick}),e[3]=t.GREEN,e[4]=r);let i;e[5]===t.PRIMARY?i=e[6]:(i=V(O,{bold:!0,color:t.PRIMARY,children:` Expect`}),e[5]=t.PRIMARY,e[6]=i);let a;e[7]===t.DIM?a=e[8]:(a=V(O,{color:t.DIM,children:` v${gt}`}),e[7]=t.DIM,e[8]=a);let o;return e[9]!==t.BORDER||e[10]!==n||e[11]!==r||e[12]!==i||e[13]!==a?(o=V(E,{children:H(O,{color:t.BORDER,children:[n,r,i,a]})}),e[9]=t.BORDER,e[10]=n,e[11]=r,e[12]=i,e[13]=a,e[14]=o):o=e[14],o},rv=[{id:`enable-sync`,label:`Use existing cookies`,detail:`Recommended. Uses your browser session as-is.`},{id:`run-without-sync`,label:`Skip cookies`,detail:`Not recommended. Tests requiring login will fail.`}],iv=e=>{let t=ie(34);if(t[0]!==`e3c7abb53538ed236081ea9ec92e2272ee1c8b466fbb62e1c8ec442744cd59e3`){for(let e=0;e<34;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e3c7abb53538ed236081ea9ec92e2272ee1c8b466fbb62e1c8ec442744cd59e3`}let{changesFor:n,instruction:r,savedFlow:i}=e,a=Pt(),o=Zm(av),[s,c]=L(0),l;t[1]!==n||t[2]!==r||t[3]!==i||t[4]!==o?(l=e=>{let t=e.id===`enable-sync`;$_(`cookies:sync_choice`,{choice:t?`use_cookies`:`skip_cookies`}),o(Xm({changesFor:n,instruction:r,savedFlow:i,requiresCookies:t}))},t[1]=n,t[2]=r,t[3]=i,t[4]=o,t[5]=l):l=t[5];let u=l,d;t[6]!==u||t[7]!==s?(d=(e,t)=>{(t.downArrow||e===`j`||t.ctrl&&e===`n`)&&c(ov),(t.upArrow||e===`k`||t.ctrl&&e===`p`)&&c(sv),e===`c`&&u(rv[0]),e===`a`&&u(rv[1]),t.return&&u(rv[s])},t[6]=u,t[7]=s,t[8]=d):d=t[8],te(d);let f;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(f=V(nv,{}),t[9]=f):f=t[9];let p;t[10]===a.DIM?p=t[11]:(p=V(O,{color:a.DIM,children:U.pointerSmall}),t[10]=a.DIM,t[11]=p);let m;t[12]!==a.TEXT||t[13]!==r?(m=V(O,{color:a.TEXT,children:r}),t[12]=a.TEXT,t[13]=r,t[14]=m):m=t[14];let h;t[15]!==p||t[16]!==m?(h=H(E,{children:[f,H(O,{wrap:`truncate`,children:[` `,p,` `,m]})]}),t[15]=p,t[16]=m,t[17]=h):h=t[17];let g;t[18]!==a.GREEN||t[19]!==a.YELLOW||t[20]!==s?(g=V(E,{marginTop:1,children:s===0?H(O,{color:a.GREEN,children:[U.tick,` Your signed-in session will be synced to the browser. Cookies stay on device.`]}):H(O,{color:a.YELLOW,children:[U.warning,` The browser won`,`'`,`t inherit your signed-in session without cookies.`]})}),t[18]=a.GREEN,t[19]=a.YELLOW,t[20]=s,t[21]=g):g=t[21];let _;t[22]!==a.DIM||t[23]!==a.PRIMARY||t[24]!==a.TEXT||t[25]!==u||t[26]!==s?(_=rv.map((e,t)=>{let n=t===s;return V(Lt,{onClick:()=>{c(t),u(e)},children:H(E,{flexDirection:`column`,marginBottom:1,children:[H(O,{children:[V(O,{color:n?a.PRIMARY:a.DIM,children:n?`${U.pointer} `:` `}),V(O,{color:n?a.PRIMARY:a.TEXT,bold:n,children:e.label})]}),H(O,{color:a.DIM,children:[` `,e.detail]})]})},e.id)}),t[22]=a.DIM,t[23]=a.PRIMARY,t[24]=a.TEXT,t[25]=u,t[26]=s,t[27]=_):_=t[27];let v;t[28]===_?v=t[29]:(v=V(E,{flexDirection:`column`,marginTop:1,children:_}),t[28]=_,t[29]=v);let y;return t[30]!==h||t[31]!==g||t[32]!==v?(y=H(E,{flexDirection:`column`,width:`100%`,paddingY:1,paddingX:1,children:[h,g,v]}),t[30]=h,t[31]=g,t[32]=v,t[33]=y):y=t[33],y};function av(e){return e.setScreen}function ov(e){return Math.min(rv.length-1,e+1)}function sv(e){return Math.max(0,e-1)}const cv=Be()(et(e=>({cookiesEnabled:!1,setCookiesEnabled:t=>e({cookiesEnabled:t}),toggleCookies:()=>e(e=>({cookiesEnabled:!e.cookiesEnabled})),lastBaseUrl:void 0,setLastBaseUrl:t=>e({lastBaseUrl:t})}),{name:`project-preferences`,storage:$e(()=>ym)})),lv=`spotify,raycast,google,controlce,controlcenter,cursor,electron,slack,discord,figma,redis,postgres,mysqld,mongod,mongos,memcached,dockerd,containerd,com.docke,docker,code,rapportd,wifiagent,airplayxpc,identitys,sharingd,bluetoothd,screencap,loginwind,systempol,corespeec,apsd,mds_store,spotlight,lsd`.split(`,`),uv=[[/next[\\/]dist[\\/]/,`next`],[/next-server/,`next`],[/vite[\\/]/,`vite`],[/vite-plus[\\/]/,`vite`],[/react-scripts[\\/]/,`react-scripts`],[/angular[\\/]cli[\\/]/,`angular`],[/remix[\\/]/,`remix`],[/astro[\\/]/,`astro`],[/nuxt[\\/]/,`nuxt`],[/svelte[\\/]/,`svelte`],[/webpack[\\/]/,`webpack`],[/webpack-dev-server/,`webpack`],[/turbopack[\\/]/,`turbopack`],[/remotion[\\/]/,`remotion`],[/gatsby[\\/]/,`gatsby`],[/parcel[\\/]/,`parcel`],[/http-server/,`http-server`],[/live-server/,`live-server`],[/serve[\\/]/,`serve`],[/express[\\/]/,`express`],[/fastify[\\/]/,`fastify`],[/hono[\\/]/,`hono`],[/elysia[\\/]/,`elysia`]],dv=e=>{let t=e.toLowerCase();return lv.some(e=>t.startsWith(e))},fv=e=>{if(!/^\d+$/.test(e))return``;try{let t=Ee(`lsof -p ${e} -a -d cwd -Fn`,{encoding:`utf-8`,timeout:1e3}).split(`
36
+ `).find(e=>e.startsWith(`n`));return t?t.slice(1):``}catch{return``}},pv=(e,t)=>{if(!/^\d+$/.test(e)||dv(t))return;let n=fv(e);try{let t=Ee(`ps -p ${e} -o command=`,{encoding:`utf-8`,timeout:1e3}).trim();for(let[e,r]of uv)if(e.test(t))return{name:r,isFramework:!0,cwd:n}}catch{}return{name:t,isFramework:!1,cwd:n}},mv=e=>{let t=new Set,n=[];for(let r of e.split(`
37
+ `)){let e=r.trim().split(/\s+/);if(e.length<9)continue;let i=e[0]??``,a=e[1]??``,o=(e[8]??``).match(/:(\d+)$/);if(!o)continue;let s=Number(o[1]);s<1024||s>65535||t.has(s)||(t.add(s),n.push({port:s,pid:a,commandName:i}))}return n},hv=()=>{try{let e=mv(Ee(`lsof -iTCP -sTCP:LISTEN -nP`,{encoding:`utf-8`,timeout:3e3})),t=[];for(let n of e){let e=pv(n.pid,n.commandName);e!==void 0&&(n.port>=32768&&!e.isFramework||t.push({port:n.port,processName:e.name,cwd:e.cwd}))}return t.sort((e,t)=>e.port-t.port)}catch{return[]}},gv=()=>N({queryKey:[`listening-ports`],queryFn:()=>hv(),refetchInterval:5e3}),_v=e=>`http://localhost:${e}`,vv=(e,t)=>{let n=t.toLowerCase();return String(e.port).includes(n)||e.processName.toLowerCase().includes(n)||e.cwd.toLowerCase().includes(n)},yv=e=>{let t=e.trim(),n=Number(t);if(Number.isInteger(n)&&n>=1&&n<=65535)return n;let r=t.match(/:(\d+)\/?$/);if(r){let e=Number(r[1]);if(Number.isInteger(e)&&e>=1&&e<=65535)return e}},bv=e=>{let t=ie(178);if(t[0]!==`84a93f0b7994a0f9318ab42167dadcad0ffba85a300830ca86b74045fc7574ce`){for(let e=0;e<178;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`84a93f0b7994a0f9318ab42167dadcad0ffba85a300830ca86b74045fc7574ce`}let{changesFor:n,instruction:r,savedFlow:i,requiresCookies:a}=e,o=Pt(),s=Zm(xv),c=cv(Sv),l=cv(Cv),{data:u}=gv(),d=u===void 0?[]:u,[f,p]=L(!1),[m,h]=L(``),[g,_]=L(!1),[v,y]=L(``),b;t[1]===c?b=t[2]:(b=()=>{if(!c)return new Set;let e=c.match(/:(\d+)/);return e?new Set([Number(e[1])]):new Set},t[1]=c,t[2]=b);let[x,S]=L(b),C;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(C=new Set,t[3]=C):C=t[3];let[w,ee]=L(C),T=d.map(wv),D=m?T.filter(e=>vv(e,m)):T,k=D.length,A=D.length+1,ne=D.length+2,re;t[4]===ne?re=t[5]:(re={itemCount:ne,visibleCount:10},t[4]=ne,t[5]=re);let{highlightedIndex:j,setHighlightedIndex:M,scrollOffset:N,handleNavigation:ae}=Km(re),oe;t[6]!==n||t[7]!==w||t[8]!==r||t[9]!==a||t[10]!==i||t[11]!==l||t[12]!==s?(oe=e=>{let t=[...e,...w];l(t.length>0?t[0]:void 0),t.length===0?$_(`port:skipped`):$_(`port:selected`,{port_count:t.length,has_custom_url:w.size>0}),s(Ym.Testing({changesFor:n,instruction:r,savedFlow:i,requiresCookies:a,baseUrls:t.length>0?t:void 0}))},t[6]=n,t[7]=w,t[8]=r,t[9]=a,t[10]=i,t[11]=l,t[12]=s,t[13]=oe):oe=t[13];let P=oe,se;t[14]===S?se=t[15]:(se=e=>{S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},t[14]=S,t[15]=se);let F=se,I;t[16]!==k||t[17]!==w||t[18]!==D||t[19]!==j||t[20]!==P||t[21]!==x||t[22]!==_||t[23]!==A?(I=()=>{if(j===A){P([]);return}if(x.size>0||w.size>0){P([...x].sort(Tv).map(_v));return}if(j===k){_(!0);return}let e=D[j];e&&P([_v(e.port)])},t[16]=k,t[17]=w,t[18]=D,t[19]=j,t[20]=P,t[21]=x,t[22]=_,t[23]=A,t[24]=I):I=t[24];let R=I,z=Ev,ce;t[25]!==y||t[26]!==ee||t[27]!==_?(ce=e=>{let t=e.trim();if(!t){_(!1);return}let n=z(t);ee(e=>new Set([...e,n])),y(``),_(!1)},t[25]=y,t[26]=ee,t[27]=_,t[28]=ce):ce=t[28];let le=ce,B;t[29]===ee?B=t[30]:(B=e=>{ee(t=>{let n=new Set(t);return n.delete(e),n})},t[29]=ee,t[30]=B);let ue=B,W;t[31]!==M||t[32]!==h?(W=e=>{h(e),M(0)},t[31]=M,t[32]=h,t[33]=W):W=t[33];let G=W,de;t[34]!==p||t[35]!==h||t[36]!==F?(de=e=>{let t=yv(e);if(t){F(t),p(!1),h(``);return}p(!1)},t[34]=p,t[35]=h,t[36]=F,t[37]=de):de=t[37];let fe=de,pe;t[38]!==R||t[39]!==k||t[40]!==D||t[41]!==ae||t[42]!==j||t[43]!==g||t[44]!==f||t[45]!==y||t[46]!==_||t[47]!==p||t[48]!==F?(pe=(e,t)=>{if(g){if(t.escape){_(!1),y(``);return}return}if(f){if(t.escape){p(!1);return}return}if(!ae(e,t)){if(e===`/`){p(!0);return}if(e===` `){if(j===k){_(!0);return}let e=D[j];e&&F(e.port);return}t.return&&R()}},t[38]=R,t[39]=k,t[40]=D,t[41]=ae,t[42]=j,t[43]=g,t[44]=f,t[45]=y,t[46]=_,t[47]=p,t[48]=F,t[49]=pe):pe=t[49],te(pe);let me,he,ge,_e,K,ve,ye,be,xe,q,Se,Ce,we,Te,Ee,De;if(t[50]!==o.DIM||t[51]!==o.GREEN||t[52]!==o.PRIMARY||t[53]!==o.TEXT||t[54]!==o.YELLOW||t[55]!==k||t[56]!==w||t[57]!==D||t[58]!==j||t[59]!==r||t[60]!==N||t[61]!==x||t[62]!==M||t[63]!==A||t[64]!==F){let e=D.slice(N,N+8);ge=N+8>=D.length,ve=ge;let n=D[j];_e=j===k,K=j===A;let i;t[81]!==w||t[82]!==x?(i=[...[...x].sort(Dv).map(_v),...w],t[81]=w,t[82]=x,t[83]=i):i=t[83];let a=i;he=E,q=`column`,Se=`100%`,Ce=1,we=1;let s;t[84]===Symbol.for(`react.memo_cache_sentinel`)?(s=V(nv,{}),t[84]=s):s=t[84];let c;t[85]===o.DIM?c=t[86]:(c=V(O,{color:o.DIM,children:U.pointerSmall}),t[85]=o.DIM,t[86]=c);let l;t[87]!==o.TEXT||t[88]!==r?(l=V(O,{color:o.TEXT,children:r}),t[87]=o.TEXT,t[88]=r,t[89]=l):l=t[89],t[90]!==c||t[91]!==l?(Te=H(E,{children:[s,H(O,{wrap:`truncate`,children:[` `,c,` `,l]})]}),t[90]=c,t[91]=l,t[92]=Te):Te=t[92],t[93]===o.DIM?Ee=t[94]:(Ee=V(E,{marginTop:1,children:V(O,{color:o.DIM,children:`Pick the dev server the agent should open in the browser.`})}),t[93]=o.DIM,t[94]=Ee);let u;t[95]!==o.GREEN||t[96]!==a?(u=a.length>0&&H(O,{color:o.GREEN,children:[U.tick,` `,a.join(`, `)]}),t[95]=o.GREEN,t[96]=a,t[97]=u):u=t[97];let d;t[98]!==o.DIM||t[99]!==a.length||t[100]!==n||t[101]!==_e||t[102]!==K?(d=a.length===0&&!K&&!_e&&n&&H(O,{color:o.DIM,children:[U.arrowRight,` `,_v(n.port)]}),t[98]=o.DIM,t[99]=a.length,t[100]=n,t[101]=_e,t[102]=K,t[103]=d):d=t[103];let f;t[104]!==o.YELLOW||t[105]!==a.length||t[106]!==K?(f=a.length===0&&K&&H(O,{color:o.YELLOW,children:[U.warning,` No base URL. The agent won`,`'`,`t know where your dev server is.`]}),t[104]=o.YELLOW,t[105]=a.length,t[106]=K,t[107]=f):f=t[107],t[108]!==u||t[109]!==d||t[110]!==f?(De=H(E,{marginTop:1,children:[u,d,f]}),t[108]=u,t[109]=d,t[110]=f,t[111]=De):De=t[111],me=E,ye=`column`,be=1;let p;t[112]!==o.DIM||t[113]!==o.PRIMARY||t[114]!==o.TEXT||t[115]!==j||t[116]!==N||t[117]!==x||t[118]!==M||t[119]!==F?(p=(e,t)=>{let n=t+N,r=n===j,i=x.has(e.port);return V(Lt,{onClick:()=>{M(n),F(e.port)},children:H(E,{children:[V(O,{color:r?o.PRIMARY:o.DIM,children:r?`${U.pointer} `:` `}),H(O,{color:i?o.PRIMARY:o.DIM,children:[i?U.checkboxOn:U.checkboxOff,` `]}),H(O,{color:r?o.PRIMARY:o.TEXT,bold:r,children:[`:`,e.port]}),e.processName&&H(O,{color:o.DIM,children:[` `,e.processName]}),e.cwd&&H(O,{color:o.DIM,children:[` `,e.cwd]})]})},e.port)},t[112]=o.DIM,t[113]=o.PRIMARY,t[114]=o.TEXT,t[115]=j,t[116]=N,t[117]=x,t[118]=M,t[119]=F,t[120]=p):p=t[120],xe=e.map(p),t[50]=o.DIM,t[51]=o.GREEN,t[52]=o.PRIMARY,t[53]=o.TEXT,t[54]=o.YELLOW,t[55]=k,t[56]=w,t[57]=D,t[58]=j,t[59]=r,t[60]=N,t[61]=x,t[62]=M,t[63]=A,t[64]=F,t[65]=me,t[66]=he,t[67]=ge,t[68]=_e,t[69]=K,t[70]=ve,t[71]=ye,t[72]=be,t[73]=xe,t[74]=q,t[75]=Se,t[76]=Ce,t[77]=we,t[78]=Te,t[79]=Ee,t[80]=De}else me=t[65],he=t[66],ge=t[67],_e=t[68],K=t[69],ve=t[70],ye=t[71],be=t[72],xe=t[73],q=t[74],Se=t[75],Ce=t[76],we=t[77],Te=t[78],Ee=t[79],De=t[80];let Oe;t[121]!==o.DIM||t[122]!==o.PRIMARY||t[123]!==o.TEXT||t[124]!==k||t[125]!==v||t[126]!==ge||t[127]!==le||t[128]!==_e||t[129]!==g||t[130]!==y||t[131]!==M||t[132]!==_?(Oe=ge&&V(Lt,{onClick:()=>{M(k),_(!0)},children:H(E,{children:[V(O,{color:_e?o.PRIMARY:o.DIM,children:_e?`${U.pointer} `:` `}),g&&H(E,{children:[V(O,{color:o.PRIMARY,children:`URL: `}),V(Ut,{focus:!0,value:v,placeholder:`http://localhost:4000 or staging.example.com`,onChange:y,onSubmit:le})]}),!g&&H(O,{color:_e?o.PRIMARY:o.TEXT,bold:_e,children:[`Enter a custom URL`,U.ellipsis]})]})}),t[121]=o.DIM,t[122]=o.PRIMARY,t[123]=o.TEXT,t[124]=k,t[125]=v,t[126]=ge,t[127]=le,t[128]=_e,t[129]=g,t[130]=y,t[131]=M,t[132]=_,t[133]=Oe):Oe=t[133];let ke;t[134]!==o.DIM||t[135]!==o.PRIMARY||t[136]!==o.TEXT||t[137]!==ge||t[138]!==w||t[139]!==ue?(ke=ge&&[...w].map(e=>V(Lt,{onClick:()=>ue(e),children:H(E,{children:[V(O,{children:` `}),H(O,{color:o.PRIMARY,children:[U.checkboxOn,` `]}),V(O,{color:o.TEXT,children:e}),V(O,{color:o.DIM,children:` (click to remove)`})]})},e)),t[134]=o.DIM,t[135]=o.PRIMARY,t[136]=o.TEXT,t[137]=ge,t[138]=w,t[139]=ue,t[140]=ke):ke=t[140];let Ae;t[141]!==o.DIM||t[142]!==o.PRIMARY||t[143]!==K||t[144]!==P||t[145]!==M||t[146]!==A||t[147]!==ve?(Ae=ve&&V(Lt,{onClick:()=>{M(A),P([])},children:H(E,{children:[V(O,{color:K?o.PRIMARY:o.DIM,children:K?`${U.pointer} `:` `}),H(O,{color:K?o.PRIMARY:o.DIM,bold:K,children:[`Skip `,U.arrowRight,` no base URL`]})]})}),t[141]=o.DIM,t[142]=o.PRIMARY,t[143]=K,t[144]=P,t[145]=M,t[146]=A,t[147]=ve,t[148]=Ae):Ae=t[148];let je;t[149]!==o.DIM||t[150]!==D.length||t[151]!==ve?(je=D.length===0&&!ve&&V(O,{color:o.DIM,children:`No matching ports`}),t[149]=o.DIM,t[150]=D.length,t[151]=ve,t[152]=je):je=t[152];let Me;t[153]!==me||t[154]!==ye||t[155]!==be||t[156]!==xe||t[157]!==Oe||t[158]!==ke||t[159]!==Ae||t[160]!==je?(Me=H(me,{flexDirection:ye,marginTop:be,children:[xe,Oe,ke,Ae,je]}),t[153]=me,t[154]=ye,t[155]=be,t[156]=xe,t[157]=Oe,t[158]=ke,t[159]=Ae,t[160]=je,t[161]=Me):Me=t[161];let Ne;t[162]!==G||t[163]!==fe||t[164]!==f||t[165]!==m?(Ne=V(Wt,{isSearching:f,query:m,onChange:G,onSubmit:fe}),t[162]=G,t[163]=fe,t[164]=f,t[165]=m,t[166]=Ne):Ne=t[166];let Pe;return t[167]!==he||t[168]!==q||t[169]!==Se||t[170]!==Ce||t[171]!==we||t[172]!==Te||t[173]!==Ee||t[174]!==De||t[175]!==Me||t[176]!==Ne?(Pe=H(he,{flexDirection:q,width:Se,paddingY:Ce,paddingX:we,children:[Te,Ee,De,Me,Ne]}),t[167]=he,t[168]=q,t[169]=Se,t[170]=Ce,t[171]=we,t[172]=Te,t[173]=Ee,t[174]=De,t[175]=Me,t[176]=Ne,t[177]=Pe):Pe=t[177],Pe};function xv(e){return e.setScreen}function Sv(e){return e.lastBaseUrl}function Cv(e){return e.setLastBaseUrl}function wv(e){return{port:e.port,processName:e.processName,cwd:e.cwd}}function Tv(e,t){return e-t}function Ev(e){let t=e.trim(),n=Number(t);return Number.isInteger(n)&&n>=1&&n<=65535?_v(n):/^https?:\/\//i.test(t)?t:`http://${t}`}function Dv(e,t){return e-t}const Ov=e=>{let t=e.replace(`#`,``);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},kv=(e,t,n)=>`#${[e,t,n].map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`,Av=(e,t,n)=>e+(t-e)*n,jv=(e,t,n)=>{let[r,i,a]=Ov(e),[o,s,c]=Ov(t);return kv(Av(r,o,n),Av(i,s,n),Av(a,c,n))},Mv=({text:e,baseColor:t,highlightColor:n,speed:r=1})=>{let[i,a]=L(-16),o=I(r);o.current=r;let s=I(e.length);s.current=e.length;let c=I(!1);return c.current||(c.current=!0,setTimeout(()=>{setInterval(()=>{let e=s.current+16;a(t=>t>=e?-16:t+o.current)},50)},0)),V(O,{children:[...e].map((e,r)=>{let a=Math.abs(r-i),o=Math.max(0,1-a/16);return V(O,{color:o>0?jv(t,n,o):t,children:e},r)})})},Nv=Be(e=>({executedPlan:void 0,expanded:!1,setExecutedPlan:t=>e({executedPlan:t}),setExpanded:t=>e({expanded:t}),toggleExpanded:()=>e(e=>({expanded:!e.expanded}))})),Pv=e=>st(Math.max(0,e),{secondsDecimalDigits:0}),Fv=new Set([`warpterminal`]),Iv=lt.stdout,Lv=ct({preferOuter:!0}),Rv=process.stdout.isTTY&&!Fv.has(Lv??``),zv=Rv&&Iv.kitty,Bv=Rv&&Iv.iterm2,Vv=zv||Bv,Hv=ct(),Uv=Hv===`tmux`||Hv===`screen`,Wv=e=>Uv?`Ptmux;${e.replaceAll(`\x1B`,`\x1B\x1B`)}\\`:e,Gv=(e,t)=>{let n=Buffer.from(e).toString(`base64`),r=`a=T,t=f`;return t.width&&(r+=`,c=${t.width}`),t.height&&(r+=`,r=${t.height}`),Wv(`_G${r};${n}\\`)},Kv=(e,t)=>{let n=`\x1B]1337;File=inline=1`;return t.width&&(n+=`;width=${t.width}`),t.height&&(n+=`;height=${t.height}`),n+=`;size=${e.byteLength}:${e.toString(`base64`)}`,Wv(n)},qv=(e,t={})=>{if(!Ke.existsSync(e))return null;if(zv)return Gv(e,t);if(Bv)try{return Kv(Ke.readFileSync(e),t)}catch{return null}return null},Jv=e=>e.startsWith(`file://`),Yv=e=>{let t=ie(9);if(t[0]!==`edb58922a19f7cd34125950b48961a70defca0454a8de685a54dc50281109929`){for(let e=0;e<9;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`edb58922a19f7cd34125950b48961a70defca0454a8de685a54dc50281109929`}let{path:n,label:r}=e,i,a;t[1]===n?(i=t[2],a=t[3]):(i=Jv(n)?me.fileURLToPath(n):G.resolve(n),a=Jv(n)?n:me.pathToFileURL(i).href,t[1]=n,t[2]=i,t[3]=a);let o=a,s=r??i,c;t[4]===s?c=t[5]:(c=V(O,{children:s}),t[4]=s,t[5]=c);let l;return t[6]!==o||t[7]!==c?(l=V(ut,{url:o,children:c}),t[6]=o,t[7]=c,t[8]=l):l=t[8],l},Xv=({src:e,alt:t,width:n,height:r})=>{let i=G.resolve(e),{write:a}=ne(),o=I(!1);if(!o.current){let e=qv(i,{width:n,height:r});e&&(a(e+`
38
+ `),o.current=!0)}return Vv?null:V(Yv,{path:i,label:t})},Zv=({error:e,type:t})=>{if(!e.message)return null;let n=Pt(),r=t===`defect`;return H(E,{paddingX:1,paddingY:1,marginBottom:1,backgroundColor:n.ERROR_BG,width:`100%`,flexDirection:`column`,gap:0,children:[V(E,{paddingBottom:1,children:H(O,{color:n.RED,bold:!0,children:[U.warning,` `,e.displayName??e._tag]})}),V(E,{paddingBottom:1,children:V(O,{color:n.DIM,children:e.message})}),r&&H(O,{color:n.DIM,children:[`This is a bug. Report it at`,` `,V(O,{color:n.YELLOW,children:`https://github.com/millionco/expect/issues`})]}),H(O,{color:n.DIM,children:[`Press `,V(O,{color:n.RED,children:`esc`}),` to return`]})]})},Qv=e=>{let t=ie(4);if(t[0]!==`075a231297c9d0f078b6eb696b743c17a186b30f3122dd20bf9f0b0544337fab`){for(let e=0;e<4;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`075a231297c9d0f078b6eb696b743c17a186b30f3122dd20bf9f0b0544337fab`}let{message:n}=e,r=Pt();if(!n)return null;let i;return t[1]!==r.RED||t[2]!==n?(i=V(E,{marginTop:1,children:V(O,{color:r.RED,children:n})}),t[1]=r.RED,t[2]=n,t[3]=i):i=t[3],i},$v=({verbose:e,agent:t})=>{let n=Xp.withRepoRoot(process.cwd());return m.mergeAll(Qp.layer.pipe(m.provide(n)),$p.layer,er.layer,um.layer,Ze.layer(),n,J_.layerPostHog).pipe(m.provide(Ga.layerFor(t??`claude`)),m.provide(ah),m.provide(X_),m.provideMerge(m.succeed(x.MinimumLogLevel,e?`All`:`Error`)))},ey=nt.make(_.none()),ty=nt.runtime(u.fnUntraced(function*(e){return $v({verbose:!0,agent:yield*e.some(ey)})},m.unwrap)).pipe(nt.keepAlive),ny=e=>e;var ry=class extends S.ErrorClass(`ReplayProxyStartError`)({_tag:S.tag(`ReplayProxyStartError`),cause:S.String}){message=`Failed to start replay proxy: ${this.cause}`};const iy=(e,t,n,r)=>{let i=new URL(e.url??`/`,r),a=Fe({hostname:i.hostname,port:i.port,path:i.pathname+i.search,method:`GET`,headers:{...e.headers,host:i.host}});a.on(`upgrade`,(e,r,i)=>{t.write([`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${e.headers[`sec-websocket-accept`]}`,``,``].join(`\r
39
+ `)),i.length>0&&t.write(i),n.length>0&&r.write(n),r.pipe(t),t.pipe(r),t.on(`error`,()=>r.destroy()),r.on(`error`,()=>t.destroy())}),a.on(`error`,()=>t.destroy()),a.end()},ay=u.fn(`startReplayProxy`)(function*(e){let t=new dt,n=[],r={title:``,status:`running`,steps:[]},i=!1,a=()=>{let e=r?.status;(e===`passed`||e===`failed`)&&(i=!0,r={...r,done:!0})};t.get(`/latest.json`,async t=>{if(i)return t.json(n);try{let r=await fetch(`${e.liveViewUrl}/latest.json`);if(!r.ok)return t.json(n);let i=await r.json();return Array.isArray(i)&&i.length>0&&(n=i),t.json(i)}catch{return t.json(n)}}),t.post(`/latest.json`,async e=>{try{let t=await e.req.json();return Array.isArray(t)&&(n=t),new Response(void 0,{status:204})}catch{return new Response(void 0,{status:400})}}),t.get(`/steps`,async t=>{if(i)return t.json(r);try{let n=await fetch(`${e.liveViewUrl}/steps`);return n.ok?(r=await n.json(),a(),t.json(r)):t.json(r)}catch{return t.json(r)}}),t.post(`/steps`,async t=>{try{let n=await t.req.text();r=JSON.parse(n),a();let i=await fetch(`${e.liveViewUrl}/steps`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n});return new Response(i.body,{status:i.status,headers:Object.fromEntries(i.headers.entries())})}catch{return new Response(void 0,{status:204})}});let o=/^https?:\/\//.test(e.replayHost)?e.replayHost:`http://${e.replayHost}`,s=new URL(o);t.all(`/*`,async e=>{let t=e.req.path;if(t===`/latest.json`||t===`/steps`)return e.text(`Not Found`,404);let n=new URL(t,o);n.search=new URL(e.req.url).search;try{return await ft(n.toString(),{headers:{"User-Agent":e.req.header(`user-agent`)??``,Accept:e.req.header(`accept`)??`*/*`,Host:s.host}})}catch(r){return console.error(`[replay-proxy] Failed to proxy ${t} to ${n}:`,r),e.text(`Bad Gateway: could not reach ${s.host}`,502)}}),t.onError((e,t)=>(console.error(`[replay-proxy] Unhandled error:`,e),t.text(`Internal Server Error`,500)));let c=yield*u.try({try:()=>pt({fetch:t.fetch,port:0}),catch:e=>new ry({cause:String(e)})});c.on(`upgrade`,(e,t,n)=>{iy(e,t,n,o)});let l=c.address(),d=`http://localhost:${typeof l==`object`&&l?l.port:0}`;return yield*u.logInfo(`Replay proxy started`,{proxyUrl:d,liveViewUrl:e.liveViewUrl}),{url:d,close:u.callback(e=>{c.close(()=>e(u.void))})}}),oy=e=>_.isSome(e)?Number(l.toEpochMillis(e.value)):void 0,sy=e=>e.length===0||!e.every(e=>e.status===`passed`||e.status===`failed`)?`running`:e.some(e=>e.status===`failed`)?`failed`:`passed`,cy=e=>{let t=e.events.find(e=>e._tag===`RunFinished`),n=t&&t._tag===`RunFinished`?t.status:sy(e.steps),r=t&&t._tag===`RunFinished`?t.summary:void 0,i=e.steps.map(e=>({stepId:e.id,title:e.title,status:e.status,summary:_.isSome(e.summary)?e.summary.value:void 0,startedAtMs:oy(e.startedAt),endedAtMs:oy(e.endedAt)}));return{title:e.title,status:n,summary:r,steps:i}},ly=u.fn(`pushStepState`)(function*(e,t){yield*u.tryPromise(()=>fetch(`${e}/steps`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).pipe(u.catchCause(()=>u.void))}),uy=`rrweb report:`,dy=`Playwright video:`,fy=()=>5e4+Math.floor(Math.random()*1e4),py=e=>{let t=e.slice().reverse().find(e=>e._tag===`ToolResult`&&e.toolName===`close`&&!e.isError&&e.result.length>0);if(!t||t._tag!==`ToolResult`)return{localReplayUrl:void 0,videoUrl:void 0};let n=t.result.split(`
40
+ `).map(e=>e.trim()).filter(e=>e.length>0),r=n.find(e=>e.startsWith(uy))?.replace(uy,``),i=n.find(e=>e.startsWith(dy))?.replace(dy,``);return{localReplayUrl:r&&r.trim().length>0?ge(r.trim()).href:void 0,videoUrl:i&&i.trim().length>0?ge(i.trim()).href:void 0}},my=nt.make([]),hy=u.fnUntraced(function*(e,t){let n=yield*$p,r=yield*Qp,i=yield*J_,a=yield*Xp,o=Date.now(),s=`http://localhost:${fy()}`,c;e.replayHost&&(c=`${(yield*ay({replayHost:e.replayHost,liveViewUrl:s})).url}/replay?live=true`,yield*u.logInfo(`Replay viewer available`,{replayUrl:c}),yield*u.sync(()=>e.onReplayUrl?.(c)));let l={...e.options,liveViewUrl:s};yield*i.capture(`run:started`,{plan_id:`direct`});let d=yield*r.execute(l).pipe(w.tap(t=>u.gen(function*(){e.onUpdate(t),yield*ly(s,cy(t))})),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Qn({...e.options,id:``,changesFor:e.options.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.options.instruction,baseUrl:void 0,isHeadless:e.options.isHeadless,requiresCookies:e.options.requiresCookies,testCoverage:_.none(),title:e.options.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock())),f=py(d.events);if(c){let e=c.split(`/replay`)[0];yield*u.tryPromise(()=>fetch(`${s}/latest.json`).then(async t=>{if(!t.ok)return;let n=await t.json();await fetch(`${e}/latest.json`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})})).pipe(u.catchCause(()=>u.void)),yield*ly(e,cy(d))}let p=yield*n.report(d),m=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`passed`).length,h=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`failed`).length;return yield*i.capture(`run:completed`,{plan_id:d.id??`direct`,passed:m,failed:h,step_count:d.steps.length,file_count:0,duration_ms:Date.now()-o}),p.status===`passed`&&(yield*a.saveTestedFingerprint()),{executedPlan:d,report:p,replayUrl:c??f.localReplayUrl,localReplayUrl:f.localReplayUrl,videoUrl:f.videoUrl}},u.annotateLogs({fn:`executeFn`})),gy=ty.fn()((e,t)=>ny(hy(e,t)).pipe(u.tapError(e=>u.gen(function*(){let t=yield*J_,n=e instanceof Error?e.constructor.name:`UnknownError`;yield*t.capture(`run:failed`,{plan_id:`direct`,error_tag:n})}).pipe(u.catchCause(()=>u.void))),u.provide(be.layer)));ty.fn(u.fnUntraced(function*(e,t){let n=yield*$p,r=yield*Qp,i=yield*J_,a=yield*Xp,o=Date.now(),s=`http://localhost:${fy()}`,c;e.replayHost&&(c=`${(yield*ay({replayHost:e.replayHost,liveViewUrl:s})).url}/replay?live=true`,yield*u.logInfo(`Replay viewer available`,{replayUrl:c}),yield*u.sync(()=>e.onReplayUrl?.(c)));let l={...e.options,liveViewUrl:s};yield*i.capture(`run:started`,{plan_id:`direct`});let d=yield*r.execute(l).pipe(w.tap(t=>u.gen(function*(){e.onUpdate(t),yield*ly(s,cy(t))})),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Qn({...e.options,id:``,changesFor:e.options.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.options.instruction,baseUrl:void 0,isHeadless:e.options.isHeadless,requiresCookies:e.options.requiresCookies,testCoverage:_.none(),title:e.options.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock())),f=py(d.events);if(c){let e=c.split(`/replay`)[0];yield*u.tryPromise(()=>fetch(`${s}/latest.json`).then(async t=>{if(!t.ok)return;let n=await t.json();await fetch(`${e}/latest.json`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})})).pipe(u.catchCause(()=>u.void)),yield*ly(e,cy(d))}let p=yield*n.report(d),m=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`passed`).length,h=p.steps.filter(e=>p.stepStatuses.get(e.id)?.status===`failed`).length;return yield*i.capture(`run:completed`,{plan_id:d.id??`direct`,passed:m,failed:h,step_count:d.steps.length,file_count:0,duration_ms:Date.now()-o}),p.status===`passed`&&(yield*a.saveTestedFingerprint()),{executedPlan:d,report:p,replayUrl:c??f.localReplayUrl,localReplayUrl:f.localReplayUrl,videoUrl:f.videoUrl}},u.annotateLogs({fn:`executeAtomFn`})));const _y=e=>{if(typeof e==`string`)try{let t=JSON.parse(e);if(v.isObject(t))return t}catch{return{}}return v.isObject(e)?e:{}},vy=e=>e.replace(/\s+/g,` `).trim(),yy=e=>{let t=e.match(/^mcp__.+__(.+)$/);return t?t[1]:e},by=(e,t)=>{let n=yy(e),r=typeof t==`string`?t:JSON.stringify(t??{}),i=_y(t),a=g.value(n).pipe(g.when(`open`,()=>i.url?`"${i.url}"`:``),g.when(`screenshot`,()=>{let e=i.mode??`screenshot`;return e===`screenshot`?``:e}),g.when(`playwright`,()=>Re(vy(i.code??r),100)),g.when(`console_logs`,()=>i.type?`type: "${i.type}"`:``),g.when(`network_requests`,()=>{let e=[];return i.method&&e.push(i.method),i.url&&e.push(`"${i.url}"`),e.join(`, `)}),g.when(`performance_metrics`,()=>``),g.when(`close`,()=>``),g.orElse(()=>xy(i))),o=(i.code??r).trim();return{name:n,args:a,multilineArgs:n===`playwright`&&o.includes(`
41
+ `)?o:void 0}},xy=e=>{let t=Object.values(e).filter(e=>typeof e==`string`&&e.length>0);return t.length===0?``:Re(vy(t.join(`, `)),100)},Sy=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Cy=(e,t,n=e.length)=>{let r=[];for(let i=t;i<n;i++){let t=e[i];if(t._tag===`ToolCall`&&r.push({tool:by(t.toolName,t.input),isRunning:!1,resultTokens:void 0}),t._tag===`ToolProgress`&&r.length>0){let e=r[r.length-1];r[r.length-1]={...e,resultTokens:Math.round(t.outputSize/4)}}if(t._tag===`ToolResult`&&r.length>0){let e=r[r.length-1];r[r.length-1]={...e,resultTokens:Math.round(t.result.length/4)}}}return r},wy=(e,t)=>{if(e.length===0)return e;let n=t.at(-1)?._tag===`ToolResult`,r=[...e];return r[r.length-1]={...r[r.length-1],isRunning:!n},r},Ty=(e,t=!1)=>{let n=-1;for(let t=e.length-1;t>=0;t--)if(e[t]._tag===`StepStarted`){n=t;break}if(n===-1)return[];let r=wy(Cy(e,n+1),e);return t?r:r.slice(-5)},Ey=(e,t=!1)=>{let n=wy(Cy(e,0),e);return t?n:n.slice(-5)},Dy=(e,t)=>{let n=-1,r=0;for(let i=0;i<e.length;i++)if(e[i]._tag===`StepStarted`&&(n++,n===t&&(r=i+1),n===t+1))return[r,i];return[r,e.length]},Oy=(e,t)=>{let[n,r]=Dy(e,t);return Cy(e,n,r)},ky=e=>{let t=ie(15);if(t[0]!==`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`){for(let e=0;e<15;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`}let{display:n,indent:r}=e,i=Pt(),a;t[1]!==i.TEXT||t[2]!==n.tool.name?(a=V(O,{color:i.TEXT,children:n.tool.name}),t[1]=i.TEXT,t[2]=n.tool.name,t[3]=a):a=t[3];let o;t[4]===n.isRunning?o=t[5]:(o=n.isRunning&&H(O,{children:[` `,V(Le,{type:`line`})]}),t[4]=n.isRunning,t[5]=o);let s;t[6]===n.resultTokens?s=t[7]:(s=n.resultTokens!==void 0&&` ${U.arrowDown} ${Sy(n.resultTokens)} tokens`,t[6]=n.resultTokens,t[7]=s);let c;return t[8]!==i.DIM||t[9]!==n.tool.args||t[10]!==r||t[11]!==a||t[12]!==o||t[13]!==s?(c=H(O,{color:i.DIM,wrap:`truncate`,children:[r,U.lineVertical,` `,a,`(`,n.tool.args,`)`,o,s]}),t[8]=i.DIM,t[9]=n.tool.args,t[10]=r,t[11]=a,t[12]=o,t[13]=s,t[14]=c):c=t[14],c},Ay=e=>{if(!_.isNone(e.startedAt))return(_.isSome(e.endedAt)?l.toEpochMillis(e.endedAt.value):Date.now())-l.toEpochMillis(e.startedAt.value)},jy=(e,t,n,r)=>{let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=`${n}-t${a}`;if(o.tool.multilineArgs){let e=o.tool.multilineArgs.split(`
42
+ `);i.push(H(O,{color:r.DIM,wrap:`truncate`,children:[t,U.lineVertical,` `,V(O,{color:r.TEXT,children:o.tool.name}),`(`,o.isRunning&&H(O,{children:[` `,V(Le,{type:`line`})]}),o.resultTokens!==void 0&&` ${U.arrowDown} ${Sy(o.resultTokens)} tokens`]},`${s}-h`));for(let n=0;n<e.length;n++)i.push(H(O,{color:r.DIM,children:[t,U.lineVertical,` `,` `,V(O,{color:r.TEXT,children:e[n]})]},`${s}-${n}`));i.push(H(O,{color:r.DIM,children:[t,U.lineVertical,` )`]},`${s}-c`))}else i.push(H(O,{color:r.DIM,wrap:`truncate`,children:[t,U.lineVertical,` `,V(O,{color:r.TEXT,children:o.tool.name}),`(`,o.tool.args,`)`,o.isRunning&&H(O,{children:[` `,V(Le,{type:`line`})]}),o.resultTokens!==void 0&&` ${U.arrowDown} ${Sy(o.resultTokens)} tokens`]},s))}return i},My=t=>{let n=ie(113);if(n[0]!==`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`){for(let e=0;e<113;e+=1)n[e]=Symbol.for(`react.memo_cache_sentinel`);n[0]=`1d0983dd3879f9a5a019acea17cc4fd75140d170e89f34badca2fe82be71c373`}let{changesFor:r,instruction:i,savedFlow:a,requiresCookies:o,baseUrls:s}=t,c=o===void 0?!1:o,l=Zm(Ny),u=Pt(),[,d]=jt(),f=Z_(Py),p=Z_(Fy),m=Z_(Iy),h=Z_(Ly),g;n[1]===Symbol.for(`react.memo_cache_sentinel`)?(g={mode:`promiseExit`},n[1]=g):g=n[1];let[v,y]=it(gy,g),b=ot(my),[x,S]=L(void 0),C;n[2]===v?C=n[3]:(C=tt.isWaiting(v),n[2]=v,n[3]=C);let w=C,ee;n[4]===v?ee=n[5]:(ee=tt.isSuccess(v),n[4]=v,n[5]=ee);let T=ee,k=T?v.value.report:void 0,[A,ne]=L(void 0),[re,j]=L(void 0),[M,N]=L(0),[ae,oe]=L(!1),P=Nv(Ry),F=Nv(zy),R=Nv(By),z;n[6]===M?z=n[7]:(z=Pv(M),n[6]=M,n[7]=z);let ce=z,le=A?.steps?A.steps.length:0,B;if(n[8]!==u||n[9]!==ce||n[10]!==A||n[11]!==P||n[12]!==w){if(B=[],P&&A){let e=A.steps??[];if(e.length===0&&w){let e=Ey(A.events,!0);B.push(...jy(e,` `,`planning`,u))}for(let t=0;t<e.length;t++){let n=e[t],r=_.isSome(n.summary)?n.summary.value:n.title,i=Ay(n),a=i===void 0?void 0:Pv(i),o=`${t+1}.`;if(n.status===`active`){B.push(H(E,{children:[H(O,{color:u.DIM,children:[` `,o,` `]}),V(Wm,{}),V(O,{children:` `}),V(Mv,{text:`${n.title} ${ce}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]},`step-${t}`));let e=Ty(A.events,!0);B.push(...jy(e,` `,`s${t}`,u))}else if(n.status===`passed`){B.push(H(O,{children:[H(O,{color:u.DIM,children:[` `,o]}),H(O,{color:u.GREEN,children:[` `,U.tick,` `,Re(r,100)]}),a&&H(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`));let e=Oy(A.events,t);B.push(...jy(e,` `,`s${t}`,u))}else if(n.status===`failed`){B.push(H(O,{children:[H(O,{color:u.DIM,children:[` `,o]}),H(O,{color:u.RED,children:[` `,U.cross,` `,Re(r,100)]}),a&&H(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`));let e=Oy(A.events,t);B.push(...jy(e,` `,`s${t}`,u))}else n.status===`skipped`?B.push(H(O,{children:[H(O,{color:u.DIM,children:[` `,o]}),H(O,{color:u.YELLOW,children:[` `,U.arrowRight,` `,Re(r,100)]}),a&&H(O,{color:u.DIM,children:[` `,a]})]},`step-${t}`)):B.push(H(O,{color:u.DIM,children:[` `,o,` `,U.circle,` `,n.title]},`step-${t}`))}}n[8]=u,n[9]=ce,n[10]=A,n[11]=P,n[12]=w,n[13]=B}else B=n[13];let W=Math.max(1,d-6),G;n[14]!==B.length||n[15]!==W?(G={itemCount:B.length,visibleCount:W},n[14]=B.length,n[15]=W,n[16]=G):G=n[16];let de=Km(G),fe=I(!1),pe,me;n[17]!==P||n[18]!==B.length||n[19]!==de?(pe=()=>{P&&!fe.current&&B.length>0&&de.setHighlightedIndex(B.length-1),fe.current=P},me=[P,B.length,de],n[17]=P,n[18]=B.length,n[19]=de,n[20]=pe,n[21]=me):(pe=n[20],me=n[21]),se(pe,me);let he,ge;n[22]!==f||n[23]!==s||n[24]!==p||n[25]!==r||n[26]!==i||n[27]!==m||n[28]!==c||n[29]!==a||n[30]!==y?(ge=()=>{j(Date.now());let e=s&&s.length>0?s.join(`, `):void 0,t=s?s.map(Vy).join(` `):void 0;return y({options:{changesFor:r,instruction:t?`${i} ${t}`:i,isHeadless:!p,requiresCookies:c,savedFlow:a,baseUrl:e},agentBackend:f,replayHost:m,onUpdate:ne,onReplayUrl:S}),()=>{y(nt.Interrupt)}},he=[y,f,p,r,i,a,c,s,m],n[22]=f,n[23]=s,n[24]=p,n[25]=r,n[26]=i,n[27]=m,n[28]=c,n[29]=a,n[30]=y,n[31]=he,n[32]=ge):(he=n[31],ge=n[32]),se(ge,he);let _e=T?v.value.replayUrl:void 0,K=T?v.value.localReplayUrl:void 0,ve=T?v.value.videoUrl:void 0,ye,be;n[33]!==A||n[34]!==T||n[35]!==K||n[36]!==_e||n[37]!==k||n[38]!==l||n[39]!==ve?(ye=()=>{T&&A&&k&&(Nv.getState().setExecutedPlan(A),l(Ym.Results({report:k,replayUrl:_e,localReplayUrl:K,videoUrl:ve})))},be=[T,A,k,_e,K,ve,l],n[33]=A,n[34]=T,n[35]=K,n[36]=_e,n[37]=k,n[38]=l,n[39]=ve,n[40]=ye,n[41]=be):(ye=n[40],be=n[41]),se(ye,be);let xe;n[42]===l?xe=n[43]:(xe=()=>{Nv.getState().setExecutedPlan(void 0),l(Ym.Main())},n[42]=l,n[43]=xe);let q=xe,Se,Ce;n[44]!==w||n[45]!==re?(Se=()=>{if(re===void 0||!w)return;let e=setInterval(()=>{N(Date.now()-re)},1e3);return()=>clearInterval(e)},Ce=[re,w],n[44]=w,n[45]=re,n[46]=Se,n[47]=Ce):(Se=n[46],Ce=n[47]),se(Se,Ce);let we;n[48]!==A||n[49]!==v||n[50]!==P||n[51]!==de||n[52]!==q||n[53]!==w||n[54]!==x||n[55]!==K||n[56]!==_e||n[57]!==k||n[58]!==F||n[59]!==l||n[60]!==ae||n[61]!==R||n[62]!==h||n[63]!==ve?(we=(t,n)=>{let r=t.toLowerCase();if(ae){if(n.return||r===`y`){oe(!1),$_(`run:cancelled`),q();return}(n.escape||r===`n`)&&oe(!1);return}if(r===`o`&&!n.ctrl&&!n.meta&&x){let{exec:t}=e(`node:child_process`);t(`open "${x.replace(/"/g,`\\"`)}"`),$_(`live_preview:opened`);return}if(n.ctrl&&t===`o`){R();return}if(n.ctrl&&t===`n`){h();return}if(P){if(de.handleNavigation(t,n))return;if(n.escape){F(!1);return}return}if(n.escape){if(tt.isFailure(v)){q();return}if(w){oe(!0);return}if(A&&k){Nv.getState().setExecutedPlan(A),l(Ym.Results({report:k,replayUrl:_e,localReplayUrl:K,videoUrl:ve}));return}q()}},n[48]=A,n[49]=v,n[50]=P,n[51]=de,n[52]=q,n[53]=w,n[54]=x,n[55]=K,n[56]=_e,n[57]=k,n[58]=F,n[59]=l,n[60]=ae,n[61]=R,n[62]=h,n[63]=ve,n[64]=we):we=n[64],te(we);let Te;n[65]!==B||n[66]!==de.scrollOffset||n[67]!==W?(Te=B.slice(de.scrollOffset,de.scrollOffset+W),n[65]=B,n[66]=de.scrollOffset,n[67]=W,n[68]=Te):Te=n[68];let Ee=Te,De;n[69]===b?De=n[70]:(De=V(D,{items:[...b],children:Hy}),n[69]=b,n[70]=De);let Oe;n[71]===Symbol.for(`react.memo_cache_sentinel`)?(Oe=V(nv,{}),n[71]=Oe):Oe=n[71];let ke;n[72]===u.DIM?ke=n[73]:(ke=V(O,{color:u.DIM,children:U.pointerSmall}),n[72]=u.DIM,n[73]=ke);let Ae;n[74]!==u.TEXT||n[75]!==i?(Ae=V(O,{color:u.TEXT,children:i}),n[74]=u.TEXT,n[75]=i,n[76]=Ae):Ae=n[76];let je;n[77]!==ke||n[78]!==Ae?(je=H(E,{children:[Oe,H(O,{wrap:`truncate`,children:[` `,ke,` `,Ae]})]}),n[77]=ke,n[78]=Ae,n[79]=je):je=n[79];let Me;n[80]!==u.DIM||n[81]!==u.PRIMARY||n[82]!==w||n[83]!==x?(Me=x&&w&&V(E,{marginTop:0,children:H(O,{color:u.DIM,children:[` `,`Press `,V(O,{color:u.PRIMARY,children:`o`}),` to open live preview`]})}),n[80]=u.DIM,n[81]=u.PRIMARY,n[82]=w,n[83]=x,n[84]=Me):Me=n[84];let Ne;n[85]!==u.DIM||n[86]!==u.GREEN||n[87]!==u.RED||n[88]!==u.YELLOW||n[89]!==ce||n[90]!==A||n[91]!==P||n[92]!==w||n[93]!==le||n[94]!==Ee?(Ne=P?V(E,{flexDirection:`column`,marginTop:1,children:Ee}):H(ue,{children:[le===0&&w&&(()=>{let e=A?Ey(A.events,!1):[];return H(E,{marginTop:1,flexDirection:`column`,children:[H(E,{children:[V(Wm,{}),V(O,{children:` `}),V(Mv,{text:`Starting${U.ellipsis} ${ce}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]}),e.map(Uy)]})})(),V(E,{flexDirection:`column`,marginTop:1,children:(A?.steps??[]).map((e,t)=>{let n=_.isSome(e.summary)?e.summary.value:e.title,r=Ay(e),i=r===void 0?void 0:Pv(r),a=`${t+1}.`;if(e.status===`active`){let t=A?Ty(A.events,!1):[];return H(E,{flexDirection:`column`,children:[H(E,{children:[H(O,{color:u.DIM,children:[` `,a,` `]}),V(Wm,{}),V(O,{children:` `}),V(Mv,{text:`${e.title} ${ce}`,baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight})]}),t.map(Wy)]},e.id)}return e.status===`passed`?H(O,{children:[H(O,{color:u.DIM,children:[` `,a]}),H(O,{color:u.GREEN,children:[` `,U.tick,` `,Re(n,100)]}),i&&H(O,{color:u.DIM,children:[` `,i]})]},e.id):e.status===`failed`?H(O,{children:[H(O,{color:u.DIM,children:[` `,a]}),H(O,{color:u.RED,children:[` `,U.cross,` `,Re(n,100)]}),i&&H(O,{color:u.DIM,children:[` `,i]})]},e.id):e.status===`skipped`?H(O,{children:[H(O,{color:u.DIM,children:[` `,a]}),H(O,{color:u.YELLOW,children:[` `,U.arrowRight,` `,Re(n,100)]}),i&&H(O,{color:u.DIM,children:[` `,i]})]},e.id):H(O,{color:u.DIM,children:[` `,a,` `,U.circle,` `,e.title]},e.id)})})]}),n[85]=u.DIM,n[86]=u.GREEN,n[87]=u.RED,n[88]=u.YELLOW,n[89]=ce,n[90]=A,n[91]=P,n[92]=w,n[93]=le,n[94]=Ee,n[95]=Ne):Ne=n[95];let Pe;n[96]!==u.PRIMARY||n[97]!==u.YELLOW||n[98]!==ae?(Pe=ae&&V(E,{marginTop:1,children:H(O,{color:u.YELLOW,children:[`Stop run? `,V(O,{color:u.PRIMARY,children:`enter`}),` to stop,`,` `,V(O,{color:u.PRIMARY,children:`esc`}),` to dismiss`]})}),n[96]=u.PRIMARY,n[97]=u.YELLOW,n[98]=ae,n[99]=Pe):Pe=n[99];let Fe;n[100]!==je||n[101]!==Me||n[102]!==Ne||n[103]!==Pe?(Fe=H(E,{flexDirection:`column`,width:`100%`,paddingY:1,paddingX:1,children:[je,Me,Ne,Pe]}),n[100]=je,n[101]=Me,n[102]=Ne,n[103]=Pe,n[104]=Fe):Fe=n[104];let Ie;n[105]===v?Ie=n[106]:(Ie=tt.builder(v).onError(Gy).onDefect(Ky).orNull(),n[105]=v,n[106]=Ie);let Le;n[107]!==Fe||n[108]!==Ie?(Le=H(E,{flexDirection:`column`,width:`100%`,children:[Fe,Ie]}),n[107]=Fe,n[108]=Ie,n[109]=Le):Le=n[109];let ze;return n[110]!==De||n[111]!==Le?(ze=H(ue,{children:[De,Le]}),n[110]=De,n[111]=Le,n[112]=ze):ze=n[112],ze};function Ny(e){return e.setScreen}function Py(e){return e.agentBackend}function Fy(e){return e.browserHeaded}function Iy(e){return e.replayHost}function Ly(e){return e.toggleNotifications}function Ry(e){return e.expanded}function zy(e){return e.setExpanded}function By(e){return e.toggleExpanded}function Vy(e){return`[url: ${e}]`}function Hy(e){return V(E,{paddingX:1,children:V(Xv,{src:e,alt:e})},e)}function Uy(e,t){return V(ky,{display:e,indent:` `},t)}function Wy(e,t){return V(ky,{display:e,indent:` `},t)}function Gy(e){return V(Zv,{type:`error`,error:e})}function Ky(e){return V(Zv,{type:`defect`,error:{_tag:`Defect`,message:s.pretty(s.fail(e))}})}const qy=e=>{try{return R.execSync(`pbcopy`,{input:e,stdio:[`pipe`,`ignore`,`ignore`]}),!0}catch{return!1}},Jy=(e,t)=>u.runPromise(pm.use(n=>n.addComment(process.cwd(),e,t)).pipe(u.provide(pm.layer))),Yy=()=>M({mutationFn:({pullRequest:e,body:t})=>Jy(e,t)}),Xy=ty.fn(u.fnUntraced(function*(e,t){return yield*(yield*um).save(e.plan)},u.annotateLogs({fn:`saveFlowFn`}),u.provide(be.layer))),Zy=e=>{if(!(_.isNone(e.startedAt)||_.isNone(e.endedAt)))return l.toEpochMillis(e.endedAt.value)-l.toEpochMillis(e.startedAt.value)},Qy=e=>{let t=0;for(let n of e){let e=Zy(n);e!==void 0&&(t+=e)}return t},$y=e=>{let t=ie(141);if(t[0]!==`b7e547f8ebc01ced52659efc05613f9ccf6a352b61760b052762a2223144f2e9`){for(let e=0;e<141;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`b7e547f8ebc01ced52659efc05613f9ccf6a352b61760b052762a2223144f2e9`}let{report:n,replayUrl:r,localReplayUrl:i,videoUrl:a}=e,o=Pt(),s=Zm(eb),[c,l]=L(void 0),u=Yy(),d;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(d={mode:`promiseExit`},t[1]=d):d=t[1];let[f,p]=it(Xy,d),m=f.waiting,h;t[2]===f?h=t[3]:(h=tt.isSuccess(f),t[2]=f,t[3]=h);let g=h,v;t[4]!==u||t[5]!==n.pullRequest||t[6]!==n.toPlainText?(v=()=>{_.isSome(n.pullRequest)&&($_(`results:posted_to_pr`),u.mutate({pullRequest:n.pullRequest.value,body:n.toPlainText}))},t[4]=u,t[5]=n.pullRequest,t[6]=n.toPlainText,t[7]=v):v=t[7];let y=v,b;t[8]!==o.GREEN||t[9]!==o.RED||t[10]!==n.toPlainText?(b=()=>{qy(n.toPlainText)?($_(`results:copied_to_clipboard`),l({text:`${U.tick} Copied to clipboard`,color:o.GREEN})):l({text:`${U.cross} Failed to copy to clipboard`,color:o.RED})},t[8]=o.GREEN,t[9]=o.RED,t[10]=n.toPlainText,t[11]=b):b=t[11];let x=b,S;t[12]!==n||t[13]!==m||t[14]!==g||t[15]!==p?(S=async()=>{m||g||($_(`flow:saved`,{step_count:n.steps.length}),await p({plan:n}))},t[12]=n,t[13]=m,t[14]=g,t[15]=p,t[16]=S):S=t[16];let C=S,w;t[17]!==n.changesFor||t[18]!==n.instruction||t[19]!==s?(w=()=>{$_(`results:restarted`),Nv.getState().setExecutedPlan(void 0),s(Xm({changesFor:n.changesFor,instruction:n.instruction}))},t[17]=n.changesFor,t[18]=n.instruction,t[19]=s,t[20]=w):w=t[20];let ee=w,T;t[21]!==x||t[22]!==y||t[23]!==ee||t[24]!==C?(T=e=>{let t=e.toLowerCase();t===`y`&&x(),t===`p`&&y(),t===`s`&&C(),t===`r`&&ee()},t[21]=x,t[22]=y,t[23]=ee,t[24]=C,t[25]=T):T=t[25],te(T);let D=n.status===`passed`,k=D?o.GREEN:o.RED,A=D?U.tick:U.cross,ne=D?`Passed`:`Failed`,re,j,M,N,ae,oe,P,se,F,I,R;if(t[26]!==o.DIM||t[27]!==o.GREEN||t[28]!==o.RED||t[29]!==o.TEXT||t[30]!==o.YELLOW||t[31]!==i||t[32]!==r||t[33]!==n.instruction||t[34]!==n.stepStatuses||t[35]!==n.steps||t[36]!==k||t[37]!==A||t[38]!==ne){let e=Qy(n.steps);j=r??i,M=!!r&&!!i&&r!==i&&i!==void 0,re=E,I=`column`,R=`100%`,N=1,ae=1;let a;t[50]===Symbol.for(`react.memo_cache_sentinel`)?(a=V(nv,{}),t[50]=a):a=t[50];let s;t[51]===o.DIM?s=t[52]:(s=V(O,{color:o.DIM,children:U.pointerSmall}),t[51]=o.DIM,t[52]=s);let c;t[53]!==o.TEXT||t[54]!==n.instruction?(c=V(O,{color:o.TEXT,children:n.instruction}),t[53]=o.TEXT,t[54]=n.instruction,t[55]=c):c=t[55],t[56]!==s||t[57]!==c?(oe=H(E,{children:[a,H(O,{wrap:`truncate`,children:[` `,s,` `,c]})]}),t[56]=s,t[57]=c,t[58]=oe):oe=t[58];let l;t[59]!==k||t[60]!==A||t[61]!==ne?(l=H(O,{color:k,bold:!0,children:[A,` `,ne]}),t[59]=k,t[60]=A,t[61]=ne,t[62]=l):l=t[62];let u=n.steps.length===1?``:`s`,d;t[63]!==o.DIM||t[64]!==n.steps.length||t[65]!==u?(d=H(O,{color:o.DIM,children:[` `,n.steps.length,` step`,u]}),t[63]=o.DIM,t[64]=n.steps.length,t[65]=u,t[66]=d):d=t[66],t[67]!==l||t[68]!==d?(P=H(E,{marginTop:1,children:[l,d]}),t[67]=l,t[68]=d,t[69]=P):P=t[69];let f;if(t[70]!==o.DIM||t[71]!==o.GREEN||t[72]!==o.RED||t[73]!==o.YELLOW||t[74]!==n.stepStatuses||t[75]!==n.steps){let e;t[77]!==o.DIM||t[78]!==o.GREEN||t[79]!==o.RED||t[80]!==o.YELLOW||t[81]!==n.stepStatuses?(e=(e,t)=>{let r=Zy(e),i=r===void 0?void 0:Pv(r),a=n.stepStatuses.get(e.id),s=a?.status===`failed`,c=a?.status===`skipped`,l=s?o.RED:c?o.YELLOW:o.GREEN,u=s?U.cross:c?U.arrowRight:U.tick,d=`${t+1}.`;return H(E,{flexDirection:`column`,children:[H(O,{children:[H(O,{color:o.DIM,children:[` `,d]}),H(O,{color:l,children:[` `,u,` `,e.title]}),i&&H(O,{color:o.DIM,children:[` `,i]})]}),(s||c)&&a?.summary&&H(O,{color:o.DIM,children:[` `,a.summary]})]},e.id)},t[77]=o.DIM,t[78]=o.GREEN,t[79]=o.RED,t[80]=o.YELLOW,t[81]=n.stepStatuses,t[82]=e):e=t[82],f=n.steps.map(e),t[70]=o.DIM,t[71]=o.GREEN,t[72]=o.RED,t[73]=o.YELLOW,t[74]=n.stepStatuses,t[75]=n.steps,t[76]=f}else f=t[76];t[83]===f?se=t[84]:(se=V(E,{flexDirection:`column`,marginTop:1,children:f}),t[83]=f,t[84]=se),F=e>0&&V(E,{marginTop:1,children:H(O,{color:o.DIM,children:[`Worked for `,Pv(e)]})}),t[26]=o.DIM,t[27]=o.GREEN,t[28]=o.RED,t[29]=o.TEXT,t[30]=o.YELLOW,t[31]=i,t[32]=r,t[33]=n.instruction,t[34]=n.stepStatuses,t[35]=n.steps,t[36]=k,t[37]=A,t[38]=ne,t[39]=re,t[40]=j,t[41]=M,t[42]=N,t[43]=ae,t[44]=oe,t[45]=P,t[46]=se,t[47]=F,t[48]=I,t[49]=R}else re=t[39],j=t[40],M=t[41],N=t[42],ae=t[43],oe=t[44],P=t[45],se=t[46],F=t[47],I=t[48],R=t[49];let z;t[85]===c?z=t[86]:(z=c&&V(E,{marginTop:1,children:V(O,{color:c.color,children:c.text})}),t[85]=c,t[86]=z);let ce;t[87]!==o.DIM||t[88]!==u.isPending?(ce=u.isPending&&V(E,{marginTop:1,children:H(O,{color:o.DIM,children:[`Posting to PR`,U.ellipsis]})}),t[87]=o.DIM,t[88]=u.isPending,t[89]=ce):ce=t[89];let le;t[90]!==o.GREEN||t[91]!==u.isSuccess?(le=u.isSuccess&&V(E,{marginTop:1,children:H(O,{color:o.GREEN,children:[U.tick,` Posted to PR`]})}),t[90]=o.GREEN,t[91]=u.isSuccess,t[92]=le):le=t[92];let B;t[93]!==o.RED||t[94]!==u.isError?(B=u.isError&&V(E,{marginTop:1,children:H(O,{color:o.RED,children:[U.cross,` Failed to post to PR`]})}),t[93]=o.RED,t[94]=u.isError,t[95]=B):B=t[95];let ue;t[96]!==o.DIM||t[97]!==m?(ue=m&&V(E,{marginTop:1,children:H(O,{color:o.DIM,children:[`Saving flow`,U.ellipsis]})}),t[96]=o.DIM,t[97]=m,t[98]=ue):ue=t[98];let W;t[99]!==o.GREEN||t[100]!==g?(W=g&&V(E,{marginTop:1,children:H(O,{color:o.GREEN,children:[U.tick,` Flow saved`]})}),t[99]=o.GREEN,t[100]=g,t[101]=W):W=t[101];let G;t[102]!==o.RED||t[103]!==f?(G=tt.isFailure(f)&&V(E,{marginTop:1,children:H(O,{color:o.RED,children:[U.cross,` Failed to save flow`]})}),t[102]=o.RED,t[103]=f,t[104]=G):G=t[104];let de;t[105]!==o.DIM||t[106]!==o.PRIMARY||t[107]!==j?(de=j&&V(E,{flexDirection:`column`,paddingX:1,marginTop:1,children:H(O,{color:o.DIM,children:[`Replay:`,` `,V(O,{color:o.PRIMARY,bold:!0,children:j})]})}),t[105]=o.DIM,t[106]=o.PRIMARY,t[107]=j,t[108]=de):de=t[108];let fe;t[109]!==o.DIM||t[110]!==o.PRIMARY||t[111]!==i||t[112]!==M?(fe=M&&V(E,{flexDirection:`column`,paddingX:1,children:H(O,{color:o.DIM,children:[`Local Replay:`,` `,V(O,{color:o.PRIMARY,bold:!0,children:i})]})}),t[109]=o.DIM,t[110]=o.PRIMARY,t[111]=i,t[112]=M,t[113]=fe):fe=t[113];let pe;t[114]!==o.DIM||t[115]!==o.PRIMARY||t[116]!==a?(pe=a&&V(E,{flexDirection:`column`,paddingX:1,children:H(O,{color:o.DIM,children:[`Video:`,` `,V(O,{color:o.PRIMARY,bold:!0,children:a})]})}),t[114]=o.DIM,t[115]=o.PRIMARY,t[116]=a,t[117]=pe):pe=t[117];let me;t[118]===n.screenshotPaths?me=t[119]:(me=n.screenshotPaths.map(tb),t[118]=n.screenshotPaths,t[119]=me);let he;return t[120]!==re||t[121]!==N||t[122]!==ae||t[123]!==oe||t[124]!==P||t[125]!==se||t[126]!==F||t[127]!==z||t[128]!==ce||t[129]!==le||t[130]!==B||t[131]!==ue||t[132]!==W||t[133]!==G||t[134]!==de||t[135]!==fe||t[136]!==pe||t[137]!==me||t[138]!==I||t[139]!==R?(he=H(re,{flexDirection:I,width:R,paddingY:N,paddingX:ae,children:[oe,P,se,F,z,ce,le,B,ue,W,G,de,fe,pe,me]}),t[120]=re,t[121]=N,t[122]=ae,t[123]=oe,t[124]=P,t[125]=se,t[126]=F,t[127]=z,t[128]=ce,t[129]=le,t[130]=B,t[131]=ue,t[132]=W,t[133]=G,t[134]=de,t[135]=fe,t[136]=pe,t[137]=me,t[138]=I,t[139]=R,t[140]=he):he=t[140],he};function eb(e){return e.setScreen}function tb(e){return V(E,{marginTop:1,children:V(Xv,{src:e,alt:`Screenshot: ${e}`})},e)}const nb=m.mergeAll(um.layer,Xp.withRepoRoot(process.cwd())),rb=()=>N({queryKey:[`saved-flows`],queryFn:()=>u.gen(function*(){return yield*(yield*um).list()}).pipe(u.provide(nb),u.provide(be.layer),u.catchTag(`FindRepoRootError`,()=>u.succeed([])),u.runPromise)}),ib=new pn({isGitRepo:!1,currentBranch:`HEAD`,mainBranch:void 0,isOnMain:!1,hasChangesFromMain:!1,hasUnstagedChanges:!1,hasBranchCommits:!1,branchCommitCount:0,fileStats:[],workingTreeFileStats:[],fingerprint:void 0,savedFingerprint:void 0}),ab=()=>N({queryKey:[`git-state`],queryFn:async()=>{let e=await u.runPromiseExit(u.gen(function*(){return yield*(yield*Xp).getState()}).pipe(u.provide(Xp.withRepoRoot(process.cwd())),u.catchTag(`FindRepoRootError`,()=>u.succeed(ib)),u.timeoutOrElse({duration:1e4,onTimeout:()=>u.succeed(ib)}),u.provide(be.layer)));return d.isSuccess(e)?e.value:ib}}),ob=e=>Array.isArray(e.flow?.steps)?e.flow.steps:[],sb=(e,t)=>{let n=gn.makeUnsafe({_tag:`Changes`,mainBranch:t}),r=ob(e),i={title:e.flow.title,userInstruction:e.flow.userInstruction,steps:r},a=e.environment.cookies;$_(`flow:reused`,{slug:e.slug,step_count:r.length}),Zm.getState().setScreen(Xm({changesFor:n,instruction:e.flow.userInstruction,savedFlow:i,requiresCookies:a}))},cb=()=>{let e=ie(11);if(e[0]!==`53939b05c229418d7d52eba403172d78da52d4f06481f5625a9cf002fc443ae8`){for(let t=0;t<11;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`53939b05c229418d7d52eba403172d78da52d4f06481f5625a9cf002fc443ae8`}let t=Pt(),[n]=jt(),r=Zm(lb),{data:i}=ab(),{data:a,isLoading:o}=rb(),s=a===void 0?[]:a,{highlightedIndex:c,setHighlightedIndex:l,scrollOffset:u,handleNavigation:d}=Km({itemCount:s.length,visibleCount:15}),f=Math.min(40,Math.floor(n*.35)),p=Math.max(20,n-f-8),m=s.slice(u,u+15);te((e,t)=>{if(!d(e,t)){if(t.return){let e=s[c];e&&sb(e,i?.mainBranch??`main`)}t.escape&&r(Ym.Main())}});let h=E,g=`${s.length} flow${s.length===1?``:`s`}`,_;e[1]===g?_=e[2]:(_=V(E,{paddingX:1,children:V($m,{title:`Saved flows`,subtitle:g})}),e[1]=g,e[2]=_);let v;e[3]===o?v=e[4]:(v=o&&V(E,{marginTop:1,paddingX:1,children:V(Wm,{message:`Loading saved flows...`})}),e[3]=o,e[4]=v);let y=!o&&s.length===0&&V(E,{marginTop:1,paddingX:1,flexDirection:`column`,children:H(O,{color:t.DIM,children:[`No saved flows yet. Run a test and press `,V(O,{color:t.PRIMARY,children:`s`}),` on the results screen to save a flow.`]})}),b=!o&&s.length>0&&V(E,{marginTop:1,flexDirection:`column`,height:15,overflow:`hidden`,paddingX:1,children:m.map((e,n)=>{let r=n+u,a=r===c,o=ob(e).length;return H(Lt,{onClick:()=>{l(r),sb(e,i?.mainBranch??`main`)},children:[V(O,{color:a?t.PRIMARY:t.DIM,children:a?`${U.pointer} `:` `}),V(O,{color:a?t.PRIMARY:t.TEXT,bold:a,children:Gm(Re(e.title,f-1),f)}),V(O,{color:t.DIM,children:Gm(`${o} step${o===1?``:`s`}`,10)}),V(O,{color:t.DIM,children:Re(e.description,p)})]},e.slug)})}),x;return e[5]!==h||e[6]!==_||e[7]!==v||e[8]!==y||e[9]!==b?(x=H(h,{flexDirection:`column`,width:`100%`,paddingY:1,children:[_,v,y,b]}),e[5]=h,e[6]=_,e[7]=v,e[8]=y,e[9]=b,e[10]=x):x=e[10],x};function lb(e){return e.setScreen}const ub=e=>{let t=ie(7);if(t[0]!==`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`){for(let e=0;e<7;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`}let{status:n}=e,r=Pt();if(n===`open`){let e;return t[1]===r.GREEN?e=t[2]:(e=H(O,{color:r.GREEN,children:[U.bullet,` `]}),t[1]=r.GREEN,t[2]=e),e}if(n===`merged`){let e;return t[3]===r.PURPLE?e=t[4]:(e=H(O,{color:r.PURPLE,children:[U.bullet,` `]}),t[3]=r.PURPLE,t[4]=e),e}if(n===`draft`){let e;return t[5]===r.DIM?e=t[6]:(e=H(O,{color:r.DIM,children:[U.bullet,` `]}),t[5]=r.DIM,t[6]=e),e}return null},db=e=>{let t=ie(30);if(t[0]!==`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`){for(let e=0;e<30;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`4fad32b1608f5dc4d90407ad58143bc83cfcba6f2b87af31eb3b6ad187111fee`}let{options:n,selectedIndex:r,isLoading:i,gitState:a}=e,o=Pt(),s;bb0:{if(n.length<=8){s=0;break bb0}let e=n.length-8;s=Math.min(e,Math.max(0,r-4))}let c=s,l,u,d,f;if(t[1]!==o||t[2]!==a||t[3]!==i||t[4]!==n||t[5]!==c||t[6]!==r){f=Symbol.for(`react.early_return_sentinel`);bb1:{let e=n.slice(c,c+8);if(n.length===0&&!i){let e;t[11]===o.DIM?e=t[12]:(e=V(E,{flexDirection:`column`,children:V(O,{color:o.DIM,children:`No matching results`})}),t[11]=o.DIM,t[12]=e),f=e;break bb1}l=E,u=`column`;let s;t[13]!==o||t[14]!==a||t[15]!==c||t[16]!==r?(s=(e,t)=>{let n=t+c===r,i=zm(e,a),s=Bm(e,a),l=e._tag===`PullRequest`||e._tag===`Branch`?e.branch.prNumber:null,u=e._tag===`PullRequest`||e._tag===`Branch`?e.branch.prStatus:null;return H(O,{wrap:`truncate`,children:[V(O,{color:n?o.PRIMARY:o.DIM,children:n?`${U.pointer} `:` `}),e._tag===`WorkingTree`?H(O,{color:o.GREEN,children:[U.bullet,` `]}):null,u?V(ub,{status:u}):null,V(O,{color:n?o.PRIMARY:o.TEXT,bold:n,children:i}),l?H(O,{children:[` `,H(O,{color:u===`open`?o.GREEN:u===`merged`?o.PURPLE:o.DIM,children:[`#`,l]}),u?H(O,{color:o.DIM,children:[` `,u]}):null]}):null,s&&!l?H(O,{color:o.DIM,children:[` `,s]}):null]},qn(e))},t[13]=o,t[14]=a,t[15]=c,t[16]=r,t[17]=s):s=t[17],d=e.map(s)}t[1]=o,t[2]=a,t[3]=i,t[4]=n,t[5]=c,t[6]=r,t[7]=l,t[8]=u,t[9]=d,t[10]=f}else l=t[7],u=t[8],d=t[9],f=t[10];if(f!==Symbol.for(`react.early_return_sentinel`))return f;let p;t[18]!==o||t[19]!==i?(p=i?V(E,{children:H(O,{color:o.DIM,children:[` Loading PRs and branches`,U.ellipsis]})}):null,t[18]=o,t[19]=i,t[20]=p):p=t[20];let m;t[21]!==o||t[22]!==n.length?(m=n.length>8?V(E,{children:H(O,{color:o.DIM,children:[` `,n.length-8,` more `,U.arrowUp,`/`,U.arrowDown]})}):null,t[21]=o,t[22]=n.length,t[23]=m):m=t[23];let h;return t[24]!==l||t[25]!==u||t[26]!==d||t[27]!==p||t[28]!==m?(h=H(l,{flexDirection:u,children:[d,p,m]}),t[24]=l,t[25]=u,t[26]=d,t[27]=p,t[28]=m,t[29]=h):h=t[29],h},fb=({gitState:e,onSelect:t})=>{let[n,r]=L(!1),[i,a]=L(``),[o,s]=L(0),{data:c=[]}=N({queryKey:[`local-context-options`,e?.currentBranch],queryFn:()=>Im(e),enabled:!!e}),{data:l=[],isLoading:u}=N({queryKey:[`remote-context-options`,e?.currentBranch],queryFn:()=>Rm(e),enabled:n&&!!e}),d=F(()=>[...c,...l],[c,l]),f=F(()=>Hm(d,i,e),[d,i,e]);se(()=>{s(0)},[i]);let p=oe(()=>{r(!0),a(``),s(0)},[]),m=oe(()=>{r(!1),a(``)},[]);return{pickerOpen:n,pickerQuery:i,pickerIndex:o,filteredOptions:f,localOptions:c,remoteLoading:u,openPicker:p,closePicker:m,handleContextSelect:oe(e=>{t(e),m()},[t,m]),setPickerQuery:a,setPickerIndex:s,createInputChangeHandler:(e,t)=>r=>{let i=Ot(r),o=e.current;if(i.length>o.length&&i[i.length-1]===`@`&&(o.length===0||i[i.length-2]===` `)){t(i.slice(0,-1)),p();return}if(n){i.length-o.length<0?(m(),t(i)):a(e=>{let n=i.slice(o.length);return n.includes(` `)?(m(),t(i),``):e+n});return}t(i)}}},pb=e=>{let t=new Set;return e.filter(e=>t.has(e.path)?!1:(t.add(e.path),!0))},mb=e=>N({queryKey:[`test-coverage`,e?.fingerprint],queryFn:async()=>{if(!e?.isGitRepo||!e.hasChangesFromMain&&!e.hasUnstagedChanges)return;let t=e.mainBranch??`main`,n=await u.runPromiseExit(u.gen(function*(){let e=yield*Xp,n=yield*Pm,r=yield*e.getChangedFiles(gn.makeUnsafe({_tag:`WorkingTree`})),i=yield*e.getChangedFiles(gn.makeUnsafe({_tag:`Changes`,mainBranch:t})),a=pb([...r,...i]);if(a.length!==0)return yield*n.analyze(a)}).pipe(u.provide(Xp.withRepoRoot(process.cwd())),u.provide(Pm.layer),u.timeoutOrElse({duration:15e3,onTimeout:()=>u.succeed(void 0)}),u.provide(be.layer)));if(d.isSuccess(n))return n.value},enabled:!!(e?.isGitRepo&&(e.hasChangesFromMain||e.hasUnstagedChanges)),staleTime:3e4}),hb=[`Test the main user flow end to end`,`Smoke test the homepage and key pages`,`Check authentication and protected routes`],gb=[`Verify my recent changes work as expected`,`Check for regressions in related features`,`Test the main user flow end to end`],_b=[`Test the changes on this branch`,`Smoke test this branch end to end`,`Check for regressions on this branch`],vb=[`Test the changes in this pull request`,`Check for regressions introduced by this PR`,`Verify the PR works end to end`],yb=[`Test the changes from this commit`,`Check if this commit introduces regressions`,`Verify this commit works as expected`],bb=(e,t)=>{if(!e)return hb;switch(e._tag){case`WorkingTree`:return gb;case`Branch`:return _b;case`PullRequest`:return vb;case`Commit`:return yb;default:return hb}},xb=e=>e>=70?Nt.GREEN:e>=40?Nt.YELLOW:Nt.RED,Sb=e=>e>=70?`#0a2b0a`:e>=40?`#332b00`:`#331510`,Cb=e=>`Use Expect to test your changes.`,wb=e=>{let t=Math.round(e/100*10),n=10-t;return{filled:`█`.repeat(t),empty:`░`.repeat(n)}},Tb=({gitState:e})=>{let t=Pt(),[n]=jt(),r=Z_(e=>e.instructionHistory),i=Zm(e=>e.setScreen),[a,o]=L(void 0),[s,c]=L(``),[l,u]=L(0),[d,f]=L(0),[p,m]=L(!1),[h,g]=L(void 0),[_,v]=L(-1),[y,b]=L(``),x=cv(e=>e.cookiesEnabled),S=cv(e=>e.toggleCookies),{data:C}=mb(e),w=()=>{if(r.length===0)return;let e=_+1;e>=r.length||(_===-1&&b(s),v(e),c(r[e]),u(e=>e+1))},ee=()=>{if(_<=-1)return;let e=_-1;v(e),c(e===-1?y:r[e]),u(e=>e+1)},T=fb({gitState:e??null,onSelect:e=>{o(e),$_(`context:selected`,{context_type:{WorkingTree:`working_tree`,Branch:`branch`,PullRequest:`pull_request`,Commit:`commit`}[e._tag]})}}),D=T.localOptions.find(e=>e._tag===`WorkingTree`)??void 0,k=a??D??null,A=bb(k,e??null);se(()=>{f(0)},[k,e]);let ne=t=>{let n=(t??s).trim();if(!n){g(`Describe what you want the browser agent to test.`);return}if(!e)return;let r=e.mainBranch??`main`,a;k?._tag===`Commit`?a=gn.makeUnsafe({_tag:`Commit`,hash:k.hash}):k?._tag===`Branch`||k?._tag===`PullRequest`?(k.branch.name&&(dm(process.cwd(),k.branch.name),Qm.invalidateQueries({queryKey:[`git-state`]})),a=gn.makeUnsafe({_tag:`Branch`,mainBranch:r})):a=gn.makeUnsafe({_tag:`Changes`,mainBranch:r}),Z_.getState().rememberInstruction(n),x||Jm(n)?i(Xm({changesFor:a,instruction:n,requiresCookies:x})):i(Ym.CookieSyncConfirm({changesFor:a,instruction:n}))},re=I(s);re.current=s;let j=T.createInputChangeHandler(re,e=>{c(e),h&&g(void 0)}),M=!s.includes(`
43
+ `),N=s===``&&!T.pickerOpen&&A.length>0,ie=N&&!p&&n>=80,ae=A[d%A.length];return te((e,t)=>{if(T.pickerOpen){if(t.escape){T.closePicker();return}if(t.downArrow||t.ctrl&&e===`n`){T.setPickerIndex(Math.min(T.filteredOptions.length-1,T.pickerIndex+1));return}if(t.upArrow||t.ctrl&&e===`p`){T.setPickerIndex(Math.max(0,T.pickerIndex-1));return}if(t.return||t.tab){let e=T.filteredOptions[T.pickerIndex];e&&T.handleContextSelect(e);return}if(t.backspace||t.delete){T.pickerQuery.length===0?T.closePicker():T.setPickerQuery(T.pickerQuery.slice(0,-1));return}e&&!t.ctrl&&!t.meta&&T.setPickerQuery(T.pickerQuery+e);return}if(M&&t.upArrow){w();return}if(M&&t.downArrow){ee();return}if(t.ctrl&&e===`k`){S(),$_(`cookies:toggled`,{enabled:!x});return}if(t.tab&&!t.shift&&N&&ae){c(ae),u(e=>e+1),$_(`suggestion:accepted`);return}if(!(t.tab&&t.shift)&&N){if(t.rightArrow){f(e=>(e+1)%A.length),m(!0);return}if(t.leftArrow){f(e=>(e-1+A.length)%A.length),m(!0);return}}},{isActive:!0}),H(E,{flexDirection:`column`,width:`100%`,paddingY:1,children:[V(E,{flexDirection:`column`,marginBottom:1,paddingX:1,children:V(nv,{})}),(e?.hasUntestedChanges||C&&C.totalCount>0)&&!(C&&C.totalCount>0&&C.percent>=90)&&H(E,{paddingX:1,paddingY:1,marginBottom:1,backgroundColor:C&&C.totalCount>0?Sb(C.percent):t.BANNER_BG,width:`100%`,flexDirection:`column`,gap:0,children:[(()=>{if(C&&C.totalCount>0)return H(E,{children:[H(O,{color:xb(C.percent),bold:!0,children:[U.warning,` Untested changes`]}),V(O,{children:` `}),V(O,{color:xb(C.percent),children:wb(C.percent).filled}),V(O,{color:t.DIM,children:wb(C.percent).empty}),H(O,{color:xb(C.percent),children:[` `,C.percent,`% test coverage`]})]});if(!e)return null;let n=e.workingTreeFileStats,r=n.reduce((e,t)=>e+t.added,0),i=n.reduce((e,t)=>e+t.removed,0);return H(E,{children:[H(O,{color:t.YELLOW,bold:!0,children:[U.warning,` Untested changes detected`]}),n.length>0&&H(ue,{children:[H(O,{color:t.DIM,children:[` `,n.length,` file`,n.length===1?``:`s`,` `]}),r>0&&H(O,{color:t.GREEN,children:[`+`,r]}),r>0&&i>0&&V(O,{color:t.DIM,children:` `}),i>0&&H(O,{color:t.RED,children:[`-`,i]})]})]})})(),V(O,{color:t.DIM,children:C&&C.totalCount>0?Cb(C.percent):`Describe what to test and hit enter to verify your changes.`})]}),H(E,{flexDirection:`column`,width:`100%`,children:[H(E,{paddingX:1,children:[!e&&V(Wm,{message:`loading context`}),e&&e.isGitRepo&&k&&V(Lt,{fullWidth:!1,onClick:()=>{T.pickerOpen?T.closePicker():T.openPicker()},children:H(O,{color:t.DIM,children:[U.bullet,` `,H(O,{color:t.PRIMARY,children:[`@`,Vm(k,e)]}),Bm(k,e)&&` (${Bm(k,e)})`]})})]}),V(Lt,{children:V(E,{flexDirection:`column`,marginTop:1,backgroundColor:t.INPUT_BG,width:`100%`,paddingX:1,paddingY:1,children:H(E,{children:[V(O,{color:t.PRIMARY,children:`❯ `}),V(E,{flexGrow:1,children:V(Ut,{focus:!T.pickerOpen,multiline:!0,placeholder:ae?`${ae} [tab]`:``,value:s,onSubmit:ne,onUpArrowAtTop:M?void 0:w,onDownArrowAtBottom:M?void 0:ee,onChange:j},l)}),ie?V(O,{color:t.DIM,children:` ←→ cycle test suggestions`}):null]})})}),e?.isGitRepo&&T.pickerOpen&&H(Ft,{color:t.BORDER,children:[H(E,{marginBottom:0,children:[V(O,{color:t.DIM,children:`@ `}),V(O,{color:t.PRIMARY,children:T.pickerQuery}),V(O,{color:t.DIM,children:T.pickerQuery?``:`type to filter`})]}),V(db,{options:T.filteredOptions,selectedIndex:T.pickerIndex,isLoading:T.remoteLoading,gitState:e})]}),e?.isGitRepo&&!T.pickerOpen&&V(E,{marginTop:1,paddingX:1,children:H(O,{color:t.DIM,children:[V(O,{color:t.PRIMARY,children:`@`}),` add context`]})})]}),V(Qv,{message:h})]})},Eb=e=>{let t=ie(10);if(t[0]!==`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`){for(let e=0;e<10;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`}let{segment:n,mutedColor:r}=e,i=n.color??r,a;t[1]!==n.label||t[2]!==i?(a=H(O,{color:i,children:[n.label,` `]}),t[1]=n.label,t[2]=i,t[3]=a):a=t[3];let o=n.color??r,s;t[4]!==n.key||t[5]!==o?(s=H(O,{color:o,children:[`[`,n.key,`]`]}),t[4]=n.key,t[5]=o,t[6]=s):s=t[6];let c;return t[7]!==a||t[8]!==s?(c=H(ue,{children:[a,s]}),t[7]=a,t[8]=s,t[9]=c):c=t[9],c},Db=e=>{let t=ie(12);if(t[0]!==`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`){for(let e=0;e<12;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e8c3ad7624de558f1292f5717cd6dbce82fb6c0767dc4ab19348dc7a7975d8f5`}let{segments:n,color:r,mutedColor:i}=e,a;t[1]===r?a=t[2]:(a=V(O,{color:r,children:` `}),t[1]=r,t[2]=a);let o;if(t[3]!==i||t[4]!==n){let e;t[6]!==i||t[7]!==n.length?(e=(e,t)=>H(E,{children:[e.onClick?V(Lt,{fullWidth:!1,onClick:e.onClick,children:V(Eb,{segment:e,mutedColor:i})}):V(Eb,{segment:e,mutedColor:i}),t<n.length-1&&V(O,{color:i,children:` `})]},e.key+e.label),t[6]=i,t[7]=n.length,t[8]=e):e=t[8],o=n.map(e),t[3]=i,t[4]=n,t[5]=o}else o=t[5];let s;return t[9]!==a||t[10]!==o?(s=H(E,{children:[a,o]}),t[9]=a,t[10]=o,t[11]=s):s=t[11],s},Ob=S.Struct({version:S.String}),kb=(e,t)=>{let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1},Ab=u.gen(function*(){let e=yield*u.tryPromise({try:()=>fetch(`https://registry.npmjs.org/${bt}/latest`).then(e=>e.json()),catch:e=>Error(`npm registry fetch failed: ${e}`)});return(yield*u.try({try:()=>S.decodeUnknownSync(Ob)(e),catch:e=>Error(`npm response decode failed: ${e}`)})).version}).pipe(u.timeoutOrElse({duration:5e3,onTimeout:()=>u.succeed(void 0)})),jb=()=>{let{data:e}=N({queryKey:[`update-check`],queryFn:async()=>{let e=await u.runPromiseExit(Ab);if(d.isSuccess(e))return e.value},staleTime:36e5,retry:!1,refetchOnWindowFocus:!1});return{latestVersion:e,updateAvailable:e!==void 0&&kb(e,`0.0.12`)}},Mb=(e,t)=>{let n=ie(87);if(n[0]!==`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`){for(let e=0;e<87;e+=1)n[e]=Symbol.for(`react.memo_cache_sentinel`);n[0]=`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`}let r=Pt(),i=Zm(Fb),a=cv(Ib),o=cv(Lb),s=Z_(Rb),c=Z_(zb),l=Nv(Bb);switch(e._tag){case`Main`:{let e=a?`cookies on`:`cookies off`,r;n[1]!==e||n[2]!==o?(r={key:`ctrl+k`,label:e,cta:!0,onClick:o},n[1]=e,n[2]=o,n[3]=r):r=n[3];let s;n[4]===i?s=n[5]:(s={key:`ctrl+r`,label:`saved flows`,cta:!0,onClick:()=>i(Ym.SavedFlowPicker())},n[4]=i,n[5]=s);let c;if(n[6]!==t?.isGitRepo||n[7]!==i||n[8]!==r||n[9]!==s){if(c=[r,s],t?.isGitRepo){let e;n[11]===i?e=n[12]:(e={key:`ctrl+p`,label:`pick pr`,cta:!0,onClick:()=>i(Ym.SelectPr())},n[11]=i,n[12]=e),c.push(e)}n[6]=t?.isGitRepo,n[7]=i,n[8]=r,n[9]=s,n[10]=c}else c=n[10];return c}case`SelectPr`:{let e,t,a;n[13]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},t={key:`←→`,label:`filter`},a={key:`/`,label:`search`},n[13]=e,n[14]=t,n[15]=a):(e=n[13],t=n[14],a=n[15]);let o;n[16]===i?o=n[17]:(o={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Ym.Main())},n[16]=i,n[17]=o);let s;n[18]===r.PRIMARY?s=n[19]:(s={key:`enter`,label:`select`,color:r.PRIMARY,cta:!0},n[18]=r.PRIMARY,n[19]=s);let c;return n[20]!==o||n[21]!==s?(c=[e,t,a,o,s],n[20]=o,n[21]=s,n[22]=c):c=n[22],c}case`SavedFlowPicker`:{let e;n[23]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},n[23]=e):e=n[23];let t;n[24]===i?t=n[25]:(t={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Ym.Main())},n[24]=i,n[25]=t);let a;n[26]===r.PRIMARY?a=n[27]:(a={key:`enter`,label:`select`,color:r.PRIMARY,cta:!0},n[26]=r.PRIMARY,n[27]=a);let o;return n[28]!==t||n[29]!==a?(o=[e,t,a],n[28]=t,n[29]=a,n[30]=o):o=n[30],o}case`CookieSyncConfirm`:{let t;n[31]===Symbol.for(`react.memo_cache_sentinel`)?(t={key:`↑↓`,label:`nav`},n[31]=t):t=n[31];let a;n[32]===i?a=n[33]:(a={key:`esc`,label:`back`,onClick:()=>i(Ym.Main())},n[32]=i,n[33]=a);let o;n[34]!==e.changesFor||n[35]!==e.instruction||n[36]!==e.savedFlow||n[37]!==i?(o={key:`c`,label:`enable sync`,cta:!0,onClick:()=>{i(Xm({changesFor:e.changesFor,instruction:e.instruction,savedFlow:e.savedFlow,requiresCookies:!0}))}},n[34]=e.changesFor,n[35]=e.instruction,n[36]=e.savedFlow,n[37]=i,n[38]=o):o=n[38];let s;n[39]!==e.changesFor||n[40]!==e.instruction||n[41]!==e.savedFlow||n[42]!==i?(s=()=>{i(Xm({changesFor:e.changesFor,instruction:e.instruction,savedFlow:e.savedFlow,requiresCookies:!1}))},n[39]=e.changesFor,n[40]=e.instruction,n[41]=e.savedFlow,n[42]=i,n[43]=s):s=n[43];let c;n[44]!==r.PRIMARY||n[45]!==s?(c={key:`a`,label:`run anyway`,color:r.PRIMARY,cta:!0,onClick:s},n[44]=r.PRIMARY,n[45]=s,n[46]=c):c=n[46];let l;return n[47]!==a||n[48]!==o||n[49]!==c?(l=[t,a,o,c],n[47]=a,n[48]=o,n[49]=c,n[50]=l):l=n[50],l}case`PortPicker`:{let e,t,a;n[51]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`↑↓`,label:`nav`},t={key:`space`,label:`toggle`},a={key:`/`,label:`custom port`},n[51]=e,n[52]=t,n[53]=a):(e=n[51],t=n[52],a=n[53]);let o;n[54]===i?o=n[55]:(o={key:`esc`,label:`back`,cta:!0,onClick:()=>i(Ym.Main())},n[54]=i,n[55]=o);let s;n[56]===r.PRIMARY?s=n[57]:(s={key:`enter`,label:`confirm`,color:r.PRIMARY,cta:!0},n[56]=r.PRIMARY,n[57]=s);let c;return n[58]!==o||n[59]!==s?(c=[e,t,a,o,s],n[58]=o,n[59]=s,n[60]=c):c=n[60],c}case`Testing`:{let e=s===!0?`notify on`:`notify off`,t=l?`collapse`:`expand`,r;n[61]!==e||n[62]!==c?(r={key:`ctrl+n`,label:e,cta:!0,onClick:c},n[61]=e,n[62]=c,n[63]=r):r=n[63];let i;n[64]===t?i=n[65]:(i={key:`ctrl+o`,label:t,cta:!0},n[64]=t,n[65]=i);let a=l?`collapse`:`cancel`,o;n[66]===a?o=n[67]:(o={key:`esc`,label:a},n[66]=a,n[67]=o);let u;return n[68]!==r||n[69]!==i||n[70]!==o?(u=[r,i,o],n[68]=r,n[69]=i,n[70]=o,n[71]=u):u=n[71],u}case`Results`:{let t;n[72]===Symbol.for(`react.memo_cache_sentinel`)?(t={key:`y`,label:`copy`,cta:!0},n[72]=t):t=n[72];let r;if(n[73]!==e.report.changesFor||n[74]!==e.report.instruction||n[75]!==e.report.pullRequest||n[76]!==i){if(r=[t],_.isSome(e.report.pullRequest)){let e;n[78]===Symbol.for(`react.memo_cache_sentinel`)?(e={key:`p`,label:`post to PR`,cta:!0},n[78]=e):e=n[78],r.push(e)}let a;n[79]===Symbol.for(`react.memo_cache_sentinel`)?(a={key:`s`,label:`save flow`,cta:!0},n[79]=a):a=n[79],r.push(a);let o;n[80]!==e.report.changesFor||n[81]!==e.report.instruction||n[82]!==i?(o={key:`r`,label:`restart`,cta:!0,onClick:()=>{Nv.getState().setExecutedPlan(void 0),i(Xm({changesFor:e.report.changesFor,instruction:e.report.instruction}))}},n[80]=e.report.changesFor,n[81]=e.report.instruction,n[82]=i,n[83]=o):o=n[83],r.push(o);let s;n[84]===i?s=n[85]:(s={key:`esc`,label:`main menu`,cta:!0,onClick:()=>{Nv.getState().setExecutedPlan(void 0),i(Ym.Main())}},n[84]=i,n[85]=s),r.push(s),n[73]=e.report.changesFor,n[74]=e.report.instruction,n[75]=e.report.pullRequest,n[76]=i,n[77]=r}else r=n[77];return r}default:{let e;return n[86]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],n[86]=e):e=n[86],e}}},Nb=e=>e.length>0?` ${e.map(e=>`${e.label} [${e.key}]`).join(` `)}`:``,Pb=()=>{let e=ie(34);if(e[0]!==`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`){for(let t=0;t<34;t+=1)e[t]=Symbol.for(`react.memo_cache_sentinel`);e[0]=`0545e7691866a2045c1228f27b801065cf39232a2a018c782c9ae2928aa6e0a5`}let[t]=jt(),{data:n}=ab(),r=Zm(Vb),{latestVersion:i,updateAvailable:a}=jb(),o=Mb(r,n),s,c,l,u,d,f,p,m;if(e[1]!==o||e[2]!==t||e[3]!==i||e[4]!==r._tag||e[5]!==a){let n=a?[...o,{key:`ctrl+u`,label:`v${i} available`,cta:!0,color:J.warning}]:o;u=n.filter(Hb);let h=ze(Nb(u)),g=Wb,_=n.filter(Gb),v=g(_)+h+2>t?_.filter(Kb):_,y=g(v);l=Math.max(0,t-y-h-2),c=E,p=`column`,e[14]!==t||e[15]!==r._tag?(m=r._tag===`Testing`?V(Mv,{text:`─`.repeat(t),baseColor:J.shimmerBase,highlightColor:J.shimmerHighlight,speed:3}):V(O,{color:J.border,children:`─`.repeat(t)}),e[14]=t,e[15]=r._tag,e[16]=m):m=e[16],s=E,d=1,f=v.map(qb),e[1]=o,e[2]=t,e[3]=i,e[4]=r._tag,e[5]=a,e[6]=s,e[7]=c,e[8]=l,e[9]=u,e[10]=d,e[11]=f,e[12]=p,e[13]=m}else s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13];let h;e[17]===l?h=e[18]:(h=` `.repeat(l),e[17]=l,e[18]=h);let g;e[19]===h?g=e[20]:(g=V(O,{children:h}),e[19]=h,e[20]=g);let _;e[21]===u?_=e[22]:(_=u.length>0?V(Db,{segments:u,color:J.primary,mutedColor:J.textMuted}):null,e[21]=u,e[22]=_);let v;e[23]!==s||e[24]!==d||e[25]!==f||e[26]!==g||e[27]!==_?(v=H(s,{paddingX:d,children:[f,g,_]}),e[23]=s,e[24]=d,e[25]=f,e[26]=g,e[27]=_,e[28]=v):v=e[28];let y;return e[29]!==c||e[30]!==p||e[31]!==m||e[32]!==v?(y=H(c,{flexDirection:p,children:[m,v]}),e[29]=c,e[30]=p,e[31]=m,e[32]=v,e[33]=y):y=e[33],y};function Fb(e){return e.setScreen}function Ib(e){return e.cookiesEnabled}function Lb(e){return e.toggleCookies}function Rb(e){return e.notifications}function zb(e){return e.toggleNotifications}function Bb(e){return e.expanded}function Vb(e){return e.screen}function Hb(e){return!e.cta}function Ub(e){return e.color?` ${e.label} [${e.key}] `:`${e.label} [${e.key}]`}function Wb(e){return ze(e.map(Ub).join(` `))}function Gb(e){return e.cta}function Kb(e){return e.key!==`ctrl+p`}function qb(e,t){let n=H(O,{children:[t>0?` `:``,e.color?H(O,{backgroundColor:e.color,color:`black`,children:[` `,V(O,{bold:!0,children:e.label}),` `,H(O,{children:[`[`,e.key,`]`]}),` `]}):H(O,{children:[H(O,{color:J.textMuted,children:[e.label,` `]}),H(O,{color:J.textMuted,children:[`[`,e.key,`]`]})]})]},e.key+e.label);return e.onClick?V(Lt,{onClick:e.onClick,fullWidth:!1,children:n},e.key+e.label):n}let Jb=null;const Yb=e=>{Jb=e},Xb=()=>Jb?.clear(),Zb=e=>{let t=ie(34);if(t[0]!==`e6ac87aa0f631766a38fac7cfbcee5d6c83ce6fd1edd967a6457097df0e89416`){for(let e=0;e<34;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`e6ac87aa0f631766a38fac7cfbcee5d6c83ce6fd1edd967a6457097df0e89416`}let{agent:n}=e,r=Zm(Qb),i=Zm($b),a=Zm(ex),{data:o}=ab(),s=at(ey),c,l;t[1]!==n||t[2]!==s?(c=()=>{s(_.some(n))},l=[n,s],t[1]=n,t[2]=s,t[3]=c,t[4]=l):(c=t[3],l=t[4]),se(c,l);let u;t[5]!==r._tag||t[6]!==i?(u=()=>{if(r._tag===`CookieSyncConfirm`){i(Ym.Main());return}if(r._tag===`PortPicker`){i(Ym.Main());return}if(r._tag===`Results`){Nv.getState().setExecutedPlan(void 0),i(Ym.Main());return}r._tag!==`Testing`&&i(Ym.Main())},t[5]=r._tag,t[6]=i,t[7]=u):u=t[7];let d=u,{updateAvailable:f}=jb(),{exit:p}=A(),[,m]=L(0),[,h]=jt(),g;t[8]!==p||t[9]!==o?.isGitRepo||t[10]!==d||t[11]!==a||t[12]!==r._tag||t[13]!==m||t[14]!==f?(g=(e,t)=>{if(t.ctrl&&e===`l`){Xb(),m(tx);return}if(t.ctrl&&e===`u`&&f){p(),process.stdout.write(_t),B(`npm`,[`install`,`-g`,`${bt}@latest`],{stdio:`inherit`});return}t.escape&&r._tag!==`Main`&&d(),t.ctrl&&e===`p`&&r._tag===`Main`&&o?.isGitRepo&&a(Ym.SelectPr()),t.ctrl&&e===`r`&&r._tag===`Main`&&a(Ym.SavedFlowPicker())},t[8]=p,t[9]=o?.isGitRepo,t[10]=d,t[11]=a,t[12]=r._tag,t[13]=m,t[14]=f,t[15]=g):g=t[15],te(g);let v;t[16]!==o||t[17]!==r._tag||t[18]!==r.baseUrls||t[19]!==r.changesFor||t[20]!==r.instruction||t[21]!==r.localReplayUrl||t[22]!==r.replayUrl||t[23]!==r.report||t[24]!==r.requiresCookies||t[25]!==r.savedFlow||t[26]!==r.videoUrl?(v=()=>{if(!o)return V(Tb,{gitState:void 0});switch(r._tag){case`PortPicker`:return V(bv,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow,requiresCookies:r.requiresCookies});case`Testing`:return V(My,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow,requiresCookies:r.requiresCookies,baseUrls:r.baseUrls});case`Results`:return V($y,{report:r.report,replayUrl:r.replayUrl,localReplayUrl:r.localReplayUrl,videoUrl:r.videoUrl});case`SelectPr`:return V(eh,{});case`CookieSyncConfirm`:return V(iv,{changesFor:r.changesFor,instruction:r.instruction,savedFlow:r.savedFlow});case`SavedFlowPicker`:return V(cb,{});default:return V(Tb,{gitState:o})}},t[16]=o,t[17]=r._tag,t[18]=r.baseUrls,t[19]=r.changesFor,t[20]=r.instruction,t[21]=r.localReplayUrl,t[22]=r.replayUrl,t[23]=r.report,t[24]=r.requiresCookies,t[25]=r.savedFlow,t[26]=r.videoUrl,t[27]=v):v=t[27];let y=v,b;t[28]===y?b=t[29]:(b=V(E,{flexGrow:1,children:y()}),t[28]=y,t[29]=b);let x;t[30]===Symbol.for(`react.memo_cache_sentinel`)?(x=V(Pb,{}),t[30]=x):x=t[30];let S;return t[31]!==h||t[32]!==b?(S=V(Tt,{children:H(E,{flexDirection:`column`,width:`100%`,height:h,children:[b,x]})}),t[31]=h,t[32]=b,t[33]=S):S=t[33],S};function Qb(e){return e.screen}function $b(e){return e.setScreen}function ex(e){return e.navigateTo}function tx(e){return e+1}const nx=()=>{let e=je();return e===`darwin`?`afplay /System/Library/Sounds/Glass.aiff`:e===`win32`?`powershell -c (New-Object Media.SoundPlayer 'C:\\Windows\\Media\\chimes.wav').PlaySync()`:`paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null || aplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null`},rx=()=>new Promise(e=>{z(nx(),()=>e())});var ix=class extends S.ErrorClass(`ExecutionTimeoutError`)({_tag:S.tag(`ExecutionTimeoutError`),timeoutMs:S.Number}){message=`expect execution timed out after ${this.timeoutMs}ms`};const ax=e=>`[${((Date.now()-e)/1e3).toFixed(1)}s]`,ox=e=>e.replace(/\r?\n/g,` `).replace(/::/g,`: :`),sx=e=>u.runPromise(ny(u.gen(function*(){let t=yield*Qp,n=yield*$p,r=yield*J_,i=Date.now();yield*r.capture(`session:started`,{mode:`headless`,skip_planning:!1,browser_headed:e.headed});let a=(yield*c.string(`GITHUB_ACTIONS`).pipe(c.withDefault(``)))!==``,o=e.ci?` [CI mode]`:``;console.log(`expect v${gt}${o}`),_.isSome(e.timeoutMs)&&console.log(`Timeout: ${e.timeoutMs.value}ms`),console.log(`Agent: ${e.agent}`),console.log(`Target: ${_n(e.changesFor)}`),console.log(`Starting browser test...`),a&&console.log(`::group::expect test execution`);let s=Date.now(),l=Date.now(),d=e.ci?setInterval(()=>{let e=Date.now();if(e-l>=6e4){let t=Math.floor((e-s)/6e4);console.log(`${ax(s)} Still running... (${t} minute${t===1?``:`s`} elapsed)`),l=e}},6e4):void 0;yield*r.capture(`run:started`,{plan_id:`direct`});let f=new Set,p=e=>{for(let t of e.events){if(f.has(t.id))continue;f.add(t.id),l=Date.now();let e=ax(s);switch(t._tag){case`RunStarted`:console.log(`${e} Starting ${t.plan.title}`);break;case`StepStarted`:console.log(`${e} ${U.arrowRight} ${t.stepId} ${t.title}`);break;case`StepCompleted`:console.log(`${e} ${U.tick} ${t.stepId} ${t.summary}`);break;case`StepFailed`:console.log(`${e} ${U.cross} ${t.stepId} ${t.message}`),a&&console.log(`::error title=${ox(t.stepId)} failed::${ox(t.message)}`);break;case`StepSkipped`:console.log(`${e} ${U.arrowRight} ${t.stepId} [skipped] ${t.reason}`);break}}},m=t.execute({changesFor:e.changesFor,instruction:e.instruction,isHeadless:!e.headed,requiresCookies:!1}).pipe(w.tap(e=>u.sync(()=>p(e))),w.runLast,u.map(t=>(t._tag===`Some`?t.value:new Qn({id:``,changesFor:e.changesFor,currentBranch:``,diffPreview:``,fileStats:[],instruction:e.instruction,baseUrl:void 0,isHeadless:!e.headed,requiresCookies:!1,testCoverage:_.none(),title:e.instruction,rationale:`Direct execution`,steps:[],events:[]})).finalizeTextBlock())),h=_.getOrUndefined(e.timeoutMs),g=yield*(h===void 0?m:m.pipe(u.timeoutOrElse({duration:`${h} millis`,onTimeout:()=>u.fail(new ix({timeoutMs:h}))}))).pipe(u.tapError(()=>u.sync(()=>{d&&clearInterval(d),a&&console.log(`::endgroup::`)})),u.catchTag(`ExecutionTimeoutError`,e=>u.sync(()=>{a&&console.log(`::error title=Execution timed out::${ox(e.message)}`),console.error(`\n${e.message}`),process.exit(1)})));d&&clearInterval(d),p(g),a&&console.log(`::endgroup::`);let v=yield*n.report(g),y=v.steps.filter(e=>v.stepStatuses.get(e.id)?.status===`passed`).length,b=v.steps.filter(e=>v.stepStatuses.get(e.id)?.status===`failed`).length;yield*r.capture(`run:completed`,{plan_id:g.id??`direct`,passed:y,failed:b,step_count:g.steps.length,file_count:0,duration_ms:Date.now()-s}),yield*r.capture(`session:ended`,{session_ms:Date.now()-i}),yield*r.flush;let x=v.toPlainText;console.error(`\n${x}`);let S=yield*c.option(c.string(`GITHUB_STEP_SUMMARY`));if(_.isSome(S)){let e=`## expect test results\n\n${v.status===`passed`?`**Result: PASSED**`:`**Result: FAILED**`}\n\n\`\`\`\n${x}\n\`\`\`\n`;yield*u.sync(()=>qe(S.value,e))}yield*u.promise(()=>rx()),process.exit(v.status===`passed`?0:1)}).pipe(u.provide($v({verbose:e.verbose,agent:e.agent}))))),cx={error:W.red,warn:W.yellow,info:W.cyan,success:W.green,dim:W.dim},$={error:(...e)=>{console.log(cx.error(e.join(` `)))},warn:(...e)=>{console.log(cx.warn(e.join(` `)))},info:(...e)=>{console.log(cx.info(e.join(` `)))},success:(...e)=>{console.log(cx.success(e.join(` `)))},dim:(...e)=>{console.log(cx.dim(e.join(` `)))},log:(...e)=>{console.log(e.join(` `))},break:()=>{console.log(``)}},lx=()=>{$.break(),$.log(`Cancelled.`),$.break(),process.exit(0)},ux=e=>mt(e,{onCancel:lx}),dx=(e,t)=>ht({text:e,isSilent:t?.silent}),fx=[`CI`,`CLAUDECODE`,`CURSOR_AGENT`,`CODEX_CI`,`OPENCODE`,`AMP_HOME`,`AMI`],px=()=>fx.some(e=>!!process.env[e]),mx=()=>!process.stdin.isTTY,hx={npm:`npm install -g expect-cli@latest`,pnpm:`pnpm add -g expect-cli@latest`,yarn:`yarn global add expect-cli@latest`,bun:`bun add -g expect-cli@latest`,vp:`vp install -g expect-cli@latest`},gx={npm:`npx -y skills add https://github.com/millionco/expect --skill expect -y`,pnpm:`pnpm dlx skills add https://github.com/millionco/expect --skill expect -y`,yarn:`npx -y skills add https://github.com/millionco/expect --skill expect -y`,bun:`bunx skills add https://github.com/millionco/expect --skill expect -y`,vp:`npx -y skills add https://github.com/millionco/expect --skill expect -y`},_x=()=>{if(process.env.VITE_PLUS_CLI_BIN)return`vp`;let e=process.env.npm_config_user_agent;if(e){if(e.startsWith(`pnpm`))return`pnpm`;if(e.startsWith(`yarn`))return`yarn`;if(e.startsWith(`bun`))return`bun`;if(e.startsWith(`npm`))return`npm`}return`npm`},vx=e=>e||px()||mx(),yx=e=>new Promise(t=>{z(e,{timeout:1e4},e=>{t(!e)}).stdin?.end()}),bx=async(e={})=>{let t=vx(e.yes??!1),n=_x(),r=hx[n];$.break(),$.log(` ${W.red(U.cross)}${W.green(U.tick)} ${W.bold(`Expect`)} ${cx.dim(`v${gt}`)}`),$.dim(` Let agents test your code in a real browser.`),$.break(),Ya().length===0&&($.error(`No supported coding agent found. expect requires one of: Claude Code, Codex, or Cursor.`),$.break(),$.log(` Install one to get started:`),$.log(` ${cx.info(`Claude Code`)} ${cx.dim(`https://docs.anthropic.com/en/docs/claude-code`)}`),$.log(` ${cx.info(`Codex`)} ${cx.dim(`https://github.com/openai/codex`)}`),$.log(` ${cx.info(`Cursor`)} ${cx.dim(`https://cursor.com`)}`),$.break(),process.exit(1));let i=dx(`Installing expect-cli globally...`).start();await yx(r)?i.succeed(`Installed! ${cx.info(`expect-cli`)} is now available globally.`):(i.fail(`Failed to install globally.`),$.dim(` Run manually: ${cx.info(r)}`)),$.break();let a=t;if(t||(a=(await ux({type:`confirm`,name:`installSkill`,message:`Install the ${cx.info(`expect`)} skill for your coding agent?`,initial:!0})).installSkill),a){let e=gx[n],t=dx(`Installing skill...`).start();await yx(e)?t.succeed(`Skill installed.`):(t.fail(`Failed to install skill.`),$.dim(` Run manually: ${cx.info(e)}`))}$.break(),$.success(`Setup complete! Here's how to get started:`),$.break(),$.log(` 1. ${cx.info(`cd`)} into your project directory`),$.log(` 2. Start your dev server (e.g. ${cx.dim(`npm run dev`)})`),$.log(` 3. Run ${cx.info(`expect-cli`)} to open the interactive test runner`),$.break(),$.log(` Or run headlessly from your coding agent:`),$.break(),$.log(` ${cx.dim(`$`)} ${cx.info(`expect-cli -m "test the login flow" -y`)}`),$.break(),$.log(` Set ${cx.info(`EXPECT_BASE_URL`)} if your app is not on localhost:3000:`),$.break(),$.log(` ${cx.dim(`$`)} ${cx.info(`EXPECT_BASE_URL=http://localhost:5173 expect-cli -m "test the homepage" -y`)}`),$.break()},xx=[`packages/*`,`apps/*`],Sx=e=>yt.some(t=>e.includes(t)),Cx=u.fn(`detectAgent`)(function*(e){let t=yield*p.FileSystem;for(let[n,r]of Object.entries(xt)){let i=G.join(e,n);if(yield*t.exists(i).pipe(u.catchTag(`PlatformError`,()=>u.succeed(!1))))return r}let n=G.join(e,`package.json`),r=yield*t.readFileString(n).pipe(u.catchTag(`PlatformError`,()=>u.succeed(``)));if(r){let e=yield*u.try({try:()=>JSON.parse(r),catch:()=>({_tag:`JsonParseError`})}).pipe(u.catchTag(`JsonParseError`,()=>u.succeed(void 0)));if(e?.packageManager){let t=e.packageManager.split(`@`)[0];if(t)return t}}return`npm`}),wx=u.fn(`readPackageJson`)(function*(e){let t=yield*p.FileSystem,n=G.join(e,`package.json`),r=yield*t.readFileString(n);return yield*u.try({try:()=>JSON.parse(r),catch:()=>({_tag:`JsonParseError`})})}),Tx=u.fn(`listWorkspaceDirectories`)(function*(e){let t=yield*p.FileSystem,n=[];for(let r of xx){let i=G.join(e,G.dirname(r)),a=yield*t.readDirectory(i).pipe(u.catchTag(`PlatformError`,()=>u.succeed([])));for(let e of a){let r=G.join(i,e);(yield*t.stat(r).pipe(u.catchTag(`PlatformError`,()=>u.succeed(void 0))))?.type===`Directory`&&n.push(r)}}return n}),Ex=(e,t,n)=>new Promise(r=>{ce(e,[`run`,n],{cwd:t,timeout:12e4,maxBuffer:5*1024*1024},(e,t,i)=>{let a=(t+`
44
+ `+i).trim();r({script:n,passed:!e,output:a})})}),Dx=u.fn(`discoverPackages`)(function*(e){let t=yield*Tx(e),n=[];for(let e of t){let t=yield*wx(e).pipe(u.catchTag(`PlatformError`,()=>u.succeed(void 0)),u.catchTag(`JsonParseError`,()=>u.succeed(void 0)));if(!t?.scripts)continue;let r=Object.keys(t.scripts).filter(Sx);r.length!==0&&n.push({packageName:t.name??G.basename(e),directory:e,scripts:r})}return n}),Ox=async(e,t)=>{let n=u.gen(function*(){let n=yield*Cx(e),r=yield*Dx(e);return yield*u.forEach(r,e=>u.gen(function*(){t.onPackageStart(e.packageName,e.scripts);let r=[];for(let i of e.scripts){let a=yield*u.promise(()=>Ex(n,e.directory,i));t.onScriptDone(e.packageName,a),r.push(a)}return{packageName:e.packageName,directory:e.directory,results:r}}),{concurrency:4})});return u.runPromise(n.pipe(u.provide(be.layer)))},kx=e=>{let t=ie(5);if(t[0]!==`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`){for(let e=0;e<5;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`}let{statusMap:n}=e,r;if(t[1]!==n){let e=Array.from(n.entries()),i,a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(i=V(O,{bold:!0,children:`expect audit`}),a=V(O,{children:` `}),t[3]=i,t[4]=a):(i=t[3],a=t[4]),r=H(E,{flexDirection:`column`,paddingY:1,children:[i,a,e.map(Lx)]}),t[1]=n,t[2]=r}else r=t[2];return r},Ax=e=>{let t=ie(12);if(t[0]!==`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`){for(let e=0;e<12;e+=1)t[e]=Symbol.for(`react.memo_cache_sentinel`);t[0]=`aef0f8bb7ade6156f95a0a2a02eb67442b17c5cae1cd627958814a31c95c65dd`}let{results:n}=e,r=0,i=0;for(let e of n)for(let t of e.results)t.passed?r++:i++;let a=`${r} passed, ${i} failed`,o=i>0?Nt.RED:Nt.GREEN,s;t[1]!==a||t[2]!==o?(s=V(O,{bold:!0,color:o,children:a}),t[1]=a,t[2]=o,t[3]=s):s=t[3];let c;t[4]===i?c=t[5]:(c=i>0&&H(O,{color:Nt.YELLOW,children:[`Run `,V(O,{bold:!0,children:`expect`}),` to test your changes in a real browser and catch issues before they ship.`]}),t[4]=i,t[5]=c);let l;t[6]===i?l=t[7]:(l=i===0&&H(O,{color:Nt.GREEN,children:[`Looking good! Run `,V(O,{bold:!0,children:`expect`}),` to verify your changes work end-to-end in the browser.`]}),t[6]=i,t[7]=l);let u;return t[8]!==s||t[9]!==c||t[10]!==l?(u=H(E,{flexDirection:`column`,gap:1,children:[s,c,l]}),t[8]=s,t[9]=c,t[10]=l,t[11]=u):u=t[11],u},jx=async()=>{let e=process.cwd(),t={current:new Map},n,r,i=k(V(()=>{let[e,t]=L(new Map),[i,a]=L();return n=e=>t(new Map(e)),r=a,H(E,{flexDirection:`column`,children:[V(kx,{statusMap:e}),i&&V(Ax,{results:i})]})},{})),a=await Ox(e,{onPackageStart:(e,r)=>{t.current.set(e,{scripts:r,completed:[],done:!1}),n?.(t.current)},onScriptDone:(e,r)=>{let i=t.current.get(e);i&&(i.completed.push(r),i.done=i.completed.length===i.scripts.length),n?.(t.current)}});r?.(a),setTimeout(()=>{i.unmount(),a.reduce((e,t)=>e+t.results.filter(e=>!e.passed).length,0)>0&&process.exit(1)},100)},Mx=async()=>{let e=process.cwd();console.log(``),console.log(W.bold(`expect audit`)),console.log(``);let t=await Ox(e,{onPackageStart:(e,t)=>{console.log(`${U.arrowRight} ${W.bold(e)} (${t.join(`, `)})`)},onScriptDone:(e,t)=>{let n=t.passed?W.green(U.tick):W.red(U.cross);if(console.log(` ${n} ${t.script}`),!t.passed){let e=t.output.split(`
45
45
  `).slice(-3).join(`
46
- `);console.log(G.dim(` ${e.split(`
46
+ `);console.log(W.dim(` ${e.split(`
47
47
  `).join(`
48
- `)}`))}}}),n=0,r=0;for(let e of t)for(let t of e.results)t.passed?n++:r++;console.log(``);let i=`${n} passed, ${r} failed`,a=r>0?G.red:G.green;console.log(a(G.bold(i))),r>0?(console.log(``),console.log(G.yellow(`Run ${G.bold(`expect`)} to test your changes in a real browser and catch issues before they ship.`))):(console.log(``),console.log(G.green(`Looking good! Run ${G.bold(`expect`)} to verify your changes work end-to-end in the browser.`))),console.log(``),r>0&&process.exit(1)},kx=async()=>{lx()||ux()?await Ox():await Dx()};function Ax(e){return e.passed}function jx(e){return U(E,{flexDirection:`column`,children:[U(O,{children:[` `,e.passed?H(O,{color:Mt.GREEN,children:W.tick}):H(O,{color:Mt.RED,children:W.cross}),` `,e.script]}),!e.passed&&U(O,{color:`gray`,children:[` `,e.output.split(`
48
+ `)}`))}}}),n=0,r=0;for(let e of t)for(let t of e.results)t.passed?n++:r++;console.log(``);let i=`${n} passed, ${r} failed`,a=r>0?W.red:W.green;console.log(a(W.bold(i))),r>0?(console.log(``),console.log(W.yellow(`Run ${W.bold(`expect`)} to test your changes in a real browser and catch issues before they ship.`))):(console.log(``),console.log(W.green(`Looking good! Run ${W.bold(`expect`)} to verify your changes work end-to-end in the browser.`))),console.log(``),r>0&&process.exit(1)},Nx=async()=>{px()||mx()?await Mx():await jx()};function Px(e){return e.passed}function Fx(e){return H(E,{flexDirection:`column`,children:[H(O,{children:[` `,e.passed?V(O,{color:Nt.GREEN,children:U.tick}):V(O,{color:Nt.RED,children:U.cross}),` `,e.script]}),!e.passed&&H(O,{color:`gray`,children:[` `,e.output.split(`
49
49
  `).slice(-3).join(`
50
- `)]})]},e.script)}function Mx(e){return U(O,{color:`gray`,children:[` `,H(Le,{type:`dots`}),` `,e]},e)}function Nx(e){let[t,n]=e;return U(E,{flexDirection:`column`,children:[U(E,{children:[n.done&&H(O,{children:n.completed.every(Ax)?H(O,{color:Mt.GREEN,children:W.tick}):H(O,{color:Mt.RED,children:W.cross})}),!n.done&&H(O,{color:`white`,children:H(Le,{type:`dots`})}),U(O,{bold:!0,children:[` `,t]})]}),n.completed.map(jx),!n.done&&n.scripts.filter(e=>!n.completed.some(t=>t.script===e)).slice(0,1).map(Mx)]},t)}const Px=[`unstaged`,`branch`,`changes`],Fx=new T().name(`expect`).description(`AI-powered browser testing for your changes`).version(ht,`-v, --version`).option(`-m, --message <instruction>`,`natural language instruction for what to test`).option(`-f, --flow <slug>`,`reuse a saved flow by its slug`).option(`-y, --yes`,`run immediately without confirmation`).option(`-a, --agent <provider>`,`agent provider to use (claude or codex)`).option(`-t, --target <target>`,`what to test: unstaged, branch, or changes`,`changes`).option(`--verbose`,`enable verbose logging`).option(`--headed`,`show a visible browser window during tests`).option(`--no-cookies`,`skip system browser cookie extraction`).option(`--replay-host <url>`,`website host for live replay viewer`,`https://expect.dev`).addHelpText(`after`,`
50
+ `)]})]},e.script)}function Ix(e){return H(O,{color:`gray`,children:[` `,V(Le,{type:`dots`}),` `,e]},e)}function Lx(e){let[t,n]=e;return H(E,{flexDirection:`column`,children:[H(E,{children:[n.done&&V(O,{children:n.completed.every(Px)?V(O,{color:Nt.GREEN,children:U.tick}):V(O,{color:Nt.RED,children:U.cross})}),!n.done&&V(O,{color:`white`,children:V(Le,{type:`dots`})}),H(O,{bold:!0,children:[` `,t]})]}),n.completed.map(Fx),!n.done&&n.scripts.filter(e=>!n.completed.some(t=>t.script===e)).slice(0,1).map(Ix)]},t)}const Rx=[`unstaged`,`branch`,`changes`],zx=new T().name(`expect`).description(`AI-powered browser testing for your changes`).version(gt,`-v, --version`).option(`-m, --message <instruction>`,`natural language instruction for what to test`).option(`-f, --flow <slug>`,`reuse a saved flow by its slug`).option(`-y, --yes`,`run immediately without confirmation`).option(`-a, --agent <provider>`,`agent provider to use (claude or codex)`).option(`-t, --target <target>`,`what to test: unstaged, branch, or changes`,`changes`).option(`--verbose`,`enable verbose logging`).option(`--headed`,`show a visible browser window during tests`).option(`--no-cookies`,`skip system browser cookie extraction`).option(`--ci`,`force CI mode: headless, no cookies, auto-yes, 30-minute timeout`).option(`--timeout <ms>`,`execution timeout in milliseconds`,parseInt).option(`--replay-host <url>`,`website host for live replay viewer`,`https://expect.dev`).addHelpText(`after`,`
51
51
  Examples:
52
52
  $ expect open interactive TUI
53
53
  $ expect -m "test the login flow" -y run immediately
54
54
  $ expect --headed -m "smoke test" -y run with a visible browser
55
55
  $ expect --target branch test all branch changes
56
56
  $ expect --target unstaged test unstaged changes
57
- $ expect --no-cookies -m "test" -y skip system browser cookie extraction`),Ix=`\x1B[?1000l\x1B[?1006l`,Lx=async e=>{let t=Date.now();await $_(),process.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`),process.on(`exit`,()=>process.stdout.write(Ix+gt));let n=k(H(nt,{initialValues:[[$v,_.some(e)]],children:H(M,{client:Zm,children:H(Xb,{agent:e})})}));Jb(n),await n.waitUntilExit(),await ev(t),process.stdout.write(Ix+gt),process.exit(0)},Rx=async e=>{let t=process.cwd();return u.runPromise(u.gen(function*(){let t=yield*Yp,n=yield*t.getMainBranch,r=yield*t.getCurrentBranch;return e===`branch`?{changesFor:hn.makeUnsafe({_tag:`Branch`,mainBranch:n}),currentBranch:r}:e===`changes`?{changesFor:hn.makeUnsafe({_tag:`Changes`,mainBranch:n}),currentBranch:r}:{changesFor:hn.makeUnsafe({_tag:`WorkingTree`}),currentBranch:r}}).pipe(u.provide(Yp.withRepoRoot(t))))},zx=(e,t)=>{X_.setState({...e.agent?{agentBackend:e.agent}:{},browserHeaded:e.headed??!1,replayHost:e.replayHost??`https://expect.dev`}),e.message?Xm.setState({screen:Jm.Testing({changesFor:t,instruction:e.message})}):Xm.setState({screen:Jm.Main()})},Bx=async(e,t)=>{let{changesFor:n}=await Rx(e);return rx({changesFor:n,instruction:t.message??`Test all changes from main in the browser and verify they work correctly.`,agent:t.agent??`claude`,verbose:t.verbose??!1,headed:t.headed??!1})},Vx=async(e,t)=>{let{changesFor:n}=await Rx(e);zx(t,n),Lx(t.agent??`claude`)};Fx.command(`init`).description(`set up expect for your coding agent`).option(`-y, --yes`,`skip confirmation prompts`).action(async e=>{await gx(e)}),Fx.command(`audit`).description(`audit your workspace for lint, type, and formatting issues`).action(async()=>{await kx()}),Fx.action(async()=>{let e=Fx.opts(),t=e.target??`changes`;if(Px.includes(t)||Fx.error(`Unknown target: ${t}. Use ${Px.join(`, `)}.`),lx()||ux())return Bx(t,e);e.message||e.flow||e.yes?await Vx(t,e):(X_.setState({browserHeaded:e.headed??!1,replayHost:e.replayHost??`https://expect.dev`}),Lx(e.agent??`claude`))}),Fx.parse();export{};
57
+ $ expect --no-cookies -m "test" -y skip system browser cookie extraction`),Bx=`\x1B[?1000l\x1B[?1006l`,Vx=async e=>{let t=Date.now();await ev(),process.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H`),process.on(`exit`,()=>process.stdout.write(Bx+_t));let n=k(V(rt,{initialValues:[[ey,_.some(e)]],children:V(j,{client:Qm,children:V(Zb,{agent:e})})}));Yb(n),await n.waitUntilExit(),await tv(t),process.stdout.write(Bx+_t),process.exit(0)},Hx=async e=>{let t=process.cwd();return u.runPromise(u.gen(function*(){let t=yield*Xp,n=yield*t.getMainBranch,r=yield*t.getCurrentBranch;return e===`branch`?{changesFor:gn.makeUnsafe({_tag:`Branch`,mainBranch:n}),currentBranch:r}:e===`changes`?{changesFor:gn.makeUnsafe({_tag:`Changes`,mainBranch:n}),currentBranch:r}:{changesFor:gn.makeUnsafe({_tag:`WorkingTree`}),currentBranch:r}}).pipe(u.provide(Xp.withRepoRoot(t))))},Ux=(e,t)=>{Z_.setState({...e.agent?{agentBackend:e.agent}:{},browserHeaded:e.headed??!1,replayHost:e.replayHost??`https://expect.dev`}),e.message?Zm.setState({screen:Ym.Testing({changesFor:t,instruction:e.message})}):Zm.setState({screen:Ym.Main()})},Wx=async(e,t)=>{let n=t.ci||px()||mx(),r=t.timeout?_.some(t.timeout):n?_.some(18e5):_.none(),{changesFor:i}=await Hx(e);return sx({changesFor:i,instruction:t.message??`Test all changes from main in the browser and verify they work correctly.`,agent:t.agent??`claude`,verbose:t.verbose??!1,headed:n?!1:t.headed??!1,ci:n,timeoutMs:r})},Gx=async(e,t)=>{let{changesFor:n}=await Hx(e);Ux(t,n),Vx(t.agent??`claude`)};zx.command(`init`).description(`set up expect for your coding agent`).option(`-y, --yes`,`skip confirmation prompts`).action(async e=>{await bx(e)}),zx.command(`audit`).description(`audit your workspace for lint, type, and formatting issues`).action(async()=>{await Nx()}),zx.action(async()=>{let e=zx.opts(),t=e.target??`changes`;if(Rx.includes(t)||zx.error(`Unknown target: ${t}. Use ${Rx.join(`, `)}.`),e.ci||px()||mx())return Wx(t,e);e.message||e.flow||e.yes?await Gx(t,e):(Z_.setState({browserHeaded:e.headed??!1,replayHost:e.replayHost??`https://expect.dev`}),Vx(e.agent??`claude`))}),zx.parse();export{};
58
58
  //# sourceMappingURL=index.js.map