@getsolaris/oh-my-worktree 0.7.5 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/omw.js +54 -55
  2. package/package.json +1 -1
package/dist/omw.js CHANGED
@@ -1,34 +1,33 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var Oa=Object.defineProperty;var Wa=(t)=>t;function Da(t,e){this[t]=Wa.bind(null,e)}var xt=(t,e)=>{for(var o in e)Oa(t,o,{get:e[o],enumerable:!0,configurable:!0,set:Da.bind(e,o)})};var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=import.meta.require;function ki(t){if(t instanceof Error)return t;return Error(typeof t==="string"?t:"Unknown error",{cause:t})}function zi(t,e=Ct){let o=e&&e.context&&e.context[Pf],n=ki(t);if(!o)throw n;try{for(let r of o)r(n)}catch(r){zi(r,e&&e.owner||null)}}function yf(){let t={owner:Ct,context:Ct?Ct.context:null,owned:null,cleanups:null};if(Ct)if(!Ct.owned)Ct.owned=[t];else Ct.owned.push(t);return t}function v(t,e){return[()=>t,(o)=>{return t=typeof o==="function"?o(t):o}]}function de(t,e){}function re(t,e){Ct=yf();let o;try{o=t(e)}catch(n){zi(n)}finally{Ct=Ct.owner}return()=>o}function Ye(t,e,o={}){let n=Array.isArray(t),r=o.defer;return()=>{if(r)return;let i;if(n){i=[];for(let s=0;s<t.length;s++)i.push(t[s]())}else i=t();return e(i)}}function an(t){if(Ct)if(!Ct.cleanups)Ct.cleanups=[t];else Ct.cleanups.push(t);return t}function to(t){let e=Symbol("context");return{id:e,Provider:Rf(e),defaultValue:t}}function eo(t){return Ct&&Ct.context&&Ct.context[t.id]!==void 0?Ct.context[t.id]:t.defaultValue}function Ef(t){let e=re(()=>sr(t()));return e.toArray=()=>{let o=e();return Array.isArray(o)?o:o!=null?[o]:[]},e}function sr(t){if(typeof t==="function"&&!t.length)return sr(t());if(Array.isArray(t)){let e=[];for(let o=0;o<t.length;o++){let n=sr(t[o]);Array.isArray(n)?e.push.apply(e,n):e.push(n)}return e}return t}function Rf(t){return function(o){return re(()=>{return Ct.context={...Ct.context,[t]:o.value},Ef(()=>o.children)})}}function Ni(t){let e=String(t),o=e.length-1;return pe.context.id+(o?String.fromCharCode(96+o):"")+e}function Mf(t,e){let o=t.each||[],n=o.length,r=t.children;if(n){let i=Array(n);for(let s=0;s<n;s++)i[s]=e(r,o[s],s);return i}return t.fallback}function St(t){return Mf(t,(e,o,n)=>e(o,()=>n))}function O(t){let e;return t.when?typeof(e=t.children)==="function"?e(t.keyed?t.when:()=>t.when):e:t.fallback||""}function vi(t,e,o={}){if(typeof e!=="function")o=e||{},e=t,t=!0;let n=new Set,r=pe.getNextContextId(),i={},s=o.storage?o.storage(o.initialValue)[0]():o.initialValue,c,f;if(pe.context.async&&o.ssrLoadFrom!=="initial"){if(i=pe.context.resources[r]||(pe.context.resources[r]={}),i.ref){if(!i.data&&!i.ref[0]._loading&&!i.ref[0].error)i.ref[1].refetch();return i.ref}}let a=()=>{if(f)throw f;let x=o.ssrLoadFrom!=="initial"&&pe.context.async&&"data"in pe.context.resources[r];if(!x&&Ao)Ao.push(r);if(!x&&h._loading){let m=eo(Of);if(m)m.resources.set(r,h),n.add(m)}return x},h=()=>{return a()?pe.context.resources[r].data:s},u=()=>{return a(),h._loading};h._loading=!1,h.error=void 0,h.state="initialValue"in o?"ready":"unresolved",Object.defineProperties(h,{latest:{get(){return h()}},loading:{get(){return u()}}});function d(){let x=pe.context;if(!x.async)return h._loading=!!(typeof t==="function"?t():t);if(x.resources&&r in x.resources&&"data"in x.resources[r]){s=x.resources[r].data;return}let m;try{if(Ao=[],m=typeof t==="function"?t():t,Ao.length)return}finally{Ao=null}if(!c){if(m==null||m===!1)return;c=e(m,{value:s})}if(c!=null&&typeof c==="object"&&"then"in c){if(h._loading=!0,h.state="pending",c=c.then((b)=>{return h._loading=!1,h.state="ready",x.resources[r].data=b,c=null,Ji(n),b}).catch((b)=>{throw h._loading=!1,h.state="errored",h.error=f=ki(b),c=null,Ji(n),f}),x.serialize)x.serialize(r,c,o.deferStream);return c}if(x.resources[r].data=c,x.serialize)x.serialize(r,c);return c=null,x.resources[r].data}if(o.ssrLoadFrom!=="initial")d();let g=[h,{refetch:d,mutate:(x)=>s=x}];if(c)i.ref=g;return g}function Wf(t){for(let e of t.resources.values())if(e._loading)return!1;return!0}function Ji(t){for(let e of t){if(!Wf(e))continue;e.completed(),t.delete(e)}}var Mm,Om,Wm,Pf,Ct=null,pe,Of,Ao=null;var Rt=N(()=>{Mm=Symbol("solid-proxy"),Om=Symbol("solid-track"),Wm=Symbol("solid-dev-component"),Pf=Symbol("error");pe={context:void 0,getContextId(){if(!this.context)throw Error("getContextId cannot be used under non-hydrating context");return Ni(this.context.count)},getNextContextId(){if(!this.context)throw Error("getNextContextId cannot be used under non-hydrating context");return Ni(this.context.count++)}};Of=to()});function Ui(t){return typeof t==="object"&&t!==null&&"frames"in t&&"interval"in t&&Array.isArray(t.frames)}function Vi(t){return typeof t==="object"&&t!==null&&"label"in t&&"onClick"in t}function cr(t,e){switch(t){case"success":return e.success;case"error":return e.error;case"warning":return e.warning;case"info":return e.info;case"loading":return ar(e.loading);default:return""}}function ar(t){if(Ui(t))return t.frames[0]??"\u25CC";return t}function fr(t){return Ui(t)?t:null}var Df,Ki;var qi=N(()=>{Df={frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],interval:100},Ki={success:"\u2713",error:"\u2717",warning:"!",info:"\u2139",loading:Df,close:"\xD7"}});import{BoxRenderable as ln,TextAttributes as Ff,TextRenderable as Io,parseColor as Bf}from"@opentui/core";function _f(t){return t!==null&&typeof t==="object"&&"ok"in t&&typeof t.ok==="boolean"&&"status"in t&&typeof t.status==="number"}function Jf(t,e={}){let[o,n]=t.split("-"),r={position:"absolute"};if(o==="top")r.top=e.top??fn.top;else r.bottom=e.bottom??fn.bottom;if(n==="left")r.left=e.left??fn.left,r.alignItems="flex-start";else if(n==="center")r.left=0,r.width="100%",r.alignItems="center";else r.right=e.right??fn.right,r.alignItems="flex-end";return r}function kf(t){return t.includes("center")}function zf(t){return t.startsWith("top")}function vf(t,e={top:0,right:0,bottom:0,left:0}){if(!t)return{...e};let{padding:o,paddingX:n,paddingY:r}=t;return{top:t.paddingTop??r??o??e.top,right:t.paddingRight??n??o??e.right,bottom:t.paddingBottom??r??o??e.bottom,left:t.paddingLeft??n??o??e.left}}function Uf(...t){let e={};for(let o of t){if(!o)continue;Object.assign(e,o)}return e}function Xi(t,e,o){let n=lr.style,r=lr[t]?.style,i=e?.style,s=e?.[t]?.style,c=Uf(n,r,i,s,o);if(c.border===!1)delete c.borderStyle,delete c.borderColor;return c}function Zi(t,e,o){if(o!==void 0)return o;let n=e?.[t]?.duration;if(n!==void 0)return n;if(e?.duration!==void 0)return e.duration;return lr.duration}var Lf,Af=200,Qi=60,fn,If,lr,jf=1,Tf=class{subscribers=[];toasts=[];dismissedToasts=new Set;_activeToasts=[];_updateActiveToastsCache=()=>{let t=this.toasts.filter((e)=>!this.dismissedToasts.has(e.id));if(t.length!==this._activeToasts.length||t.some((e,o)=>e!==this._activeToasts[o]))this._activeToasts=t};subscribe=(t)=>{return this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);if(e>-1)this.subscribers.splice(e,1)}};publish=(t)=>{for(let e of this.subscribers)e(t)};addToast=(t)=>{this.toasts=[...this.toasts,t],this._updateActiveToastsCache(),this.publish(t)};create=(t)=>{let{message:e,...o}=t,n=typeof t.id==="number"||t.id&&t.id.length>0?t.id:jf++,r=this.toasts.find((s)=>s.id===n),i=t.dismissible===void 0?!0:t.dismissible;if(this.dismissedToasts.has(n))this.dismissedToasts.delete(n);if(r)this.toasts=this.toasts.map((s)=>{if(s.id===n)return this.publish({...s,...t,id:n,title:e}),{...s,...t,id:n,dismissible:i,title:e};return s}),this._updateActiveToastsCache();else this.addToast({title:e,...o,dismissible:i,id:n,type:t.type??"default"});return n};dismiss=(t)=>{if(t!==void 0)this.dismissedToasts.add(t),this._updateActiveToastsCache(),setTimeout(()=>{for(let e of this.subscribers)e({id:t,dismiss:!0})},0);else{for(let e of this.toasts){this.dismissedToasts.add(e.id);for(let o of this.subscribers)o({id:e.id,dismiss:!0})}this._updateActiveToastsCache()}return t};message=(t,e)=>{return this.create({...e,message:t,type:"default"})};error=(t,e)=>{return this.create({...e,message:t,type:"error"})};success=(t,e)=>{return this.create({...e,message:t,type:"success"})};info=(t,e)=>{return this.create({...e,message:t,type:"info"})};warning=(t,e)=>{return this.create({...e,message:t,type:"warning"})};loading=(t,e)=>{return this.create({...e,message:t,type:"loading"})};promise=(t,e)=>{if(!e)return;let o;if(e.loading!==void 0)o=this.create({...e,type:"loading",message:e.loading,description:typeof e.description!=="function"?e.description:void 0});let n=t instanceof Function?t():t,r=o!==void 0,i,s=n.then(async(f)=>{if(i=["resolve",f],_f(f)&&!f.ok){r=!1;let a=typeof e.error==="function"?await e.error(`HTTP error! status: ${f.status}`):e.error,h=typeof e.description==="function"?await e.description(`HTTP error! status: ${f.status}`):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}else if(f instanceof Error){r=!1;let a=typeof e.error==="function"?await e.error(f):e.error,h=typeof e.description==="function"?await e.description(f):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}else if(e.success!==void 0){r=!1;let a=typeof e.success==="function"?await e.success(f):e.success,h=typeof e.description==="function"?await e.description(f):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"success",description:h,...u})}}).catch(async(f)=>{if(i=["reject",f],e.error!==void 0){r=!1;let a=typeof e.error==="function"?await e.error(f):e.error,h=typeof e.description==="function"?await e.description(f):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}}).finally(()=>{if(r)this.dismiss(o),o=void 0;e.finally?.()}),c=()=>new Promise((f,a)=>s.then(()=>i[0]==="reject"?a(i[1]):f(i[1])).catch(a));if(typeof o!=="string"&&typeof o!=="number")return{unwrap:c};return Object.assign(o,{unwrap:c})};getActiveToasts=()=>{return this._activeToasts}},At,Gf=(t,e)=>At.message(t,e),Hf=()=>At.toasts,Nf=()=>At.getActiveToasts(),oo,Vf,Yi;var ts=N(()=>{qi();Lf={SHORT:2000,DEFAULT:4000,LONG:6000,EXTENDED:1e4,PERSISTENT:1/0},fn={top:1,right:2,bottom:1,left:2},If={border:!0,borderStyle:"single",borderColor:"#333333",minHeight:3,backgroundColor:"#1a1a1a",foregroundColor:"#ffffff",mutedColor:"#6b7280"},lr={style:If,duration:Lf.DEFAULT,default:{style:{borderColor:"#333333"}},success:{style:{borderColor:"#22c55e"}},error:{style:{borderColor:"#ef4444"}},warning:{style:{borderColor:"#f59e0b"}},info:{style:{borderColor:"#3b82f6"}},loading:{style:{borderColor:"#6b7280"}}};At=new Tf,oo=Object.assign(Gf,{success:At.success,info:At.info,warning:At.warning,error:At.error,message:At.message,promise:At.promise,dismiss:At.dismiss,loading:At.loading},{getHistory:Hf,getToasts:Nf});Vf=class extends ln{_toast;_icons;_toastOptions;_computedStyle;_closeButton;_onRemove;_remainingTime;_closeTimerStartTime=0;_lastCloseTimerStartTime=0;_timerHandle=null;_paused=!1;_dismissed=!1;_spinnerHandle=null;_spinnerFrameIndex=0;_spinnerConfig=null;_iconText=null;_contentBox=null;_titleText=null;_descriptionText=null;_actionsBox=null;constructor(t,e){let o=Xi(e.toast.type,e.toastOptions,e.toast.style),n=Zi(e.toast.type,e.toastOptions,e.toast.duration),r=vf(o,{top:0,right:1,bottom:0,left:1});super(t,{id:`toast-${e.toast.id}`,flexDirection:"row",gap:1,border:o.border,borderStyle:o.borderStyle,borderColor:o.borderColor,customBorderChars:o.customBorderChars,backgroundColor:o.backgroundColor,minHeight:o.minHeight,maxWidth:o.maxWidth??Qi,minWidth:o.minWidth,paddingTop:r.top,paddingRight:r.right,paddingBottom:r.bottom,paddingLeft:r.left,onMouseOver:()=>this.pause(),onMouseOut:()=>this.resume()});if(this._toast=e.toast,this._icons=e.icons===!1?!1:{...Ki,...e.icons},this._toastOptions=e.toastOptions,this._computedStyle=o,this._closeButton=e.closeButton,this._onRemove=e.onRemove,this._remainingTime=n,this.setupContent(),this._remainingTime!==1/0&&this._toast.type!=="loading")this.startTimer();if(this._toast.type==="loading")this.startSpinner()}setupContent(){let t=this.ctx,e=this._toast,o=this._computedStyle,n=this._icons,r=o.iconColor??o.borderColor,i=e.type==="loading";if(i&&n!==!1)this._spinnerConfig=fr(n.loading);let s=e.icon??(n===!1?void 0:i?ar(n.loading):cr(e.type,n));if(s)this._iconText=new Io(t,{id:`${this.id}-icon`,content:s,fg:r,flexShrink:0,paddingTop:0,paddingBottom:0}),this.add(this._iconText);this._contentBox=new ln(t,{id:`${this.id}-content`,flexDirection:"column",flexGrow:1,flexShrink:1,gap:0});let c=typeof e.title==="function"?e.title():e.title;if(c)this._titleText=new Io(t,{id:`${this.id}-title`,content:c,fg:o.foregroundColor,attributes:Ff.BOLD,wrapMode:"word"}),this._contentBox.add(this._titleText);let f=typeof e.description==="function"?e.description():e.description;if(f)this._descriptionText=new Io(t,{id:`${this.id}-description`,content:f,fg:o.mutedColor,wrapMode:"word"}),this._contentBox.add(this._descriptionText);if(this.add(this._contentBox),e.action){if(this._actionsBox=new ln(t,{id:`${this.id}-actions`,flexDirection:"row",gap:1,flexShrink:0,alignItems:"center"}),e.action&&Vi(e.action)){let a=new Io(t,{id:`${this.id}-action`,content:`[${e.action.label}]`,fg:o.foregroundColor,onMouseUp:()=>e.action?.onClick?.()});this._actionsBox.add(a)}this.add(this._actionsBox)}if((e.closeButton??this._closeButton)&&e.dismissible!==!1){let a=n===!1?"\xD7":n.close,h=new Io(t,{id:`${this.id}-close`,content:a,fg:o.mutedColor,flexShrink:0,onMouseUp:()=>this.dismiss()});this.add(h)}}startTimer(){if(this._remainingTime===1/0)return;this._closeTimerStartTime=Date.now(),this._timerHandle=setTimeout(()=>{this._toast.onAutoClose?.(this._toast),this.dismiss()},this._remainingTime)}pause(){if(this._paused||this._remainingTime===1/0)return;if(this._paused=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;if(this._lastCloseTimerStartTime<this._closeTimerStartTime){let t=Date.now()-this._closeTimerStartTime;this._remainingTime=Math.max(0,this._remainingTime-t)}this._lastCloseTimerStartTime=Date.now()}resume(){if(!this._paused||this._remainingTime===1/0)return;this._paused=!1,this.startTimer()}startSpinner(){if(this._spinnerHandle||!this._spinnerConfig)return;let{frames:t,interval:e}=this._spinnerConfig;this._spinnerHandle=setInterval(()=>{this._spinnerFrameIndex=(this._spinnerFrameIndex+1)%t.length;let o=t[this._spinnerFrameIndex];if(this._iconText&&o)this._iconText.content=o,this.requestRender()},e)}stopSpinner(){if(this._spinnerHandle)clearInterval(this._spinnerHandle),this._spinnerHandle=null}dismiss(){if(this._dismissed)return;if(this._dismissed=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),this._toast.onDismiss?.(this._toast),At.dismiss(this._toast.id),setTimeout(()=>{this._onRemove?.(this._toast)},Af)}updateToast(t){this._toast=t;let e=Xi(t.type,this._toastOptions,t.style);if(this._computedStyle=e,e.borderColor)this.borderColor=e.borderColor;if(e.customBorderChars)this.customBorderChars=e.customBorderChars;let o=e.iconColor??e.borderColor;if(this._iconText){let i=t.icon??(this._icons===!1?void 0:cr(t.type,this._icons));if(i)this._iconText.content=i;if(o)this._iconText.fg=Bf(o)}if(this._titleText){let i=typeof t.title==="function"?t.title():t.title;if(i)this._titleText.content=i}if(this._descriptionText){let i=typeof t.description==="function"?t.description():t.description;if(i)this._descriptionText.content=i}let n=this._spinnerHandle!==null,r=t.type==="loading";if(n&&!r)this.stopSpinner(),this._spinnerConfig=null;else if(!n&&r){if(this._icons!==!1)this._spinnerConfig=fr(this._icons.loading);this.startSpinner()}if(t.type!=="loading"){if(this._timerHandle)clearTimeout(this._timerHandle);if(this._remainingTime=Zi(t.type,this._toastOptions,t.duration),this._remainingTime!==1/0)this.startTimer()}this.requestRender()}get toast(){return this._toast}get isDismissed(){return this._dismissed}destroy(){if(this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),super.destroy()}},Yi=class extends ln{_options={};_toastRenderables=new Map;_unsubscribe=null;constructor(t,e={}){super(t,{id:"toaster",flexDirection:"column",gap:1,zIndex:9999});this._options=e,this.applyLayoutOptions(),this.subscribe()}applyLayoutOptions(){let t=this._options.position??"bottom-right",e=Jf(t,this._options.offset??{}),o=kf(t);if(Object.assign(this,e),super.gap=this._options.gap??1,!o)super.maxWidth=this._options.maxWidth??Qi}isToastPosition(t){return t==="top-left"||t==="top-center"||t==="top-right"||t==="bottom-left"||t==="bottom-center"||t==="bottom-right"}set position(t){if(this.isToastPosition(t))this._options.position=t,this.applyLayoutOptions();else super.position=t}set offset(t){this._options.offset=t,this.applyLayoutOptions()}set gap(t){this._options.gap=t,super.gap=t}set visibleToasts(t){this._options.visibleToasts=t}set closeButton(t){this._options.closeButton=t}set icons(t){this._options.icons=t}set stackingMode(t){this._options.stackingMode=t}set maxWidth(t){this._options.maxWidth=t,super.maxWidth=t}set toastOptions(t){this._options.toastOptions=t}subscribe(){this._unsubscribe=At.subscribe((t)=>{if("dismiss"in t&&t.dismiss)this.removeToast(t.id);else this.addOrUpdateToast(t)})}addOrUpdateToast(t){let e=this._toastRenderables.get(t.id);if(e){e.updateToast(t);return}if((this._options.stackingMode??"single")==="single")for(let[n]of this._toastRenderables)this.removeToast(n);else{let n=this._options.visibleToasts??3,r=this._toastRenderables.size;if(r>=n){let i=r-n+1,s=Array.from(this._toastRenderables.keys());for(let c=0;c<i;c++){let f=s[c];if(f!==void 0)this.removeToast(f)}}}let o=new Vf(this.ctx,{toast:t,icons:this._options.icons,toastOptions:this._options.toastOptions,closeButton:this._options.closeButton,onRemove:(n)=>this.handleToastRemoved(n)});if(this._toastRenderables.set(t.id,o),zf(this._options.position??"bottom-right"))this.add(o);else this.add(o,0);this.requestRender()}removeToast(t){let e=this._toastRenderables.get(t);if(e)e.dismiss()}handleToastRemoved(t){let e=this._toastRenderables.get(t.id);if(e)this._toastRenderables.delete(t.id),this.remove(e.id),e.destroy(),this.requestRender()}get toastCount(){return this._toastRenderables.size}dismissAll(){for(let[t]of this._toastRenderables)this.removeToast(t)}destroy(){this._unsubscribe?.();for(let[,t]of this._toastRenderables)t.destroy();this._toastRenderables.clear(),super.destroy()}}});import{createElement as Hm,extend as Kf,spread as Nm}from"@opentui/solid";var hr=N(()=>{ts();Kf({toaster:Yi})});function os(t){let[e,o]=v("list"),[n,r]=v(0),[i,s]=v(null),[c,f]=v(!1),[a,h]=v(!1),[u,d]=v(!1),[g,x]=v(new Set),[m,b]=v(!1),S=(it)=>{let st=new Set(g());if(st.has(it))st.delete(it);else st.add(it);x(st)},E=(it)=>{x(new Set(it))},y=(it)=>{let st=new Set(it),G=g(),ot=new Set;for(let et of G)if(st.has(et))ot.add(et);if(ot.size!==G.size)x(ot)},R=()=>{x(new Set)};return React.createElement(es.Provider,{value:{activeTab:e,setActiveTab:o,selectedWorktreeIndex:n,setSelectedWorktreeIndex:r,selectedWorktreePath:i,setSelectedWorktreePath:s,showRemove:c,setShowRemove:f,showCommandPalette:a,setShowCommandPalette:h,showDetailView:u,setShowDetailView:d,repoPath:()=>t.repoPath,repoPaths:()=>t.repoPaths,selectedWorktrees:g,toggleWorktreeSelection:S,selectAllNonMain:E,pruneSelectedWorktrees:y,clearSelection:R,showBulkActions:m,setShowBulkActions:b}},t.children)}function Et(){let t=eo(es);if(!t)throw Error("useApp must be used within AppProvider");return t}var es;var ie=N(()=>{Rt();es=to()});var Gt,jo,ur,_o;var Zt=N(()=>{Gt=class Gt extends Error{exitCode;stderr;command;constructor(t,e,o,n){super(t);this.exitCode=e;this.stderr=o;this.command=n;this.name="GitError"}};jo=class jo extends Error{installed;required;constructor(t,e){super(`git version ${t} is below minimum required ${e}`);this.installed=t;this.required=e;this.name="GitVersionError"}};ur=class ur extends Error{branch;reason;constructor(t,e,o){super(t);this.branch=e;this.reason=o;this.name="ArchiveError"}};_o=class _o extends Error{path;reason;constructor(t,e,o){super(t);this.path=e;this.reason=o;this.name="ImportError"}}});async function Qt(t,e,o){let n=Array(t.length),r=0;async function i(){while(r<t.length){let c=r++;n[c]=await o(t[c])}}let s=Array.from({length:Math.min(e,t.length)},()=>i());return await Promise.all(s),n}import{resolve as ns,dirname as Xf}from"path";import{mkdirSync as Zf,existsSync as Qf}from"fs";function To(t){let e=hn.get(t);if(!e)return;if(Date.now()>e.expires){hn.delete(t);return}return e.data}function se(t,e,o=Yf){return hn.set(t,{data:e,expires:Date.now()+o}),e}function Mt(){hn.clear()}class M{static gitVersionChecked=!1;static async run(t,e){let o=Bun.spawn(["git",...t],{cwd:e??Bun.cwd,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw new Gt(`git ${t[0]} failed: ${r.trim()}`,i,r.trim(),`git ${t.join(" ")}`);return n.trim()}static async exec(t,e){return this.run(t,e)}static async checkVersion(){if(this.gitVersionChecked)return;let e=(await this.run(["--version"])).match(/git version (\d+)\.(\d+)\.?((\d+)?)/);if(!e)throw Error("Cannot parse git version");let[,o,n]=e.map(Number);if(o<2||o===2&&n<17)throw new jo(`${o}.${n}`,"2.17");this.gitVersionChecked=!0}static async list(t){await this.checkVersion();let e=t??Bun.cwd,o=await this.getMainRepoPath(e).catch(()=>e),n=`list:${o}`,r=To(n);if(r)return r;let i=o.split("/").pop()??"",s=await this.run(["worktree","list","--porcelain"],e),c=this.parsePorcelain(s,i,o),f=await Qt(c,10,async(a)=>({...a,isDirty:await this.isDirty(a.path).catch(()=>!1)}));return se(n,f)}static async listAll(t){await this.checkVersion();let e=new Set,o=[];for(let r of t){let i=ns(r);if(!e.has(i))e.add(i),o.push(i)}return(await Qt(o,5,async(r)=>{try{return await this.list(r)}catch{return[]}})).flat()}static parsePorcelain(t,e,o){let n=t.trim();if(!n)return[];return n.split(/\n\n+/).filter(Boolean).map((i,s)=>{let c=i.split(`
4
- `),f=c.find((b)=>b.startsWith("worktree ")),a=c.find((b)=>b.startsWith("HEAD ")),h=c.find((b)=>b.startsWith("branch ")),u=c.find((b)=>b.startsWith("locked")),d=f?.slice(9)??"",g=a?.slice(5)??"",x=null;if(h)x=h.slice(7).replace(/^refs\/heads\//,"");let m=u&&u.startsWith("locked ")?u.slice(7):void 0;return{path:d,branch:x,head:g,isMain:s===0,isDirty:!1,isLocked:Boolean(u),lockReason:m,repoName:e,repoPath:o}})}static async add(t,e,o,n){await this.checkVersion();let r=Xf(e);if(!Qf(r))Zf(r,{recursive:!0});let s=!await this.localBranchExists(t,n),c=["worktree","add",e,t];if(s)c=["worktree","add","-b",t,e,o?.base??"HEAD"];await this.run(c,n),Mt()}static async localBranchExists(t,e){try{return await this.run(["rev-parse","--verify",`refs/heads/${t}`],e??Bun.cwd),!0}catch{return!1}}static async remove(t,e,o){await this.checkVersion();let n=["worktree","remove",t];if(e?.force)n.push("--force");await this.run(n,o),Mt()}static async move(t,e,o){await this.checkVersion(),await this.run(["worktree","move",t,e],o),Mt()}static async prune(t){await this.checkVersion(),await this.run(["worktree","prune"],t),Mt()}static async isWorktree(t){let e=t??Bun.cwd;try{let o=await this.run(["rev-parse","--git-dir"],e),n=await this.run(["rev-parse","--git-common-dir"],e);return o!==n&&!o.endsWith("/.git")&&!o.endsWith("\\.git")}catch{return!1}}static async getMainRepoPath(t){let e=t??Bun.cwd,o=await this.run(["rev-parse","--git-common-dir"],e),n=ns(e,o);return n.endsWith("/.git")?n.slice(0,-5):n}static async getBranchForWorktree(t){try{let e=await this.run(["rev-parse","--abbrev-ref","HEAD"],t);return e==="HEAD"?null:e}catch{return null}}static async isDirty(t){try{return(await this.run(["status","--porcelain"],t??Bun.cwd)).length>0}catch{return!1}}static async getAheadBehind(t,e){let o=e??Bun.cwd,n=`ahead-behind:${o}:${t}`,r=To(n);if(r)return r;try{let i=await this.run(["rev-parse","--abbrev-ref",`${t}@{upstream}`],o),s=await this.run(["rev-list","--left-right","--count",`${i}...${t}`],o),[c,f]=s.split(/\s+/).map(Number);return se(n,{ahead:f??0,behind:c??0})}catch{return se(n,{ahead:0,behind:0})}}static async getLastCommit(t){let e=t??Bun.cwd,o=`last-commit:${e}`,n=To(o);if(n!==void 0)return n;try{let r=await this.run(["log","-1","--format=%h\x1F%s\x1F%cr"],e);if(!r)return se(o,null);let[i,s,c]=r.split("\x1F");return se(o,{hash:i??"",message:s??"",relativeDate:c??""})}catch{return se(o,null)}}static async getDirtyCount(t){let e=t??Bun.cwd,o=`dirty-count:${e}`,n=To(o);if(n!==void 0)return n;try{let r=await this.run(["status","--porcelain"],e);if(!r)return se(o,0);return se(o,r.split(`
5
- `).filter(Boolean).length)}catch{return se(o,0)}}static async unlock(t,e){await this.checkVersion(),await this.run(["worktree","unlock",t],e),Mt()}static async isMergedInto(t,e,o){try{return(await this.run(["branch","--merged",e],o??Bun.cwd)).split(`
6
- `).some((r)=>r.trim().replace(/^[*+] /,"")===t)}catch{return!1}}static async getDefaultRemote(t){try{return await this.run(["config","checkout.defaultRemote"],t??Bun.cwd)||"origin"}catch{return"origin"}}static async remoteBranchExists(t,e,o){let n=e??await this.getDefaultRemote(o);try{return await this.run(["rev-parse","--verify",`refs/remotes/${n}/${t}`],o??Bun.cwd),!0}catch{return!1}}static async listBranches(t){let e=t??Bun.cwd,o=`branches:${e}`,n=To(o);if(n)return n;let[r,i]=await Promise.all([this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/heads/"],e).catch(()=>""),this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/remotes/"],e).catch(()=>"")]),s=[];for(let c of r.split(`
7
- `).filter(Boolean)){let[f,a]=c.split("\x1F");s.push({name:f??"",isRemote:!1,lastCommitDate:a??""})}for(let c of i.split(`
8
- `).filter(Boolean)){let[f,a]=c.split("\x1F");if(!f||f.endsWith("/HEAD"))continue;let h=f.replace(/^[^/]+\//,"");if(s.some((u)=>u.name===h))continue;s.push({name:h,isRemote:!0,lastCommitDate:a??""})}return se(o,s)}static async diffBetween(t,e,o,n){let r=["diff"];if(o?.stat)r.push("--stat");if(o?.nameOnly)r.push("--name-only");return r.push(t,e),this.run(r,n)}static async getWorktreeLastActivity(t){try{let e=await this.run(["log","-1","--format=%ci"],t);return e?new Date(e):null}catch{return null}}static async setUpstream(t,e,o){let n=e??await this.getDefaultRemote(o),r=o??Bun.cwd;try{if(await this.run(["config",`branch.${t}.remote`],r))return}catch{}await this.run(["branch",`--set-upstream-to=${n}/${t}`,t],r)}}var Yf=3000,hn;var ct=N(()=>{Zt();hn=new Map});function is(t){let[e,{refetch:o}]=vi(async()=>{try{if(t.repoPaths.length<=1)return await M.list(t.repoPaths[0]);return await M.listAll(t.repoPaths)}catch(s){throw s}}),n=()=>{Mt(),o()},r=re(()=>{let s=e()??[],c=new Set,f=[];for(let a of s)if(!c.has(a.repoName))c.add(a.repoName),f.push(a.repoName);return f}),i=re(()=>r().length>1);return React.createElement(rs.Provider,{value:{worktrees:()=>e(),refetch:n,loading:()=>e.loading,error:()=>e.error,repoNames:r,isMultiRepo:i}},t.children)}function Ot(){let t=eo(rs);if(!t)throw Error("useGit must be used within GitProvider");return t}var rs;var me=N(()=>{Rt();ct();rs=to()});var tl,un,ss,el,pn,l;var Ht=N(()=>{Rt();tl={opencode:{bg:{base:"#090909",surface:"#111111",elevated:"#1a1a1a",overlay:"#000000"},border:{default:"#2a2a2a",active:"#4fc3f7",subtle:"#1e1e1e"},text:{primary:"#e8e8e8",secondary:"#666666",accent:"#4fc3f7",success:"#4ade80",warning:"#fbbf24",error:"#f87171",selected:"#ffffff"},tab:{active:"#4fc3f7",activeBg:"#1a1a1a",inactive:"#555555",inactiveBg:"#000000"},select:{focusedBg:"#1a2a3a",focusedFg:"#4fc3f7",selectedBg:"#161616",selectedFg:"#e8e8e8",normalFg:"#e8e8e8",descFg:"#666666"}},"tokyo-night":{bg:{base:"#1a1b26",surface:"#1f2335",elevated:"#24283b",overlay:"#0d1117"},border:{default:"#3b4261",active:"#7aa2f7",subtle:"#292e42"},text:{primary:"#c0caf5",secondary:"#565f89",accent:"#7aa2f7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",selected:"#ffffff"},tab:{active:"#7aa2f7",activeBg:"#24283b",inactive:"#565f89",inactiveBg:"#1a1b26"},select:{focusedBg:"#283457",focusedFg:"#7aa2f7",selectedBg:"#2a2f44",selectedFg:"#c0caf5",normalFg:"#c0caf5",descFg:"#565f89"}},dracula:{bg:{base:"#282a36",surface:"#21222c",elevated:"#343746",overlay:"#191a21"},border:{default:"#6272a4",active:"#bd93f9",subtle:"#44475a"},text:{primary:"#f8f8f2",secondary:"#6272a4",accent:"#bd93f9",success:"#50fa7b",warning:"#ffb86c",error:"#ff5555",selected:"#ffffff"},tab:{active:"#bd93f9",activeBg:"#343746",inactive:"#6272a4",inactiveBg:"#282a36"},select:{focusedBg:"#44475a",focusedFg:"#bd93f9",selectedBg:"#383a4a",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#6272a4"}},nord:{bg:{base:"#2e3440",surface:"#3b4252",elevated:"#434c5e",overlay:"#242933"},border:{default:"#4c566a",active:"#81a1c1",subtle:"#3b4252"},text:{primary:"#eceff4",secondary:"#4c566a",accent:"#81a1c1",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",selected:"#ffffff"},tab:{active:"#88c0d0",activeBg:"#434c5e",inactive:"#4c566a",inactiveBg:"#2e3440"},select:{focusedBg:"#3b4252",focusedFg:"#88c0d0",selectedBg:"#3b4252",selectedFg:"#eceff4",normalFg:"#eceff4",descFg:"#4c566a"}},catppuccin:{bg:{base:"#1e1e2e",surface:"#181825",elevated:"#313244",overlay:"#11111b"},border:{default:"#45475a",active:"#cba6f7",subtle:"#313244"},text:{primary:"#cdd6f4",secondary:"#585b70",accent:"#cba6f7",success:"#a6e3a1",warning:"#fab387",error:"#f38ba8",selected:"#ffffff"},tab:{active:"#cba6f7",activeBg:"#313244",inactive:"#585b70",inactiveBg:"#1e1e2e"},select:{focusedBg:"#313244",focusedFg:"#cba6f7",selectedBg:"#313244",selectedFg:"#cdd6f4",normalFg:"#cdd6f4",descFg:"#585b70"}},"github-dark":{bg:{base:"#0d1117",surface:"#161b22",elevated:"#21262d",overlay:"#010409"},border:{default:"#30363d",active:"#58a6ff",subtle:"#21262d"},text:{primary:"#e6edf3",secondary:"#484f58",accent:"#58a6ff",success:"#3fb950",warning:"#d29922",error:"#f85149",selected:"#ffffff"},tab:{active:"#58a6ff",activeBg:"#21262d",inactive:"#484f58",inactiveBg:"#0d1117"},select:{focusedBg:"#1f2937",focusedFg:"#58a6ff",selectedBg:"#1f2937",selectedFg:"#e6edf3",normalFg:"#e6edf3",descFg:"#484f58"}},"one-dark":{bg:{base:"#282c34",surface:"#21252b",elevated:"#2c313a",overlay:"#1b1f27"},border:{default:"#3e4451",active:"#61afef",subtle:"#2c313a"},text:{primary:"#abb2bf",secondary:"#5c6370",accent:"#61afef",success:"#98c379",warning:"#e5c07b",error:"#e06c75",selected:"#ffffff"},tab:{active:"#61afef",activeBg:"#2c313a",inactive:"#5c6370",inactiveBg:"#282c34"},select:{focusedBg:"#2c313a",focusedFg:"#61afef",selectedBg:"#2c313a",selectedFg:"#abb2bf",normalFg:"#abb2bf",descFg:"#5c6370"}},monokai:{bg:{base:"#272822",surface:"#1e1f1c",elevated:"#3e3d32",overlay:"#1a1b18"},border:{default:"#49483e",active:"#a6e22e",subtle:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#75715e",accent:"#66d9ef",success:"#a6e22e",warning:"#e6db74",error:"#f92672",selected:"#ffffff"},tab:{active:"#a6e22e",activeBg:"#3e3d32",inactive:"#75715e",inactiveBg:"#272822"},select:{focusedBg:"#3e3d32",focusedFg:"#66d9ef",selectedBg:"#3e3d32",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#75715e"}},"github-light":{bg:{base:"#ffffff",surface:"#f6f8fa",elevated:"#eaeef2",overlay:"#d0d7de"},border:{default:"#d0d7de",active:"#0969da",subtle:"#eaeef2"},text:{primary:"#1f2328",secondary:"#656d76",accent:"#0969da",success:"#1a7f37",warning:"#9a6700",error:"#cf222e",selected:"#000000"},tab:{active:"#0969da",activeBg:"#eaeef2",inactive:"#656d76",inactiveBg:"#ffffff"},select:{focusedBg:"#ddf4ff",focusedFg:"#0969da",selectedBg:"#eaeef2",selectedFg:"#1f2328",normalFg:"#1f2328",descFg:"#656d76"}}},un=["opencode","tokyo-night","dracula","nord","catppuccin","github-dark","one-dark","monokai","github-light"],ss={opencode:"OpenCode","tokyo-night":"Tokyo Night",dracula:"Dracula",nord:"Nord",catppuccin:"Catppuccin Mocha","github-dark":"GitHub Dark","one-dark":"One Dark",monokai:"Monokai","github-light":"GitHub Light"},[el,pn]=v("opencode"),l=new Proxy({},{get(t,e){return new Proxy({},{get(o,n){return tl[el()][e]?.[n]}})}})});import{readFileSync as ol,statSync as nl}from"fs";import{join as cs,resolve as rl}from"path";function Go(t){let e=cs(t,".git"),o=nl(e,{throwIfNoEntry:!1});if(!o||o.isDirectory())return e;let r=ol(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim();return rl(t,r)}function ce(t,e){return cs(Go(t),e)}var We=()=>{};import{existsSync as il,mkdirSync as sl,readFileSync as cl,writeFileSync as al}from"fs";import{dirname as fl}from"path";function as(t){return ce(t,"omw-focus")}function ho(t,e){let o=as(t);sl(fl(o),{recursive:!0}),al(o,e.join(`
9
- `),{encoding:"utf-8",mode:384})}function Yt(t){let e=as(t);if(!il(e))return null;return cl(e,"utf-8").split(/\r?\n/).filter(Boolean)}var xe=N(()=>{We()});import{existsSync as dr,mkdirSync as ll,readFileSync as hl,writeFileSync as ul,unlinkSync as pl}from"fs";import{dirname as dl}from"path";function pr(t){return t.replace(/\//g,"-").replace(/[^a-zA-Z0-9._-]/g,"_")}async function ge(t){let e=Bun.spawn(["tmux",...t],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C"}}),[o,n,r]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text(),e.exited]);if(r!==0)throw new uo(`tmux ${t[0]} failed: ${n.trim()}`,n.trim());return o.trim()}function De(t,e){let o=pr(e??fs),n=pr(t);return`${o}_${n}`}function mr(t){return ce(t,"omw-session")}function ml(t,e){let o=mr(t);ll(dl(o),{recursive:!0}),ul(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}function Vt(t){let e=mr(t);if(!dr(e))return null;try{return JSON.parse(hl(e,"utf-8"))}catch{return null}}function xr(t){let e=mr(t);if(dr(e))pl(e)}async function po(){try{return await Bun.spawn(["tmux","-V"],{stdout:"pipe",stderr:"pipe"}).exited===0}catch{return!1}}function gr(){return Boolean(Bun.env.TMUX)}async function we(t){try{return await ge(["has-session","-t",t]),!0}catch{return!1}}async function xl(t,e,o){if(await we(t))throw new uo(`Session '${t}' already exists`,"session_exists");if(!dr(e))throw new uo(`Worktree path does not exist: ${e}`,"path_not_found");let n=o?.windows??[],r=n[0],i=["new-session","-d","-s",t,"-c",e];if(r)i.push("-n",r.name);if(await ge(i),r?.command)await ge(["send-keys","-t",`${t}:${r.name}`,r.command,"Enter"]);for(let s=1;s<n.length;s++){let c=n[s];if(await ge(["new-window","-t",t,"-n",c.name,"-c",e]),c.command)await ge(["send-keys","-t",`${t}:${c.name}`,c.command,"Enter"])}if(n.length>0)await ge(["select-window","-t",`${t}:${n[0].name}`])}async function wr(t){if(!await we(t))return;await ge(["kill-session","-t",t])}async function dn(t){if(!await we(t))throw new uo(`Session '${t}' does not exist`,"session_not_found");if(gr())await ge(["switch-client","-t",t]);else if(await Bun.spawn(["tmux","attach-session","-t",t],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw new uo(`Failed to attach to session '${t}'`,"attach_failed")}async function br(t){let e=pr(t??fs);try{let o=await ge(["list-sessions","-F","#{session_name}|#{session_windows}|#{session_attached}|#{session_created}"]);if(!o)return[];return o.split(`
10
- `).filter(Boolean).filter((n)=>n.startsWith(`${e}_`)||n.startsWith(`${e}:`)).map((n)=>{let[r,i,s,c]=n.split("|");return{name:r??"",windows:parseInt(i??"0",10),attached:s==="1",created:c??""}})}catch{return[]}}async function mn(t,e,o){let n=De(t,o?.prefix),r=o?.attach??!0;if(await we(n)){if(r)await dn(n);return n}if(await xl(n,e,o?.layout),ml(e,{name:n,branch:t,worktreePath:e,createdAt:new Date().toISOString(),layout:o?.layoutName}),r)await dn(n);return n}async function xn(t,e,o){let n=De(t,o),r=await we(n);if(r)await wr(n);return xr(e),r}var uo,fs="omw";var Fe=N(()=>{We();uo=class uo extends Error{reason;constructor(t,e){super(t);this.reason=e;this.name="SessionError"}}});import{useTerminalDimensions as gl}from"@opentui/solid";function ls(t){let e=Ot(),o=gl(),n=()=>o().width,r=()=>o().height,[i,s]=v(null),[c,f]=v(!0),[a,h]=v(""),u;an(()=>{if(u)clearTimeout(u)});let d=()=>{return(e.worktrees()??[]).find((it)=>it.isMain)?.branch??"main"};de(Ye(()=>t.worktree.path,(y)=>{if(u)clearTimeout(u);if(!y){s(null),h(""),f(!1);return}s(null),h(""),f(!0),u=setTimeout(async()=>{if(t.worktree.path!==y)return;try{let[R,it,st]=await Promise.all([bl(y),t.worktree.branch&&!t.worktree.isMain?M.diffBetween(d(),t.worktree.branch,{stat:!0},y).catch(()=>""):Promise.resolve(""),t.worktree.branch?M.getAheadBehind(t.worktree.branch,y):Promise.resolve({ahead:0,behind:0})]);if(t.worktree.path!==y)return;let G=null;try{G=Yt(y)}catch{}let ot=null,et=Vt(y);if(et){let le=await we(et.name).catch(()=>!1);ot={meta:et,active:le}}if(t.worktree.path!==y)return;s({commits:R,diffStat:it,aheadBehind:st,focus:G,session:ot}),h("")}catch(R){if(t.worktree.path!==y)return;s(null),h(R.message)}finally{if(t.worktree.path===y)f(!1)}},wl)}));let g=()=>{let y=t.worktree;if(y.isLocked)return"\uD83D\uDD12 locked";if(y.isDirty)return"\u25CF dirty";return"\u2713 clean"},x=()=>{let y=t.worktree;if(y.isLocked)return l.text.warning;if(y.isDirty)return l.text.error;return l.text.success},m=()=>{let y=i();if(!y)return"";let R=[];if(y.aheadBehind.ahead>0)R.push(`\u2191${y.aheadBehind.ahead}`);if(y.aheadBehind.behind>0)R.push(`\u2193${y.aheadBehind.behind}`);return R.length>0?R.join(" "):"\u2713 up to date"},b=()=>{let y=i();if(!y)return l.text.secondary;return y.aheadBehind.ahead||y.aheadBehind.behind?l.text.warning:l.text.success},S=()=>{let y=i();if(!y||!y.diffStat)return[];return y.diffStat.split(`
11
- `).filter(Boolean)},E=()=>"\u2500".repeat(Math.max(n()-7,10));return React.createElement("box",{x:0,y:0,width:n(),height:r(),backgroundColor:l.bg.base},React.createElement("scrollbox",{x:2,y:1,width:n()-3,height:r()-3},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Worktree Detail"),React.createElement("text",{x:17,y:0,fg:l.text.secondary},"(Esc to close)")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},t.worktree.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},t.worktree.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Status")),React.createElement("text",{fg:x()},g())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"HEAD")),React.createElement("text",{fg:l.text.secondary},t.worktree.head?.slice(0,8))),React.createElement(O,{when:c()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Loading details..."))),React.createElement(O,{when:!c()&&!!a()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},`Failed to load details: ${a()}`))),React.createElement(O,{when:!c()&&!a()&&!!i()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Upstream")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Sync")),React.createElement("text",{fg:b()},m())),React.createElement(O,{when:i().aheadBehind.ahead>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Ahead")),React.createElement("text",{fg:l.text.warning},`${i().aheadBehind.ahead} commit(s)`))),React.createElement(O,{when:i().aheadBehind.behind>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Behind")),React.createElement("text",{fg:l.text.warning},`${i().aheadBehind.behind} commit(s)`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Recent Commits")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement(O,{when:i().commits.length>0,fallback:React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"No commits found"))},React.createElement(St,{each:i().commits},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},y)))),React.createElement(O,{when:!t.worktree.isMain&&S().length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},`Diff vs ${d()}`)),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement(St,{each:S()},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},y)))),React.createElement(O,{when:i().focus&&i().focus.length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Focus Paths")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement(St,{each:i().focus},(y)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.primary},` \u2022 ${y}`)))),React.createElement(O,{when:i().session},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.accent,bold:!0},"Session")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Name")),React.createElement("text",{fg:l.text.primary},i().session.meta.name)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Status")),React.createElement("text",{fg:i().session.active?l.text.success:l.text.error},i().session.active?"\u25CF active":"\u25CB inactive")),React.createElement(O,{when:i().session.meta.layout},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Layout")),React.createElement("text",{fg:l.text.primary},i().session.meta.layout)))),React.createElement(O,{when:t.worktree.isMain},React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:te,height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Type")),React.createElement("text",{fg:l.text.accent},"main worktree")))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},E())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Esc:back d:delete o:open r:refresh"))))}async function bl(t){try{let e=Bun.spawn(["git","log","--oneline","-10"],{cwd:t,stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),o=await new Response(e.stdout).text();if(await e.exited,e.exitCode!==0)return[];return o.trim().split(`
12
- `).filter(Boolean)}catch{return[]}}var wl=150,te=16;var hs=N(()=>{Rt();me();Ht();xe();Fe();ct()});import{useKeyboard as Cl,useTerminalDimensions as $l}from"@opentui/solid";function us(){let t=Et(),e=Ot(),o=$l(),n=()=>{let b=e.worktrees()??[],S=t.selectedWorktreePath();if(S){let E=b.find((y)=>y.path===S);if(E)return E}return b[t.selectedWorktreeIndex()]},r=()=>o().width,i=()=>o().height,s=14,[c,f]=v(null),[a,h]=v(!1),[u,d]=v(""),g;an(()=>{if(g)clearTimeout(g)}),de(Ye(()=>n()?.path,(b)=>{if(g)clearTimeout(g);if(!b){f(null),h(!1),d("");return}f(null),h(!0),d(""),g=setTimeout(async()=>{let S=n();if(!S||S.path!==b)return;try{let[E,y,R]=await Promise.all([S.branch?M.getAheadBehind(S.branch,S.path):Promise.resolve({ahead:0,behind:0}),M.getLastCommit(S.path),M.getDirtyCount(S.path)]);if(n()?.path===b)f({aheadBehind:E,lastCommit:y,dirtyCount:R}),d("")}catch(E){if(n()?.path===b)f(null),d(E.message)}finally{if(n()?.path===b)h(!1)}},Sl)}));let x=()=>{if(a())return"Loading...";if(u())return"Unavailable";let b=c();if(!b)return"";let S=[];if(b.aheadBehind.ahead>0)S.push(`\u2191${b.aheadBehind.ahead}`);if(b.aheadBehind.behind>0)S.push(`\u2193${b.aheadBehind.behind}`);return S.length>0?S.join(" "):"\u2713 up to date"},m=()=>{let b=n();if(!b)return"";if(b.isLocked)return"\uD83D\uDD12 locked";let S=c();if(S&&S.dirtyCount>0)return`\u25CF ${S.dirtyCount} file(s) dirty`;if(b.isDirty)return"\u25CF dirty";return"\u2713 clean"};return Cl((b)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let S=b.name;if(S==="x"&&t.selectedWorktrees().size>0){t.setShowBulkActions(!0);return}if(S==="return"&&!t.showDetailView()&&n()){t.setShowDetailView(!0);return}if(S==="escape"&&t.showDetailView()){t.setShowDetailView(!1);return}}),React.createElement("box",{width:"100%",height:"100%",backgroundColor:l.bg.base},React.createElement(O,{when:t.showDetailView()&&!!n()},React.createElement(ls,{worktree:n()})),React.createElement(O,{when:!t.showDetailView()},React.createElement(O,{when:e.loading()},React.createElement("text",{x:2,y:2,fg:l.text.secondary},"Loading worktrees...")),React.createElement(O,{when:!e.loading()&&!!e.error()},React.createElement("text",{x:2,y:2,fg:l.text.error},"Error: ",e.error()?.message),React.createElement("text",{x:2,y:3,fg:l.text.secondary},"Not in a git repository?")),React.createElement(O,{when:!e.loading()&&!e.error()&&!!n()},React.createElement("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:l.bg.surface,paddingX:2,paddingY:1},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("text",{fg:l.text.accent},"Worktree Details")),React.createElement("box",{height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement(O,{when:e.isMultiRepo()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Repo")),React.createElement("text",{fg:l.text.warning},n()?.repoName))),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},n()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},n()?.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Status")),React.createElement("text",{fg:n()?.isDirty?l.text.error:n()?.isLocked?l.text.warning:l.text.success},m())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Sync")),React.createElement("text",{fg:u()?l.text.error:a()?l.text.secondary:c()?.aheadBehind?.ahead||c()?.aheadBehind?.behind?l.text.warning:l.text.success},x())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"HEAD")),React.createElement("text",{fg:l.text.secondary},n()?.head?.slice(0,8))),React.createElement(O,{when:c()?.lastCommit},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Last Commit")),React.createElement("text",{fg:l.text.primary},c().lastCommit.relativeDate)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"")),React.createElement("text",{fg:l.text.secondary},c().lastCommit.message.length>50?c().lastCommit.message.slice(0,47)+"...":c().lastCommit.message))),React.createElement(O,{when:(()=>{let b=Yt(n()?.path??"");return b&&b.length>0})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},Yt(n()?.path??"")?.join(", ")??""))),React.createElement(O,{when:(()=>{return!!Vt(n()?.path??"")})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Session")),React.createElement("text",{fg:l.text.accent},(()=>{let b=Vt(n()?.path??"");if(!b)return"";return b.layout?`${b.name} [${b.layout}]`:b.name})()))),React.createElement(O,{when:n()?.isMain},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Type")),React.createElement("text",{fg:l.text.accent},"main worktree"))),React.createElement("box",{height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:detail"),React.createElement("text",{fg:l.text.secondary},"d:delete"),React.createElement("text",{fg:l.text.secondary},"a:add"),React.createElement("text",{fg:l.text.secondary},"o:open"),React.createElement("text",{fg:l.text.secondary},"r:refresh"),React.createElement("text",{fg:l.text.secondary},"^P:commands")))),React.createElement(O,{when:!e.loading()&&!e.error()&&!n()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.secondary},"No worktree selected."),React.createElement("text",{fg:l.text.accent},"Press 'a' to create one.")))))}var Sl=150;var ps=N(()=>{Rt();ie();me();Ht();xe();Fe();ct();hs()});import{join as Cr,resolve as gn}from"path";import*as Be from"fs";function ae(t,e,o){if(!Array.isArray(t)||t.some((n)=>typeof n!=="string"))o.push({field:e,message:"Must be an array of strings"})}function gs(){let e=Bun.env.XDG_CONFIG_HOME??Cr(Bun.env.HOME??"~",".config");return Cr(e,"oh-my-worktree")}function Nt(){return Cr(gs(),"config.json")}function No(t){let e=[];if(typeof t!=="object"||t===null)return e.push({field:"root",message:"Config must be a JSON object"}),e;let o=t;if(!("version"in o))e.push({field:"version",message:"Required field 'version' is missing"});else if(o.version!==1)e.push({field:"version",message:`Expected version 1, got ${JSON.stringify(o.version)}`});for(let n of Object.keys(o))if(!Pl.has(n))e.push({field:n,message:`Unknown field '${n}'`});if("defaults"in o&&o.defaults!==void 0)if(typeof o.defaults!=="object"||o.defaults===null)e.push({field:"defaults",message:"Must be an object"});else{let n=o.defaults;for(let r of Object.keys(n))if(!yl.has(r))e.push({field:`defaults.${r}`,message:`Unknown field '${r}'`});if("worktreeDir"in n&&typeof n.worktreeDir!=="string")e.push({field:"defaults.worktreeDir",message:"Must be a string"});if("autoUpstream"in n&&typeof n.autoUpstream!=="boolean")e.push({field:"defaults.autoUpstream",message:"Must be a boolean"});for(let r of["copyFiles","linkFiles","postCreate","postRemove"])if(r in n)ae(n[r],`defaults.${r}`,e);if("sharedDeps"in n&&n.sharedDeps!==void 0)if(typeof n.sharedDeps!=="object"||n.sharedDeps===null)e.push({field:"defaults.sharedDeps",message:"Must be an object"});else ds(n.sharedDeps,"defaults.sharedDeps",e)}if("repos"in o&&o.repos!==void 0)if(!Array.isArray(o.repos))e.push({field:"repos",message:"Must be an array"});else for(let n=0;n<o.repos.length;n++){let r=o.repos[n],i=`repos[${n}]`;if(typeof r!=="object"||r===null){e.push({field:i,message:"Must be an object"});continue}let s=r;for(let c of Object.keys(s))if(!El.has(c))e.push({field:`${i}.${c}`,message:`Unknown field '${c}'`});if(!("path"in s)||typeof s.path!=="string")e.push({field:`${i}.path`,message:"Required string field 'path' is missing"});if("worktreeDir"in s&&typeof s.worktreeDir!=="string")e.push({field:`${i}.worktreeDir`,message:"Must be a string"});if("autoUpstream"in s&&typeof s.autoUpstream!=="boolean")e.push({field:`${i}.autoUpstream`,message:"Must be a boolean"});for(let c of["copyFiles","linkFiles","postCreate","postRemove"])if(c in s)ae(s[c],`${i}.${c}`,e);if("sharedDeps"in s&&s.sharedDeps!==void 0)if(typeof s.sharedDeps!=="object"||s.sharedDeps===null)e.push({field:`${i}.sharedDeps`,message:"Must be an object"});else ds(s.sharedDeps,`${i}.sharedDeps`,e);if("monorepo"in s&&s.monorepo!==void 0)if(typeof s.monorepo!=="object"||s.monorepo===null)e.push({field:`${i}.monorepo`,message:"Must be an object"});else{let c=s.monorepo;for(let f of Object.keys(c))if(!Rl.has(f))e.push({field:`${i}.monorepo.${f}`,message:`Unknown field '${f}'`});if("autoDetect"in c&&typeof c.autoDetect!=="boolean")e.push({field:`${i}.monorepo.autoDetect`,message:"Must be a boolean"});if("extraPatterns"in c&&c.extraPatterns!==void 0)ae(c.extraPatterns,`${i}.monorepo.extraPatterns`,e);if("hooks"in c&&c.hooks!==void 0)if(!Array.isArray(c.hooks))e.push({field:`${i}.monorepo.hooks`,message:"Must be an array"});else for(let f=0;f<c.hooks.length;f++){let a=c.hooks[f];if(typeof a!=="object"||a===null){e.push({field:`${i}.monorepo.hooks[${f}]`,message:"Must be an object"});continue}if(!("glob"in a)||typeof a.glob!=="string")e.push({field:`${i}.monorepo.hooks[${f}].glob`,message:"Required string field"});if("copyFiles"in a&&a.copyFiles!==void 0)ae(a.copyFiles,`${i}.monorepo.hooks[${f}].copyFiles`,e);if("linkFiles"in a&&a.linkFiles!==void 0)ae(a.linkFiles,`${i}.monorepo.hooks[${f}].linkFiles`,e);if("postCreate"in a&&a.postCreate!==void 0)ae(a.postCreate,`${i}.monorepo.hooks[${f}].postCreate`,e);if("postRemove"in a&&a.postRemove!==void 0)ae(a.postRemove,`${i}.monorepo.hooks[${f}].postRemove`,e)}}}if("templates"in o&&o.templates!==void 0)if(typeof o.templates!=="object"||o.templates===null||Array.isArray(o.templates))e.push({field:"templates",message:"Must be an object (key-value map)"});else{let n=o.templates;for(let[r,i]of Object.entries(n)){let s=`templates.${r}`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i;for(let f of Object.keys(c))if(!Ml.has(f))e.push({field:`${s}.${f}`,message:`Unknown field '${f}'`});if("worktreeDir"in c&&typeof c.worktreeDir!=="string")e.push({field:`${s}.worktreeDir`,message:"Must be a string"});if("base"in c&&typeof c.base!=="string")e.push({field:`${s}.base`,message:"Must be a string"});if("autoUpstream"in c&&typeof c.autoUpstream!=="boolean")e.push({field:`${s}.autoUpstream`,message:"Must be a boolean"});for(let f of["copyFiles","linkFiles","postCreate","postRemove"])if(f in c)ae(c[f],`${s}.${f}`,e)}}if("lifecycle"in o&&o.lifecycle!==void 0)if(typeof o.lifecycle!=="object"||o.lifecycle===null)e.push({field:"lifecycle",message:"Must be an object"});else{let n=o.lifecycle;for(let r of Object.keys(n))if(!Ol.has(r))e.push({field:`lifecycle.${r}`,message:`Unknown field '${r}'`});if("autoCleanMerged"in n&&typeof n.autoCleanMerged!=="boolean")e.push({field:"lifecycle.autoCleanMerged",message:"Must be a boolean"});if("staleAfterDays"in n&&(typeof n.staleAfterDays!=="number"||n.staleAfterDays<1))e.push({field:"lifecycle.staleAfterDays",message:"Must be a positive number"});if("maxWorktrees"in n&&(typeof n.maxWorktrees!=="number"||n.maxWorktrees<1))e.push({field:"lifecycle.maxWorktrees",message:"Must be a positive number"})}if("sessions"in o&&o.sessions!==void 0)if(typeof o.sessions!=="object"||o.sessions===null)e.push({field:"sessions",message:"Must be an object"});else{let n=o.sessions;for(let r of Object.keys(n))if(!Wl.has(r))e.push({field:`sessions.${r}`,message:`Unknown field '${r}'`});for(let r of["enabled","autoCreate","autoKill"])if(r in n&&typeof n[r]!=="boolean")e.push({field:`sessions.${r}`,message:"Must be a boolean"});if("prefix"in n&&typeof n.prefix!=="string")e.push({field:"sessions.prefix",message:"Must be a string"});if("defaultLayout"in n&&typeof n.defaultLayout!=="string")e.push({field:"sessions.defaultLayout",message:"Must be a string"});if("layouts"in n&&n.layouts!==void 0)if(typeof n.layouts!=="object"||n.layouts===null||Array.isArray(n.layouts))e.push({field:"sessions.layouts",message:"Must be an object (key-value map)"});else{let r=n.layouts;for(let[i,s]of Object.entries(r)){let c=`sessions.layouts.${i}`;if(typeof s!=="object"||s===null){e.push({field:c,message:"Must be an object"});continue}let f=s;if(!("windows"in f)||!Array.isArray(f.windows))e.push({field:`${c}.windows`,message:"Required array field"});else for(let a=0;a<f.windows.length;a++){let h=f.windows[a];if(typeof h!=="object"||h===null){e.push({field:`${c}.windows[${a}]`,message:"Must be an object"});continue}if(!("name"in h)||typeof h.name!=="string")e.push({field:`${c}.windows[${a}].name`,message:"Required string field"});if("command"in h&&typeof h.command!=="string")e.push({field:`${c}.windows[${a}].command`,message:"Must be a string"})}}}if("defaultLayout"in n&&typeof n.defaultLayout==="string"&&"layouts"in n&&typeof n.layouts==="object"&&n.layouts!==null){let r=n.layouts;if(!(n.defaultLayout in r))e.push({field:"sessions.defaultLayout",message:`Layout '${n.defaultLayout}' does not exist in sessions.layouts`})}}if("profiles"in o&&o.profiles!==void 0)if(typeof o.profiles!=="object"||o.profiles===null||Array.isArray(o.profiles))e.push({field:"profiles",message:"Must be an object (key-value map)"});else{let n=o.profiles;for(let[r,i]of Object.entries(n)){let s=`profiles.${r}`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i;for(let f of Object.keys(c))if(!Dl.has(f))e.push({field:`${s}.${f}`,message:`Unknown field '${f}'`})}}if("activeProfile"in o&&o.activeProfile!==void 0){if(typeof o.activeProfile!=="string")e.push({field:"activeProfile",message:"Must be a string"});else if("profiles"in o&&o.profiles!==void 0&&typeof o.profiles==="object"&&o.profiles!==null&&!Array.isArray(o.profiles)){let n=o.profiles;if(!(o.activeProfile in n))e.push({field:"activeProfile",message:`Profile '${o.activeProfile}' does not exist in profiles`})}else if(!("profiles"in o)||o.profiles===void 0)e.push({field:"activeProfile",message:"Cannot set activeProfile without profiles"})}return e}function ds(t,e,o){let n=new Set(["strategy","paths","invalidateOn"]);for(let r of Object.keys(t))if(!n.has(r))o.push({field:`${e}.${r}`,message:`Unknown field '${r}'`});if("strategy"in t&&!["hardlink","symlink","copy"].includes(t.strategy))o.push({field:`${e}.strategy`,message:'Must be "hardlink", "symlink", or "copy"'});if("paths"in t)ae(t.paths,`${e}.paths`,o);if("invalidateOn"in t)ae(t.invalidateOn,`${e}.invalidateOn`,o)}function Ho(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function no(t){if(Array.isArray(t))return t.map((e)=>no(e));if(Ho(t)){let e={};for(let[o,n]of Object.entries(t))e[o]=no(n);return e}return t}function ws(t,e){if(e===void 0)return no(t);if(Array.isArray(e))return e.map((r)=>no(r));if(!Ho(e))return no(e);let o=Ho(t)?t:{},n={};for(let[r,i]of Object.entries(o))n[r]=no(i);for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let s=o[r];if(Ho(s)&&Ho(i)){n[r]=ws(s,i);continue}n[r]=no(i)}return n}function Fl(t){if(!t.activeProfile)return structuredClone(t);let e=t.profiles?.[t.activeProfile];if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Active profile '${t.activeProfile}' does not exist`);return ws(t,e)}function Y(t){let e=t??Nt();if(!Be.existsSync(e))return structuredClone(xs);let o;try{let s=wn.readFileSync(e,"utf-8");o=JSON.parse(s)}catch(s){let c=s.message;if(c.includes("JSON"))throw Error(`Invalid JSON in config file: ${c}`);if(s instanceof SyntaxError)throw Error(`Invalid JSON in config file: ${c}`);throw Error(`Failed to read config file: ${c}`)}let n=No(o);if(n.length>0){let s=n.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed: ${s}`)}let r=Fl(o),i=No(r);if(i.length>0){let s=i.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed after applying activeProfile: ${s}`)}return r}function Lt(t,e){let o=gn(e),n=t.repos?.find((r)=>gn(r.path)===o);return{worktreeDir:n?.worktreeDir??t.defaults?.worktreeDir??mo.worktreeDir,copyFiles:n?.copyFiles??t.defaults?.copyFiles??mo.copyFiles,linkFiles:n?.linkFiles??t.defaults?.linkFiles??mo.linkFiles,postCreate:n?.postCreate??t.defaults?.postCreate??mo.postCreate,postRemove:n?.postRemove??t.defaults?.postRemove??mo.postRemove,autoUpstream:n?.autoUpstream??t.defaults?.autoUpstream??mo.autoUpstream,monorepo:n?.monorepo,sharedDeps:n?.sharedDeps??t.defaults?.sharedDeps}}function Le(t){return(t.repos??[]).map((e)=>gn(e.path))}function bn(t,e){let o=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,o).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}function fe(t){let e=t??Nt(),o=t?gn(e,".."):gs();if(!Be.existsSync(o))wn.mkdirSync(o,{recursive:!0,mode:448});if(Be.existsSync(e))return e;return Jo(e,`${JSON.stringify(xs,null,2)}
13
- `),e}function Cn(t,e){return t.templates?.[e]}function $n(t,e){return{worktreeDir:e.worktreeDir??t.worktreeDir,copyFiles:e.copyFiles??t.copyFiles,linkFiles:e.linkFiles??t.linkFiles,postCreate:e.postCreate??t.postCreate,postRemove:e.postRemove??t.postRemove,autoUpstream:e.autoUpstream??t.autoUpstream,monorepo:t.monorepo,sharedDeps:t.sharedDeps}}function Ae(t){return t.sessions??{}}function Sn(t,e){let o=t.sessions;if(!o?.layouts)return;let n=e??o.defaultLayout;if(!n)return;return o.layouts[n]}function Jo(t,e){let o=`${t}.tmp.${Date.now()}`;try{Be.writeFileSync(o,e,{encoding:"utf-8",mode:384});let n=JSON.parse(e),r=No(n);if(r.length>0)throw Error(`Validation failed: ${r.map((i)=>i.message).join("; ")}`);wn.renameSync(o,t)}catch(n){if(Be.existsSync(o))wn.unlinkSync(o);throw n}}var wn,ms="~/.omw/worktrees/{repo}-{branch}",xs,mo,Pl,yl,El,Rl,Ml,Ol,Wl,Dl;var $t=N(()=>{wn=Be,xs={version:1,defaults:{worktreeDir:ms,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0},repos:[]},mo={worktreeDir:ms,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0,sharedDeps:void 0};Pl=new Set(["version","defaults","repos","$schema","theme","templates","lifecycle","sessions","profiles","activeProfile"]),yl=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","sharedDeps"]),El=new Set(["path","worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","monorepo","sharedDeps"]),Rl=new Set(["autoDetect","extraPatterns","hooks"]),Ml=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","base"]),Ol=new Set(["autoCleanMerged","staleAfterDays","maxWorktrees"]),Wl=new Set(["enabled","autoCreate","autoKill","prefix","defaultLayout","layouts"]),Dl=new Set(["defaults","repos","theme","templates","lifecycle","sessions"])});import*as Bl from"fs";import{join as Ie,resolve as be,dirname as ko}from"path";function go(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=Ie(be(t),r),s=Ie(be(e),r);if(!Ce(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping copy: ${r}`);continue}if(Ce(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping copy: ${r}`);continue}try{xo(ko(s),{recursive:!0}),Cs(i,s),n.copied.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to copy ${r}: ${c.message}`)}}return n}function wo(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=be(Ie(be(t),r)),s=Ie(be(e),r);if(!Ce(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping symlink: ${r}`);continue}if(Ce(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping symlink: ${r}`);continue}try{xo(ko(s),{recursive:!0}),$s(i,s),n.linked.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to symlink ${r}: ${c.message}`)}}return n}function Ss(t,e,o=0){let n=0,r=[];if(o>jl)return{linked:0,errors:[`Max directory depth exceeded at ${t}`]};let i=be(t),s=be(e);if(!Ce(i))return{linked:0,errors:[`Source not found: ${t}`]};let c=Il(i,{throwIfNoEntry:!1});if(!c||!c.isDirectory())try{return xo(ko(s),{recursive:!0}),bs(i,s),{linked:1,errors:[]}}catch(f){return{linked:0,errors:[`Failed to hardlink ${t}: ${f.message}`]}}if(!Ce(s))xo(s,{recursive:!0});try{let f=Al(i,{withFileTypes:!0});for(let a of f){let h=Ie(i,a.name),u=Ie(s,a.name);if(a.isDirectory()){let d=Ss(h,u,o+1);if(n+=d.linked,d.errors.length>0)r.push(...d.errors)}else if(a.isFile()){if(Ce(u))continue;try{bs(h,u),n++}catch(d){try{Cs(h,u),n++}catch(g){r.push(`Failed to link/copy ${a.name}: ${g.message}`)}}}}}catch(f){r.push(`Failed to read directory ${t}: ${f.message}`)}return{linked:n,errors:r}}function Ps(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]},r=o.paths??[],i=o.strategy??"symlink";for(let s of r){let c=Ie(be(t),s),f=Ie(be(e),s);if(!Ce(c)){n.skipped.push(s),n.warnings.push(`Source not found, skipping shared dep: ${s}`);continue}if(Ce(f)){n.skipped.push(s);continue}try{if(i==="symlink")xo(ko(f),{recursive:!0}),$s(c,f),n.linked.push(s);else if(i==="hardlink"){let a=Ss(c,f);if(a.linked>0)n.linked.push(s);for(let h of a.errors)n.warnings.push(h)}else xo(ko(f),{recursive:!0}),Ll(c,f,{recursive:!0}),n.copied.push(s)}catch(a){n.skipped.push(s),n.warnings.push(`Failed to share dep ${s}: ${a.message}`)}}return n}var Cs,Ll,Ce,$s,Ix,bs,Al,Il,xo,jl=30;var Pn=N(()=>{({copyFileSync:Cs,cpSync:Ll,existsSync:Ce,symlinkSync:$s,unlinkSync:Ix,linkSync:bs,readdirSync:Al,statSync:Il,mkdirSync:xo}=Bl)});import{existsSync as _l,mkdirSync as Tl}from"fs";async function Wt(t,e){let o=e.timeout??30000;for(let n of t)await Gl(n,e.cwd,o,e.env??{},e.onOutput)}async function Gl(t,e,o,n,r){if(!_l(e))Tl(e,{recursive:!0});let i;try{i=Bun.spawn(["sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}catch(a){if(a.code!=="ENOENT")throw a;i=Bun.spawn(["/bin/sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}let s=!1,c=setTimeout(()=>{s=!0,i.kill()},o),f=i.stderr?new Response(i.stderr).text():Promise.resolve("");try{if(r&&i.stdout){let h=i.stdout.getReader(),u=new TextDecoder,d=[];while(!0){let{done:x,value:m}=await h.read();if(x)break;let S=u.decode(m,{stream:!0}).split(`
14
- `);if(S.length===1)d.push(S[0]);else{d.push(S[0]);let E=d.join("");if(d.length=0,E)r(E);for(let R=1;R<S.length-1;R++)if(S[R])r(S[R]);let y=S[S.length-1];if(y)d.push(y)}}let g=d.join("")+u.decode();if(g)r(g)}let a=await i.exited;if(s)throw new Co(t,o);if(a!==0){let h=(await f).trim();throw new bo(t,a,h)}}finally{clearTimeout(c)}}var bo,Co;var $e=N(()=>{bo=class bo extends Error{command;exitCode;stderr;constructor(t,e,o){super(`Hook command failed (exit ${e}): ${t}
15
- ${o}`);this.command=t;this.exitCode=e;this.stderr=o;this.name="HookError"}};Co=class Co extends Error{command;timeoutMs;constructor(t,e){super(`Hook command timed out after ${e}ms: ${t}`);this.command=t;this.timeoutMs=e;this.name="HookTimeoutError"}}});import{existsSync as Hl,readdirSync as Hx,readFileSync as Nx,statSync as Nl}from"fs";import{join as Jl,relative as kx}from"path";function yn(t,e){let o=[],n=[];for(let r of e){let i=r.trim();if(!i){n.push(i);continue}let s=Jl(t,i);try{if(Hl(s)&&Nl(s).isDirectory())o.push(i);else n.push(i)}catch{n.push(i)}}return{valid:o,invalid:n}}var $r=()=>{};function ro(t,e){return t.map((o)=>{let n=new Bun.Glob(o.glob),r=e.filter((i)=>n.match(i));return{glob:o.glob,matchedPaths:r,copyFiles:o.copyFiles??[],linkFiles:o.linkFiles??[],postCreate:o.postCreate??[],postRemove:o.postRemove??[]}}).filter((o)=>o.matchedPaths.length>0)}function kl(t,e){return t.replace(/\{packagePath\}/g,e.packagePath).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}async function $o(t,e,o){for(let n of t){let r=n[e],i=e==="postCreate"&&n.copyFiles.length>0,s=e==="postCreate"&&n.linkFiles.length>0,c=r.length>0;if(!i&&!s&&!c)continue;for(let f of n.matchedPaths){let{join:a}=await import("path"),h=a(o.mainRepoPath,f),u=a(o.cwd,f);if(i){let d=go(h,u,n.copyFiles);for(let g of d.copied)o.onOutput?.(`Copied ${f}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(s){let d=wo(h,u,n.linkFiles);for(let g of d.linked)o.onOutput?.(`Linked ${f}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(c){let d=r.map((x)=>kl(x,{packagePath:f,repo:o.repo,branch:o.branch})),g={...o.env??{},OMW_FOCUS_PATHS:o.focusPaths.join(","),OMW_PACKAGE_PATH:f};await Wt(d,{cwd:o.cwd,timeout:o.timeout,env:g,onOutput:o.onOutput})}}}}var En=N(()=>{$e();Pn()});import{useTerminalDimensions as zl}from"@opentui/solid";function je(t){let e=zl(),o=()=>Math.max(0,Math.floor((e().width-t.width)/2)),n=()=>Math.max(0,Math.floor((e().height-t.height)/2)),r=()=>React.createElement("box",{x:o(),y:n(),width:t.width,height:t.height,border:!0,borderStyle:"rounded",borderColor:t.borderColor??l.border.active,backgroundColor:t.backgroundColor??l.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:t.gap??0,title:t.title,titleAlignment:"left",position:"absolute"},t.children,React.createElement(O,{when:t.footer},t.footer));return React.createElement(O,{when:t.backdrop,fallback:r()},React.createElement("box",{x:0,y:0,width:e().width,height:e().height,backgroundColor:t.backdropColor??l.bg.overlay,position:"absolute"},r()))}var zo=N(()=>{Rt();Ht()});import{useKeyboard as vl,useTerminalDimensions as Ul}from"@opentui/solid";import{basename as ys,resolve as Vl}from"path";function Es(){let t=Et(),e=Ot(),o=Ul(),[n,r]=v("input"),[i,s]=v(""),[c,f]=v(""),[a,h]=v("branch"),[u,d]=v(""),[g,x]=v([]),[m,b]=v(""),[S,E]=v([]),[y,R]=v(-1),[it,st]=v(!1),G=()=>{let k=i().toLowerCase();if(!k)return S().slice(0,10);return S().filter((T)=>T.name.toLowerCase().includes(k)).slice(0,10)};de(Ye(()=>et(),async()=>{try{let k=et(),T=await M.listBranches(k);E(T)}catch{E([])}})),de(Ye(i,()=>{R(-1),st(i().length>0&&G().length>0)}));let ot=(k,T)=>{x((Z)=>Z.map((dt,A)=>A===k?{...dt,...T}:dt))},et=()=>{let k=e.worktrees()??[],T=t.selectedWorktreePath();return(T?k.find((dt)=>dt.path===T)??k[t.selectedWorktreeIndex()]:k[t.selectedWorktreeIndex()])?.repoPath??t.repoPath()},le=()=>{let k=e.worktrees()??[],T=t.selectedWorktreePath();return(T?k.find((dt)=>dt.path===T)??k[t.selectedWorktreeIndex()]:k[t.selectedWorktreeIndex()])?.repoName??t.repoPath().split("/").pop()??""},_=()=>{let k=i();if(!k)return"";let T=et(),Z=Y(),dt=Lt(Z,T),A=k.replace(/\//g,"-"),ee=ys(T);return Vl(bn(dt.worktreeDir,{repo:ee,branch:A}))};vl(async(k)=>{if(t.activeTab()!=="add")return;if(t.showCommandPalette())return;let T=k.name;if(T==="escape"){if(n()==="preview"){r("input");return}t.setActiveTab("list"),s(""),f(""),h("branch"),r("input");return}if(n()==="input"){if(T==="tab"){if(it()&&a()==="branch")st(!1),R(-1);h((Z)=>Z==="branch"?"focus":"branch");return}if(a()==="branch"&&it()&&G().length>0){if(T==="down"||k.sequence==="\x1B[B"){R((Z)=>Math.min(Z+1,G().length-1));return}if(T==="up"||k.sequence==="\x1B[A"){R((Z)=>Math.max(Z-1,-1));return}}if(T==="return"||T==="enter"){if(a()==="branch"&&y()>=0){let Z=G()[y()];if(Z){s(Z.name),st(!1),R(-1);return}}if(!i())return;st(!1),d(_()),r("preview");return}if(T==="backspace"){if(a()==="branch")s((Z)=>Z.slice(0,-1));else f((Z)=>Z.slice(0,-1));return}if(k.sequence==="\x15"||k.ctrl&&T==="u"){if(a()==="branch")s("");else f("");return}if(k.sequence==="\x17"||k.ctrl&&T==="w"){if(a()==="branch")s((Z)=>Z.replace(/\S+\s*$/,""));else f((Z)=>Z.replace(/\S+\s*$/,""));return}if(k.sequence&&k.sequence.length===1&&k.sequence.charCodeAt(0)>=32)if(a()==="branch")s((Z)=>Z+k.sequence);else f((Z)=>Z+k.sequence)}if(n()==="preview"){if(T==="return"||T==="enter"){r("creating");let Z=i(),dt=u(),A=et(),ee=ys(A);try{let Se=Y(),F=Lt(Se,A),nt=[{label:"Creating worktree",status:"pending"}];if(F.autoUpstream)nt.push({label:"Setting upstream",status:"pending"});if(F.copyFiles.length>0)nt.push({label:"Copying files",status:"pending"});if(F.linkFiles.length>0)nt.push({label:"Creating symlinks",status:"pending"});if(F.postCreate.length>0)nt.push({label:"Running hooks",status:"pending"});let pt=c(),U=[];if(pt)U=pt.split(/[,\s]+/).map((rt)=>rt.trim()).filter(Boolean);if(U.length>0)nt.push({label:"Setting focus",status:"pending"});if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){if(ro(F.monorepo.hooks,U).length>0)nt.push({label:"Running monorepo hooks",status:"pending"})}x(nt);let Q=0;if(ot(Q,{status:"running"}),await M.add(Z,dt,{createBranch:!0},A),ot(Q,{status:"done"}),Q++,F.autoUpstream){ot(Q,{status:"running"});try{let rt=await M.getDefaultRemote(A);if(await M.remoteBranchExists(Z,rt,A))await M.setUpstream(Z,rt,A),ot(Q,{status:"done",message:`\u2192 ${rt}/${Z}`});else ot(Q,{status:"done",message:"no remote branch"})}catch(rt){ot(Q,{status:"error",message:rt.message})}Q++}if(F.copyFiles.length>0)ot(Q,{status:"running"}),go(A,dt,F.copyFiles),ot(Q,{status:"done"}),Q++;if(F.linkFiles.length>0)ot(Q,{status:"running"}),wo(A,dt,F.linkFiles),ot(Q,{status:"done"}),Q++;let ft={OMW_BRANCH:Z,OMW_WORKTREE_PATH:dt,OMW_REPO_PATH:A};if(F.postCreate.length>0)ot(Q,{status:"running"}),await Wt(F.postCreate,{cwd:dt,env:ft,onOutput:(rt)=>ot(Q,{message:rt})}),ot(Q,{status:"done"}),Q++;if(U.length>0){ot(Q,{status:"running"});let{valid:rt}=yn(dt,U);if(U=rt,rt.length>0)ho(dt,rt),ft.OMW_FOCUS_PATHS=rt.join(",");ot(Q,{status:"done"}),Q++}if(U.length>0&&F.monorepo?.hooks&&F.monorepo.hooks.length>0){ot(Q,{status:"running"});let rt=ro(F.monorepo.hooks,U);if(rt.length>0)await $o(rt,"postCreate",{cwd:dt,env:ft,repo:ee,branch:Z,focusPaths:U,mainRepoPath:A,onOutput:(io)=>ot(Q,{message:io})});ot(Q,{status:"done"}),Q++}b("Worktree created successfully!"),r("done"),oo.success(`Worktree created: ${Z}`),e.refetch(),setTimeout(()=>{t.setActiveTab("list"),s(""),f(""),h("branch"),r("input")},1500)}catch(Se){oo.error(Se.message);let nt=g().findIndex((pt)=>pt.status==="running");if(nt>=0)ot(nt,{status:"error",message:Se.message});b(`${Se.message}`),r("error")}return}}if(n()==="error"){if(T==="escape"||T==="return"||T==="enter")r("input"),b("")}});let D=()=>o().width,L=()=>o().height,V=()=>Math.max(50,Math.min(80,D()-4)),tt=4,mt=()=>{if(n()==="input"){let k=it()&&a()==="branch"?G().length*2:0,T=i().length>0?4:0;return Math.max(21+tt,Math.min(21+tt+k+T,L()-4))}if(n()==="preview")return Math.max(13+tt,Math.min((c().length>0?15:13)+tt,L()-4));if(n()==="creating")return Math.max(9+tt,Math.min(g().length*2+7+tt,L()-4));if(n()==="done")return Math.max(11+tt,Math.min((c().length>0?15:13)+tt,L()-4));return Math.max(11+tt,Math.min(11+tt,L()-4))},q=()=>Math.max(V()-4,10),ut=()=>Math.max(q(),20);return React.createElement(je,{width:V(),height:mt(),borderColor:n()==="done"?l.text.success:n()==="error"?l.text.error:l.border.active,backgroundColor:l.bg.surface,gap:1,title:" Create Worktree ",footer:React.createElement(dg,null,React.createElement("box",{height:1,width:q()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(q(),1)))),React.createElement(O,{when:n()==="input"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Tab:switch"),React.createElement("text",{fg:l.text.secondary},"\u2191\u2193:pick"),React.createElement("text",{fg:l.text.secondary},"Enter:confirm"),React.createElement("text",{fg:l.text.secondary},"Esc:cancel"))),React.createElement(O,{when:n()==="preview"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:create"),React.createElement("text",{fg:l.text.secondary},"Esc:back"))),React.createElement(O,{when:n()==="creating"},React.createElement("text",{fg:l.text.secondary},"Creating worktree...")),React.createElement(O,{when:n()==="done"},React.createElement("text",{fg:l.text.secondary},"\u2713 Done \u2014 returning to list")),React.createElement(O,{when:n()==="error"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"Enter:retry"),React.createElement("text",{fg:l.text.secondary},"Esc:back"))))},React.createElement(O,{when:n()==="input"},React.createElement("box",{height:1,width:q(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"New Worktree"),React.createElement("text",{x:17,y:0,fg:l.text.secondary},le())),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(q())),React.createElement("text",{fg:a()==="branch"?l.text.accent:l.text.secondary},"Branch name"),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},i()),React.createElement(O,{when:a()==="branch"},React.createElement("text",{x:i().length+1,y:0,fg:l.text.accent},"\u2588"))),React.createElement(O,{when:it()&&a()==="branch"&&G().length>0},React.createElement(St,{each:G()},(k,T)=>React.createElement("box",{height:1,width:q(),backgroundColor:T()===y()?l.select.focusedBg:l.bg.surface},React.createElement("text",{x:1,y:0,fg:T()===y()?l.tab.active:l.text.primary},T()===y()?"\u25B8 ":" ",k.name),React.createElement("text",{x:Math.max(1+k.name.length+4,27),y:0,fg:l.text.secondary},k.isRemote?"(remote) ":"",k.lastCommitDate)))),React.createElement("text",{fg:l.text.secondary},"Tab to switch fields \xB7 \u2191\u2193 to select branch"),React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:a()==="focus"?l.text.accent:l.text.secondary},"Focus "),React.createElement("text",{fg:l.text.secondary},"(optional)")),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},c()),React.createElement(O,{when:a()==="focus"},React.createElement("text",{x:c().length+1,y:0,fg:l.text.accent},"\u2588"))),React.createElement("text",{fg:l.text.secondary},"comma-separated paths, e.g. apps/web,apps/api"),React.createElement(O,{when:i().length>0},React.createElement("text",{fg:l.text.secondary},"Target path"),React.createElement("text",{fg:l.text.primary},_())),React.createElement("text",{fg:l.text.primary},"Type a branch name, e.g. feature/my-feature")),React.createElement(O,{when:n()==="preview"},React.createElement("box",{height:1,width:q(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Confirm Worktree")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(q())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},u())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},c()))),React.createElement("text",{fg:l.text.success},"\u2713 Ready to create. Press Enter to confirm.")),React.createElement(O,{when:n()==="creating"},React.createElement("box",{height:1,width:q(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Creating Worktree")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(q())),React.createElement(St,{each:g()},(k)=>React.createElement("box",{height:1},React.createElement("text",{fg:k.status==="done"?l.text.success:k.status==="running"?l.text.accent:k.status==="error"?l.text.error:l.text.secondary},k.status==="done"?"\u2713":k.status==="running"?"\u27F3":k.status==="error"?"\u2717":"\u25CB"," ",k.label),React.createElement(O,{when:k.message},React.createElement("text",{x:k.label.length+4,y:0,fg:l.text.secondary},k.message))))),React.createElement(O,{when:n()==="done"},React.createElement("box",{height:1,width:q(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.success},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Worktree Created")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(q())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},u())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:l.text.secondary},"Focus")),React.createElement("text",{fg:l.text.accent},c()))),React.createElement("text",{fg:l.text.success},"\u2713 ",m())),React.createElement(O,{when:n()==="error"},React.createElement("box",{height:1,width:q(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.error},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},"Error")),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(q())),React.createElement("text",{fg:l.text.error},"\u2717 Failed"),React.createElement("box",{width:ut(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.primary},m().slice(0,Math.max(ut()-3,10)))),React.createElement("text",{fg:l.text.secondary},"Press Enter or Escape to try again")))}var Rs=N(()=>{Rt();ie();me();ct();$t();Pn();$e();xe();$r();En();hr();Ht();zo()});import{useKeyboard as Kl,useTerminalDimensions as ql}from"@opentui/solid";function Ms(){let t=Et(),e=Ot(),o=ql(),[n,r]=v(!1),[i,s]=v(""),[c,f]=v(!1),a=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((E)=>E.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},h=()=>{t.setShowRemove(!1),r(!1),s(""),f(!1)},u=async(m)=>{let b=a();if(!b){h();return}r(!0),s("Removing...");try{let S=Y(),E=Lt(S,b.repoPath);if(E.postRemove.length>0)s("Running postRemove hooks..."),await Wt(E.postRemove,{cwd:b.path,env:{OMW_BRANCH:b.branch??"",OMW_WORKTREE_PATH:b.path,OMW_REPO_PATH:b.repoPath}}).catch(()=>{});await M.remove(b.path,{force:m},b.repoPath),s("Removed successfully!"),oo.success("Worktree removed");let y=e.worktrees()??[],R=t.selectedWorktreeIndex(),it=y[R-1]??y[R+1]??null;if(R>0)t.setSelectedWorktreeIndex(R-1);else t.setSelectedWorktreeIndex(0);t.setSelectedWorktreePath(it?.path??null),e.refetch(),setTimeout(h,1000)}catch(S){let E=S.message;if(!m&&E.includes("dirty"))s("Worktree has changes. Press Enter to force remove."),r(!1),f(!0);else s(`Failed: ${E}`),r(!1),oo.error(`Failed: ${E}`)}};Kl(async(m)=>{if(!t.showRemove())return;if(t.showCommandPalette())return;let b=m.name;if(b==="escape"){h();return}if(c()&&(b==="return"||b==="enter")){f(!1),await u(!0);return}if((b==="return"||b==="enter")&&!n())await u(!1)});let d=()=>a(),g=()=>Math.max(50,Math.min(80,o().width-4)),x=()=>10;return React.createElement(je,{width:g(),height:x(),borderColor:l.border.active,backgroundColor:l.bg.elevated,gap:1,title:" Remove Worktree ",backdrop:!0,footer:React.createElement("box",{flexDirection:"column"},React.createElement(O,{when:!n()&&!c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"[Enter] Confirm"),React.createElement("text",{fg:l.text.secondary},"[Esc] Cancel"))),React.createElement(O,{when:c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"[Enter] Force remove"),React.createElement("text",{fg:l.text.secondary},"[Esc] Cancel"))))},React.createElement(O,{when:!!d()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:l.text.secondary},"Branch")),React.createElement("text",{fg:l.text.accent},d()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:l.text.secondary},"Path")),React.createElement("text",{fg:l.text.primary},d()?.path)),React.createElement(O,{when:c()},React.createElement("text",{fg:l.text.warning},i())),React.createElement(O,{when:n()},React.createElement("text",{fg:i().startsWith("Failed")?l.text.error:l.text.success},i()))),React.createElement(O,{when:!d()},React.createElement("text",{fg:l.text.secondary},"No worktree selected.")))}var Os=N(()=>{Rt();ie();me();ct();$t();$e();hr();Ht();zo()});function Ds(t){let[e,o]=v([]),n=(i)=>{o((s)=>s.filter((c)=>c.id!==i))},r=(i)=>{let s=`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`,c=i.duration??3000;o((f)=>[...f,{...i,id:s}].slice(-5)),setTimeout(()=>{n(s)},c)};return React.createElement(Ws.Provider,{value:{toasts:e,addToast:r,removeToast:n}},t.children)}function Rn(){let t=eo(Ws);if(!t)throw Error("useToast must be used within ToastProvider");return t}var Ws;var Mn=N(()=>{Rt();Ws=to()});import{useKeyboard as Xl}from"@opentui/solid";function Fs(t){let e=Et(),o=Ot(),n=Rn(),[r,i]=v("confirming"),[s,c]=v(""),[f,a]=v(0),h=()=>{let x=o.worktrees()??[],m=e.selectedWorktrees(),b=[];for(let S of m){let E=x.find((y)=>y.path===S);if(E&&!E.isMain)b.push({branch:E.branch??"(detached)",path:E.path,repoPath:E.repoPath})}return b},u=()=>{e.setShowBulkActions(!1),i("confirming"),c(""),a(0)},d=async()=>{let x=h();if(x.length===0){u();return}i("executing"),a(0);let m=[];for(let b=0;b<x.length;b++){let S=x[b];c(`Removing ${S.branch} (${b+1}/${x.length})...`),a(b);try{let E=Y(),y=Lt(E,S.repoPath);if(y.postRemove.length>0)await Wt(y.postRemove,{cwd:S.path,env:{OMW_BRANCH:S.branch,OMW_WORKTREE_PATH:S.path,OMW_REPO_PATH:S.repoPath}}).catch(()=>{});await M.remove(S.path,{force:!1},S.repoPath)}catch(E){m.push(`${S.branch}: ${E.message}`)}}if(Mt(),e.clearSelection(),e.setSelectedWorktreeIndex(0),e.setSelectedWorktreePath(null),o.refetch(),m.length>0)i("error"),c(`Failed: ${m.join("; ")}`),n.addToast({message:`Failed to remove ${m.length} worktree(s)`,type:"error"}),setTimeout(u,3000);else i("done"),c(`Removed ${x.length} worktree(s) successfully!`),n.addToast({message:`Removed ${x.length} worktrees`,type:"success"}),setTimeout(u,1500)};Xl(async(x)=>{if(!e.showBulkActions())return;if(e.showCommandPalette())return;let m=x.name;if(r()==="executing")return;if(m==="escape"){u();return}if((m==="return"||m==="enter")&&r()==="confirming")await d()});let g=()=>h().length;return React.createElement("box",{x:0,y:0,width:t.w,height:t.h,backgroundColor:l.bg.base},React.createElement("box",{x:2,y:1,width:t.w-3,height:t.h-2,flexDirection:"column",backgroundColor:l.bg.base},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},"Bulk Delete Worktrees")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.border.subtle},"\u2500".repeat(Math.max(t.w-5,10)))),React.createElement("box",{height:1}),React.createElement(O,{when:r()==="confirming"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.warning},`Delete ${g()} worktree(s)?`)),React.createElement("box",{height:1}),React.createElement(St,{each:h().slice(0,Math.max(t.h-10,5))},(x)=>React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.accent},`\u2022 ${x.branch}`))),React.createElement(O,{when:g()>Math.max(t.h-10,5)},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.secondary},`... and ${g()-Math.max(t.h-10,5)} more`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},"Enter:delete all Esc:cancel"))),React.createElement(O,{when:r()==="executing"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.warning},s())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.secondary},`Progress: ${f()+1}/${g()}`))),React.createElement(O,{when:r()==="done"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.success},s()))),React.createElement(O,{when:r()==="error"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:l.text.error},s())))))}var Bs=N(()=>{Rt();ie();Mn();me();ct();$t();$e();Ht()});import{useKeyboard as Zl,useTerminalDimensions as Ql}from"@opentui/solid";import{spawnSync as Yl}from"child_process";function Ls(){let t=Et(),e=Ql(),o=Nt(),n=()=>{try{return Y()}catch{return null}},[r,i]=v(n()),[s,c]=v("");Zl((h)=>{if(t.activeTab()!=="config")return;if(t.showCommandPalette())return;let u=h.name;if(u==="e"){let d=process.env.EDITOR??process.env.VISUAL??"vi";fe(),Yl(d,[o],{stdio:"inherit"}),i(n()),c("Config reloaded"),setTimeout(()=>c(""),2000)}if(u==="r")i(n()),c("Reloaded"),setTimeout(()=>c(""),2000);if(u==="i")fe(),i(n()),c("Config initialized"),setTimeout(()=>c(""),2000)});let f=()=>e().width,a=()=>e().height;return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:l.bg.base,flexDirection:"column"},React.createElement("box",{width:"100%",height:"100%",backgroundColor:l.bg.surface,flexDirection:"column",paddingX:2,paddingY:1},React.createElement("box",{height:1},React.createElement("text",{fg:l.text.accent},React.createElement("b",null,"Configuration"))),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:l.text.secondary},"Path:"),React.createElement("text",{fg:l.text.primary},o)),React.createElement(O,{when:!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.warning},"No config file found."),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:l.text.secondary},"Press"),React.createElement("text",{fg:l.text.accent},"i"),React.createElement("text",{fg:l.text.secondary},"to initialize with defaults.")))),React.createElement(O,{when:!!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.accent},"Defaults"),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"worktreeDir")),React.createElement("text",{fg:l.text.primary},r()?.defaults?.worktreeDir??"../{repo}-{branch}")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"copyFiles")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.copyFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"linkFiles")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.linkFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:l.text.secondary},"postCreate")),React.createElement("text",{fg:l.text.primary},"[",(r()?.defaults?.postCreate??[]).join(", "),"]"))),React.createElement("box",null,React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(f()-34,10)))),React.createElement(O,{when:(r()?.repos?.length??0)>0},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:l.text.accent},"Repos (",r()?.repos?.length,")"),React.createElement(St,{each:r()?.repos?.slice(0,4)},(h)=>React.createElement("box",{flexDirection:"column",gap:0},React.createElement("text",{fg:l.text.primary},h.path.split("/").pop()??h.path),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:l.text.secondary},"copyFiles")),React.createElement("text",{fg:l.text.primary},(h.copyFiles??[]).length>0?(h.copyFiles??[]).join(", "):"\u2014")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:l.text.secondary},"postCreate")),React.createElement("text",{fg:l.text.primary},(h.postCreate??[]).length>0?(h.postCreate??[]).join(", "):"\u2014")))))),React.createElement(O,{when:(r()?.repos?.length??0)===0},React.createElement("text",{fg:l.text.secondary},"No per-repo configs defined."))),React.createElement(O,{when:!!s()},React.createElement("text",{fg:l.text.success},s()))),React.createElement("box",{width:"100%",height:1,backgroundColor:l.bg.base,flexDirection:"row",gap:2},React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"e"),React.createElement("text",{fg:l.text.primary},":edit")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"r"),React.createElement("text",{fg:l.text.primary},":reload")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:l.text.secondary},"i"),React.createElement("text",{fg:l.text.primary},":init"))))}var As=N(()=>{Rt();ie();$t();Ht()});import{existsSync as Po,readdirSync as th,rmSync as eh}from"fs";import{basename as Sr,dirname as Pr,join as oh,resolve as So}from"path";function nh(t){let e=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,e)}function Is(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _s(t){if(!Po(Nt()))return[];let e=t.find((c)=>c.isMain);if(!e)return[];let o=Y(),n=So(e.path),r=Sr(n);return[o.repos?.find((c)=>So(c.path)===n)?.worktreeDir??o.defaults?.worktreeDir].filter((c)=>typeof c==="string").map((c)=>nh(c)).filter((c)=>!Pr(c).includes("{")&&Sr(c).includes("{")).map((c)=>{let f=Sr(c),a=`^${Is(f).replace(/\\\{repo\\\}/g,Is(r)).replace(/\\\{branch\\\}/g,".+")}$`,h=new RegExp(a);return{path:So(Pr(c)),matches:(u)=>h.test(u)}})}function Ts(t){let e=new Set;for(let o of t)if(!o.isMain)e.add(So(Pr(o.path)));return[...e]}function js(t,e,o,n){if(!Po(t))return;let r=th(t,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;if(n&&!n(i.name))continue;let s=So(oh(t,i.name));if(!e.has(s))o.add(s)}}function Gs(t){let e=new Set(t.map((r)=>So(r.path))),o=new Set,n=new Set;for(let r of _s(t))n.add(r.path),js(r.path,e,o,r.matches);for(let r of Ts(t)){if(n.has(r))continue;js(r,e,o)}return[...o]}function rh(t){return _s(t).some((e)=>Po(e.path))||Ts(t).some((e)=>Po(e))}async function ih(){let t=Bun.spawn(["git","--version"],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[e,o]=await Promise.all([new Response(t.stdout).text(),t.exited]);if(o!==0)return null;return e.trim().match(/git version (\d+\.\d+(?:\.\d+)?)/)?.[1]??null}async function sh(){try{return await M.checkVersion(),{name:"Git version",status:"pass",message:`${await ih()??"unknown"} (>= 2.17 required)`}}catch(e){if(e instanceof jo)return{name:"Git version",status:"fail",message:e.message};return{name:"Git version",status:"fail",message:`Check failed: ${e.message}`}}}async function ch(){try{let o=(Y().repos??[]).map((n)=>n.path).filter((n)=>!Po(n));if(o.length>0)return{name:"Configuration",status:"warn",message:"missing repository paths",detail:o};return{name:"Configuration",status:"pass",message:"valid"}}catch(e){return{name:"Configuration",status:"fail",message:`Check failed: ${e.message}`}}}function ah(t){let o=t.map((n)=>n.path).filter((n)=>!Po(n));if(o.length>0)return{name:"Stale worktrees",status:"warn",message:"missing worktree paths",detail:o};return{name:"Stale worktrees",status:"pass",message:"none"}}function fh(t){try{let o=Gs(t);if(o.length===0)return{name:"Orphaned directories",status:"pass",message:rh(t)?"none":"no worktree directory"};return{name:"Orphaned directories",status:"warn",message:"orphaned worktree directories found",detail:o}}catch(o){return{name:"Orphaned directories",status:"fail",message:`Check failed: ${o.message}`}}}function lh(t){let o=t.filter((r)=>r.isLocked);if(o.length===0)return{name:"Worktree locks",status:"pass",message:"all clear"};return{name:"Worktree locks",status:"warn",message:"locked worktrees present",detail:o.map((r)=>{let i=r.branch??"detached";if(!r.lockReason)return`${i} - ${r.path} (potential stale lock: no reason)`;return`${i} - ${r.path} (reason: ${r.lockReason})`})}}function hh(t){let o=t.filter((n)=>n.isDirty&&!n.isMain);if(o.length===0)return{name:"Dirty worktrees",status:"pass",message:"none"};return{name:"Dirty worktrees",status:"warn",message:"dirty non-main worktrees found",detail:o.map((n)=>`${n.branch??"detached"} - ${n.path}`)}}async function yo(t){let e=await M.list(t).catch(()=>[]),o=[await sh(),await ch(),ah(e),fh(e),lh(e),hh(e)];return{checks:o,healthy:o.every((n)=>n.status==="pass")}}async function uh(t){try{return await M.prune(t),{action:"Prune stale worktrees",success:!0}}catch(e){return{action:"Prune stale worktrees",success:!1,detail:e.message}}}async function ph(t){let e=[];try{let o=Gs(await M.list(t).catch(()=>[]));for(let n of o)try{eh(n,{recursive:!0,force:!0}),e.push({action:"Remove orphaned directory",success:!0,detail:n})}catch(r){e.push({action:"Remove orphaned directory",success:!1,detail:`${n}: ${r.message}`})}}catch(o){e.push({action:"Remove orphaned directories",success:!1,detail:o.message})}return e}async function dh(t){let e=[];try{let n=(await M.list(t)).filter((r)=>r.isLocked&&!r.lockReason);for(let r of n)try{await M.unlock(r.path,t),e.push({action:"Unlock stale lock",success:!0,detail:`${r.branch??"detached"} - ${r.path}`})}catch(i){e.push({action:"Unlock stale lock",success:!1,detail:`${r.path}: ${i.message}`})}}catch(o){e.push({action:"Fix stale locks",success:!1,detail:o.message})}return e}async function On(t){let e=[];return e.push(await uh(t)),e.push(...await ph(t)),e.push(...await dh(t)),e}var yr=N(()=>{$t();ct();Zt()});import{useKeyboard as mh,useTerminalDimensions as xh}from"@opentui/solid";function Hs(){let t=Et(),e=xh(),[o,n]=v(null),[r,i]=v(!0),[s,c]=v(""),[f,a]=v(!1),[h,u]=v([]),d=async()=>{i(!0),c(""),u([]);try{let G=await yo();n(G)}catch(G){c(G.message)}i(!1)},g=async()=>{if(o()?.healthy)return;a(!0);try{let G=await On();u(G);let ot=await yo();n(ot)}catch(G){c(G.message)}a(!1)};d(),mh((G)=>{if(t.activeTab()!=="doctor")return;if(t.showCommandPalette())return;let ot=G.name;if(ot==="r")d();if(ot==="f"&&!r()&&!f()&&!o()?.healthy)g()});let x=()=>e().width,m=()=>e().height,b=()=>Math.max(50,Math.min(80,x()-4)),S=()=>{let G=it()+st()+8+(st()>0?2:0);return Math.max(12,Math.min(G,m()-4))},E=()=>Math.max(b()-4,10),y=(G)=>{if(G==="pass")return"\u2713";if(G==="warn")return"\u26A0";return"\u2717"},R=(G)=>{if(G==="pass")return l.text.success;if(G==="warn")return l.text.warning;return l.text.error},it=()=>o()?.checks.length??0,st=()=>h().length;return React.createElement(je,{width:b(),height:S(),borderColor:o()?.healthy?l.text.success:o()?l.text.warning:l.border.default,backgroundColor:l.bg.surface,title:" Doctor ",footer:React.createElement(rw,null,React.createElement("box",{height:1,width:E()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(E(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"r:recheck"),React.createElement(O,{when:!o()?.healthy},React.createElement("text",{fg:l.text.secondary},"f:fix")),React.createElement("text",{fg:l.text.secondary},"Esc:back")))},React.createElement(O,{when:r()},React.createElement("text",{fg:l.text.secondary},"Running health checks...")),React.createElement(O,{when:f()},React.createElement("text",{fg:l.text.accent},"Running auto-fix...")),React.createElement(O,{when:!r()&&!f()&&!!s()},React.createElement("text",{fg:l.text.error},"Error: ",s())),React.createElement(O,{when:!r()&&!f()&&!s()&&!!o()},React.createElement("text",{fg:l.text.accent},"Health Checks"),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(E())),React.createElement(St,{each:o().checks},(G)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:R(G.status)},y(G.status)),React.createElement("text",{x:2,y:0,fg:l.text.primary},G.name,":"),React.createElement("text",{x:G.name.length+4,y:0,fg:l.text.secondary},G.message))}),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(E())),React.createElement("text",{fg:o().healthy?l.text.success:l.text.warning},o().healthy?"\u2713 All checks passed":`${o().checks.filter((G)=>G.status==="fail").length} error(s), ${o().checks.filter((G)=>G.status==="warn").length} warning(s) found`),React.createElement(O,{when:st()>0},React.createElement("text",{fg:l.text.accent},"Fix Results"),React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(E())),React.createElement(St,{each:h()},(G)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:G.success?l.text.success:l.text.error},G.success?"\u2713":"\u2717"),React.createElement("text",{x:2,y:0,fg:l.text.primary},G.action),React.createElement(O,{when:!!G.detail},React.createElement("text",{x:G.action.length+3,y:0,fg:l.text.secondary},"(",G.detail,")")))}))))}var Ns=N(()=>{Rt();ie();yr();Ht();zo()});var zs={};xt(zs,{writePin:()=>Rr,removePin:()=>Mr,readPin:()=>Uo,listPinnedWorktrees:()=>Or,isPinned:()=>_e});import{readFileSync as Js,writeFileSync as gh,unlinkSync as wh,mkdirSync as bh,existsSync as Er}from"fs";import{join as Ch,dirname as ks}from"path";function vo(t){return ce(t,"omw-pin")}function $h(t){let e=vo(t),o=ks(e),n=Ch(o,"HEAD"),r=Js(n,"utf-8").trim(),i=r.match(/^ref:\s+refs\/heads\/(.+)$/);return i?i[1]:r}function Rr(t,e){let o=vo(t),n={branch:$h(t),pinnedAt:new Date().toISOString(),...e?{reason:e}:{}};bh(ks(o),{recursive:!0}),gh(o,JSON.stringify(n),{encoding:"utf-8",mode:384})}function Uo(t){let e=vo(t);if(!Er(e))return null;return JSON.parse(Js(e,"utf-8"))}function Mr(t){let e=vo(t);if(!Er(e))return;wh(e)}function _e(t){return Er(vo(t))}function Or(t){return t.filter((e)=>_e(e.path))}var Eo=N(()=>{We()});import{useKeyboard as Sh}from"@opentui/solid";function vs(){let t=Et(),e=Ot(),o=()=>e.worktrees()??[],n=()=>t.selectedWorktreeIndex(),r=(h)=>{let u=Math.max(0,Math.min(h,Math.max(o().length-1,0))),d=o()[u];t.setSelectedWorktreeIndex(u),t.setSelectedWorktreePath(d?.path??null)},i=re(()=>{let h=o(),u=[],d=new Map;for(let m of h){let b=d.get(m.repoName);if(b)b.push(m);else d.set(m.repoName,[m])}let g=0,x=!0;for(let[m,b]of d){if(!x)u.push({type:"separator"});x=!1,u.push({type:"header",repoName:m});for(let S of b)u.push({type:"worktree",wt:S,flatIdx:g}),g++}return u}),s=()=>t.selectedWorktrees().size;Sh((h)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let u=h.name,d=o();if(u==="j"||u==="down")r(Math.min(n()+1,d.length-1));if(u==="k"||u==="up")r(Math.max(n()-1,0));if(u==="space"){let g=n(),x=d[g];if(x&&!x.isMain)t.toggleWorktreeSelection(x.path)}if(h.ctrl&&u==="a")t.selectAllNonMain(d.filter((g)=>!g.isMain).map((g)=>g.path))});let c=(h)=>{if(h.isLocked)return"\uD83D\uDD12";if(h.isDirty)return"\u25CF";return"\u2713"},f=(h)=>{if(h.isLocked)return l.text.warning;if(h.isDirty)return l.text.error;return l.text.success},a=(h,u)=>{let d=h.branch??"(detached)",g=Math.max(8,Vo-(u?9:7));return d.length>g?d.slice(0,g-1)+"\u2026":d};return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:l.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:0},React.createElement(O,{when:e.loading()},React.createElement("text",{fg:l.text.secondary},"Loading...")),React.createElement(O,{when:!e.loading()},React.createElement(St,{each:i()},(h)=>{if(h.type==="header")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.text.accent},React.createElement("b",null,h.repoName)));if(h.type==="separator")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Vo)));let u=h.wt,d=()=>h.flatIdx===n(),g=()=>t.selectedWorktrees().has(u.path);return React.createElement("box",{width:"100%",height:1,backgroundColor:d()?l.select.focusedBg:g()?l.bg.elevated:l.bg.surface,paddingX:1,onMouseDown:()=>r(h.flatIdx)},React.createElement("text",{x:0,y:0,fg:f(u)},c(u)),React.createElement("text",{x:2,y:0,fg:d()?l.tab.active:l.text.primary},a(u,!1)),React.createElement(O,{when:g()},React.createElement("text",{x:Vo-1,y:0,fg:l.text.accent},"\u2713")),React.createElement(O,{when:!!Vt(u.path)},React.createElement("text",{x:Vo-(g()?3:1),y:0,fg:l.text.accent},"S")),React.createElement(O,{when:_e(u.path)},React.createElement("text",{x:Vo-(g()?5:3)+(Vt(u.path)?0:2),y:0,fg:l.text.warning},"P")))}),React.createElement(O,{when:s()>0},React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:l.text.accent},`Selected: ${s()}`)))))}var Vo=24;var Us=N(()=>{Rt();ie();me();Ht();Eo();Fe()});import{useKeyboard as Ph,useTerminalDimensions as yh}from"@opentui/solid";function Vs(){let t=Et(),e=Ot(),o=yh(),[n,r]=v(""),[i,s]=v(0),c=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let S=m.find((E)=>E.path===b);if(S)return S}return m[t.selectedWorktreeIndex()]},f=()=>{let m=process.env.VISUAL||process.env.EDITOR;if(m)return m;let b=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let S of b)try{if(Bun.spawnSync(["which",S],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return S}catch{}return null},a=re(()=>[{id:"add",label:"Add Worktree",description:"Create a new git worktree",action:()=>{t.setActiveTab("add"),t.setShowCommandPalette(!1)}},{id:"delete",label:"Delete Worktree",description:"Remove the selected worktree",action:()=>{let m=c();if(!m||m.isMain)return;t.setShowRemove(!0),t.setShowCommandPalette(!1)}},{id:"open-editor",label:"Open in Editor",description:"Open selected worktree in IDE",action:()=>{let m=c();if(!m)return;let b=f();if(!b)return;t.setShowCommandPalette(!1),Bun.spawn([b,m.path],{stdout:"inherit",stderr:"inherit"})}},{id:"refresh",label:"Refresh",description:"Reload worktree list",action:()=>{e.refetch(),t.setShowCommandPalette(!1)}},{id:"config",label:"Open Config",description:"View configuration",action:()=>{t.setActiveTab("config"),t.setShowCommandPalette(!1)}},{id:"doctor",label:"Run Doctor",description:"Check worktree health",action:()=>{t.setActiveTab("doctor"),t.setShowCommandPalette(!1)}},...un.map((m)=>({id:`theme:${m}`,label:`Theme: ${ss[m]}`,description:"Switch color theme",action:()=>{pn(m);try{let b=Nt(),S={...Y()};S.theme=m,Jo(b,JSON.stringify(S,null,2))}catch{}t.setShowCommandPalette(!1)}})),{id:"quit",label:"Quit",description:"Exit oh-my-worktree",action:()=>process.exit(0)}]),h=re(()=>{let m=n().toLowerCase();if(!m)return a();return a().filter((b)=>b.label.toLowerCase().includes(m)||b.description.toLowerCase().includes(m))});Ph((m)=>{if(!t.showCommandPalette())return;let b=m.name;if(b==="escape"){t.setShowCommandPalette(!1),r(""),s(0);return}if(b==="return"||b==="enter"){let S=h()[i()];if(S)S.action();r(""),s(0);return}if(b==="down"||b==="j"){s((S)=>Math.min(S+1,h().length-1));return}if(b==="up"||b==="k"){s((S)=>Math.max(S-1,0));return}if(b==="backspace"){r((S)=>S.slice(0,-1)),s(0);return}if(m.sequence&&m.sequence.length===1&&m.sequence.charCodeAt(0)>=32)r((S)=>S+m.sequence),s(0)});let u=()=>Math.max(50,Math.min(80,o().width-4)),d=()=>Math.max(10,Math.min(h().length+8,o().height-4)),g=()=>u()-4,x=()=>d()-8;return React.createElement(je,{width:u(),height:d(),borderColor:l.border.active,backgroundColor:l.bg.surface,title:" Command Palette ",footer:React.createElement(yw,null,React.createElement("box",{height:1,width:g()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(g(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:l.text.secondary},"\u2191\u2193:navigate"),React.createElement("text",{fg:l.text.secondary},"Enter:run"),React.createElement("text",{fg:l.text.secondary},"Esc:close")))},React.createElement("box",{height:1,width:g(),backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:l.text.accent},">"),React.createElement("text",{x:3,y:0,fg:l.text.primary},n()),React.createElement("text",{x:3+n().length,y:0,fg:l.text.accent},"\u2588")),React.createElement("box",{height:1,width:g()},React.createElement("text",{fg:l.border.subtle},"\u2500".repeat(Math.max(g(),1)))),React.createElement("box",{width:g(),height:x(),backgroundColor:l.bg.surface,flexDirection:"column"},React.createElement(St,{each:h().slice(0,x())},(m,b)=>{let S=()=>b()===i();return React.createElement("box",{height:1,width:g(),backgroundColor:S()?l.select.focusedBg:l.bg.surface,onMouseDown:()=>{s(b()),m.action()}},React.createElement("text",{x:2,y:0,fg:S()?l.tab.active:l.text.primary},m.label),React.createElement("text",{x:Math.max(25,m.label.length+4),y:0,fg:l.text.secondary},m.description))}),React.createElement(O,{when:h().length===0},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:l.text.secondary},"No commands found")))))}var Ks=N(()=>{Rt();ie();me();Ht();zo();$t()});import{useTerminalDimensions as Eh}from"@opentui/solid";function Rh(t){if(t==="success")return"\u2713";if(t==="warning")return"\u26A0";if(t==="error")return"\u2717";return"\u2139"}function Mh(t){if(t==="success")return l.text.success;if(t==="warning")return l.text.warning;if(t==="error")return l.text.error;return l.text.primary}function qs(){let t=Eh(),e=()=>Math.min(60,Math.max(24,t().width-4));return React.createElement("box",{x:(()=>Math.max(0,t().width-e()-1))(),y:1,width:e(),height:5,flexDirection:"column"},React.createElement(St,{each:Rn().toasts()},(n,r)=>React.createElement("box",{x:0,y:r(),width:e(),height:1,backgroundColor:l.bg.elevated},React.createElement("text",{x:1,y:0,fg:Mh(n.type)},`${Rh(n.type)} ${n.message}`))))}var Xs=N(()=>{Rt();Mn();Ht()});var Ys={};xt(Ys,{launchTUI:()=>Ah});import{render as Oh,useKeyboard as Wh,useTerminalDimensions as Dh,useRenderer as Fh}from"@opentui/solid";import{resolve as Zs}from"path";function Bh(){let t=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let e of t)try{if(Bun.spawnSync(["which",e],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return e}catch{}return null}function Lh(t){let e=Et(),o=Ot(),n=Fh(),[r,i]=v(!1),s=Dh(),c=()=>{let m=o.worktrees()??[],b=e.selectedWorktreePath();if(b){let S=m.find((E)=>E.path===b);if(S)return S}return m[e.selectedWorktreeIndex()]};de(()=>{let m=o.worktrees()??[],b=m.map((R)=>R.path);if(e.pruneSelectedWorktrees(b),m.length===0){if(e.selectedWorktreeIndex()!==0)e.setSelectedWorktreeIndex(0);if(e.selectedWorktreePath()!==null)e.setSelectedWorktreePath(null);return}let S=e.selectedWorktreePath();if(S){let R=m.findIndex((it)=>it.path===S);if(R>=0){if(R!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(R);return}}let E=Math.min(e.selectedWorktreeIndex(),m.length-1),y=m[E]?.path??null;if(E!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(E);if(y!==e.selectedWorktreePath())e.setSelectedWorktreePath(y)}),Wh((m)=>{if(e.showCommandPalette())return;let b=m.name;if(m.ctrl&&b==="p"){e.setShowCommandPalette(!0);return}if(b==="escape"){if(e.showBulkActions()){e.setShowBulkActions(!1);return}if(e.showDetailView()){e.setShowDetailView(!1);return}if(e.showRemove()){e.setShowRemove(!1);return}if(r()){i(!1);return}if(e.activeTab()!=="list"){e.setActiveTab("list");return}}if(e.showBulkActions())return;if(e.showRemove())return;if(e.activeTab()==="add")return;if(e.activeTab()==="list"){if(e.showDetailView())return;if(b==="a"){e.setActiveTab("add");return}if(b==="r"){o.refetch();return}if(b==="d"){let S=c();if(S&&!S.isMain)e.setShowRemove(!0);return}if(b==="o"){let S=c();if(S){let E=process.env.VISUAL||process.env.EDITOR||Bh();if(E)Bun.spawn([E,S.path],{stdout:"inherit",stderr:"inherit"})}return}}if(b==="h"){e.setActiveTab("doctor");return}if(b==="q"||b==="Q")n.destroy();if(b==="?")i((S)=>!S)});let f=()=>s().width,a=()=>s().height,h=()=>t.repoPath.split("/").pop()??"",u=()=>{let m=o.repoNames();if(m.length<=1)return h();return`${m.length} repos`},d=()=>{let m=o.worktrees()??[];return`${h()} \xB7 ${m.length} worktrees`},g=()=>{return` Worktrees (${(o.worktrees()??[]).length}) `},x=()=>f()-Qs-1;return React.createElement("box",{width:f(),height:a(),backgroundColor:l.bg.base,flexDirection:"column"},React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:1,y:0,fg:l.text.accent},"\uD83C\uDF33 oh-my-worktree"),React.createElement("text",{x:f()-u().length-2,y:0,fg:l.text.secondary},u())),React.createElement("box",{flexGrow:1,flexDirection:"row"},React.createElement("box",{width:Qs,flexShrink:0,backgroundColor:l.bg.surface,flexDirection:"column"},React.createElement("box",{height:1,paddingX:1},React.createElement("text",{fg:l.text.accent},React.createElement("b",null,g()))),React.createElement(vs,null)),React.createElement("box",{width:1}),React.createElement("box",{flexGrow:1,backgroundColor:l.bg.base},React.createElement(O,{when:e.activeTab()!=="config"&&!e.showRemove()&&!e.showBulkActions()},React.createElement(us,null)),React.createElement(O,{when:e.activeTab()==="list"&&e.showBulkActions()},React.createElement(Fs,{w:x(),h:a()-3})),React.createElement(O,{when:e.activeTab()==="config"},React.createElement(Ls,null)))),React.createElement(qs,null),React.createElement("toaster",{position:"bottom-right"}),React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:0,y:0,fg:l.border.subtle},"\u2500".repeat(f()))),React.createElement("box",{height:1,backgroundColor:l.bg.overlay},React.createElement("text",{x:1,y:0,fg:l.text.secondary},"d:delete a:add o:open r:refresh ^P:cmd h:health q:quit")),React.createElement(O,{when:r()&&!e.showCommandPalette()},React.createElement("box",{x:Math.max(0,Math.floor((f()-Math.max(40,Math.min(60,f()-4)))/2)),y:Math.max(0,Math.floor((a()-14)/2)),width:Math.max(40,Math.min(60,f()-4)),height:14,border:!0,borderStyle:"rounded",borderColor:l.border.active,backgroundColor:l.bg.elevated,title:" Keyboard Shortcuts ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1,position:"absolute"},React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"q"),React.createElement("text",{x:8,fg:l.text.primary},"Quit")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"j/k"),React.createElement("text",{x:8,fg:l.text.primary},"Navigate list")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"a"),React.createElement("text",{x:8,fg:l.text.primary},"Add worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"d"),React.createElement("text",{x:8,fg:l.text.primary},"Delete worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"r"),React.createElement("text",{x:8,fg:l.text.primary},"Refresh list")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"Ctrl+P"),React.createElement("text",{x:8,fg:l.text.primary},"Command palette")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.secondary},"?"),React.createElement("text",{x:8,fg:l.text.primary},"Toggle help")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:l.text.accent},"Press ? to close")))),React.createElement(O,{when:e.activeTab()==="add"},React.createElement(Es,null)),React.createElement(O,{when:e.activeTab()==="doctor"},React.createElement(Hs,null)),React.createElement(O,{when:e.showRemove()},React.createElement(Ms,null)),React.createElement(O,{when:e.showCommandPalette()},React.createElement(Vs,null)))}async function Ah(){if(process.stdout.isTTY)process.stdout.write("\x1B]0;Oh My Worktree\x07");let t=await M.getMainRepoPath().catch(()=>process.cwd()),e=[t];try{let o={...Y()},n=Le(o),r=new Set([Zs(t)]);for(let i of n){let s=Zs(i);if(!r.has(s))r.add(s),e.push(i)}if(o.theme&&un.includes(o.theme))pn(o.theme)}catch{}await Oh(()=>React.createElement(os,{repoPath:t,repoPaths:e},React.createElement(is,{repoPaths:e},React.createElement(Ds,null,React.createElement(Lh,{repoPath:t})))),{exitOnCtrlC:!0,useMouse:!0})}var Qs=28;var tc=N(()=>{Rt();ie();me();ct();ps();Rs();Os();Bs();As();Ns();Us();Ht();Ks();Mn();Xs();$t()});import*as ec from"readline";async function Te(t){let e=ec.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}async function at(){return M.getMainRepoPath().catch(()=>process.cwd())}function Kt(t,e){let o=t.find((n)=>n.branch===e||n.path===e||n.path.endsWith("/"+e));if(!o)console.error(`Error: no worktree found for '${e}'`),process.exit(1);return o}function wt(t){if(t instanceof Gt)console.error(`Git error: ${t.message}`);else console.error(`Error: ${t.message}`);process.exit(1)}var Dt=N(()=>{ct();Zt()});import{mkdirSync as Ih,writeFileSync as jh}from"fs";import{dirname as _h}from"path";function Th(t){return ce(t,"omw-pr")}function oc(t,e){let o=Th(t);Ih(_h(o),{recursive:!0}),jh(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}var nc=N(()=>{We()});import{appendFileSync as Gh,existsSync as Hh,mkdirSync as Nh,readFileSync as rc,rmSync as Jh,statSync as kh,writeFileSync as zh}from"fs";import{dirname as vh}from"path";function Wr(t){return ce(t,"omw-activity.log")}function qt(t,e){let o=Wr(t);Nh(vh(o),{recursive:!0}),Gh(o,`${JSON.stringify(e)}
16
- `,{encoding:"utf-8",mode:384});let n=kh(o,{throwIfNoEntry:!1});if(n&&n.size>Vh){let r=rc(o,"utf-8").split(/\r?\n/).filter(Boolean);if(r.length>ic){let i=r.slice(-Uh);zh(o,`${i.join(`
3
+ var Ia=Object.defineProperty;var Aa=(t)=>t;function ja(t,e){this[t]=Aa.bind(null,e)}var xt=(t,e)=>{for(var o in e)Ia(t,o,{get:e[o],enumerable:!0,configurable:!0,set:ja.bind(e,o)})};var H=(t,e)=>()=>(t&&(e=t(t=0)),e);var pe=import.meta.require;function Vi(t){if(t instanceof Error)return t;return Error(typeof t==="string"?t:"Unknown error",{cause:t})}function Ki(t,e=Ct){let o=e&&e.context&&e.context[Ol],n=Vi(t);if(!o)throw n;try{for(let r of o)r(n)}catch(r){Ki(r,e&&e.owner||null)}}function Wl(){let t={owner:Ct,context:Ct?Ct.context:null,owned:null,cleanups:null};if(Ct)if(!Ct.owned)Ct.owned=[t];else Ct.owned.push(t);return t}function N(t,e){return[()=>t,(o)=>{return t=typeof o==="function"?o(t):o}]}function ie(t,e){}function se(t,e){Ct=Wl();let o;try{o=t(e)}catch(n){Ki(n)}finally{Ct=Ct.owner}return()=>o}function De(t,e,o={}){let n=Array.isArray(t),r=o.defer;return()=>{if(r)return;let i;if(n){i=[];for(let s=0;s<t.length;s++)i.push(t[s]())}else i=t();return e(i)}}function un(t){}function ce(t){if(Ct)if(!Ct.cleanups)Ct.cleanups=[t];else Ct.cleanups.push(t);return t}function eo(t){let e=Symbol("context");return{id:e,Provider:Fl(e),defaultValue:t}}function oo(t){return Ct&&Ct.context&&Ct.context[t.id]!==void 0?Ct.context[t.id]:t.defaultValue}function Dl(t){let e=se(()=>lr(t()));return e.toArray=()=>{let o=e();return Array.isArray(o)?o:o!=null?[o]:[]},e}function lr(t){if(typeof t==="function"&&!t.length)return lr(t());if(Array.isArray(t)){let e=[];for(let o=0;o<t.length;o++){let n=lr(t[o]);Array.isArray(n)?e.push.apply(e,n):e.push(n)}return e}return t}function Fl(t){return function(o){return se(()=>{return Ct.context={...Ct.context,[t]:o.value},Dl(()=>o.children)})}}function zi(t){let e=String(t),o=e.length-1;return me.context.id+(o?String.fromCharCode(96+o):"")+e}function Bl(t,e){let o=t.each||[],n=o.length,r=t.children;if(n){let i=Array(n);for(let s=0;s<n;s++)i[s]=e(r,o[s],s);return i}return t.fallback}function $t(t){return Bl(t,(e,o,n)=>e(o,()=>n))}function O(t){let e;return t.when?typeof(e=t.children)==="function"?e(t.keyed?t.when:()=>t.when):e:t.fallback||""}function Xi(t,e,o={}){if(typeof e!=="function")o=e||{},e=t,t=!0;let n=new Set,r=me.getNextContextId(),i={},s=o.storage?o.storage(o.initialValue)[0]():o.initialValue,c,l;if(me.context.async&&o.ssrLoadFrom!=="initial"){if(i=me.context.resources[r]||(me.context.resources[r]={}),i.ref){if(!i.data&&!i.ref[0]._loading&&!i.ref[0].error)i.ref[1].refetch();return i.ref}}let a=()=>{if(l)throw l;let x=o.ssrLoadFrom!=="initial"&&me.context.async&&"data"in me.context.resources[r];if(!x&&_o)_o.push(r);if(!x&&h._loading){let m=oo(Ll);if(m)m.resources.set(r,h),n.add(m)}return x},h=()=>{return a()?me.context.resources[r].data:s},u=()=>{return a(),h._loading};h._loading=!1,h.error=void 0,h.state="initialValue"in o?"ready":"unresolved",Object.defineProperties(h,{latest:{get(){return h()}},loading:{get(){return u()}}});function d(){let x=me.context;if(!x.async)return h._loading=!!(typeof t==="function"?t():t);if(x.resources&&r in x.resources&&"data"in x.resources[r]){s=x.resources[r].data;return}let m;try{if(_o=[],m=typeof t==="function"?t():t,_o.length)return}finally{_o=null}if(!c){if(m==null||m===!1)return;c=e(m,{value:s})}if(c!=null&&typeof c==="object"&&"then"in c){if(h._loading=!0,h.state="pending",c=c.then((b)=>{return h._loading=!1,h.state="ready",x.resources[r].data=b,c=null,Ui(n),b}).catch((b)=>{throw h._loading=!1,h.state="errored",h.error=l=Vi(b),c=null,Ui(n),l}),x.serialize)x.serialize(r,c,o.deferStream);return c}if(x.resources[r].data=c,x.serialize)x.serialize(r,c);return c=null,x.resources[r].data}if(o.ssrLoadFrom!=="initial")d();let g=[h,{refetch:d,mutate:(x)=>s=x}];if(c)i.ref=g;return g}function Il(t){for(let e of t.resources.values())if(e._loading)return!1;return!0}function Ui(t){for(let e of t){if(!Il(e))continue;e.completed(),t.delete(e)}}var Tm,Gm,vm,Ol,Ct=null,me,Ll,_o=null;var Et=H(()=>{Tm=Symbol("solid-proxy"),Gm=Symbol("solid-track"),vm=Symbol("solid-dev-component"),Ol=Symbol("error");me={context:void 0,getContextId(){if(!this.context)throw Error("getContextId cannot be used under non-hydrating context");return zi(this.context.count)},getNextContextId(){if(!this.context)throw Error("getNextContextId cannot be used under non-hydrating context");return zi(this.context.count++)}};Ll=eo()});function qi(t){return typeof t==="object"&&t!==null&&"frames"in t&&"interval"in t&&Array.isArray(t.frames)}function Zi(t){return typeof t==="object"&&t!==null&&"label"in t&&"onClick"in t}function fr(t,e){switch(t){case"success":return e.success;case"error":return e.error;case"warning":return e.warning;case"info":return e.info;case"loading":return hr(e.loading);default:return""}}function hr(t){if(qi(t))return t.frames[0]??"\u25CC";return t}function ur(t){return qi(t)?t:null}var Al,Qi;var Yi=H(()=>{Al={frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"],interval:100},Qi={success:"\u2713",error:"\u2717",warning:"!",info:"\u2139",loading:Al,close:"\xD7"}});import{BoxRenderable as dn,TextAttributes as jl,TextRenderable as To,parseColor as _l}from"@opentui/core";function kl(t){return t!==null&&typeof t==="object"&&"ok"in t&&typeof t.ok==="boolean"&&"status"in t&&typeof t.status==="number"}function Vl(t,e={}){let[o,n]=t.split("-"),r={position:"absolute"};if(o==="top")r.top=e.top??pn.top;else r.bottom=e.bottom??pn.bottom;if(n==="left")r.left=e.left??pn.left,r.alignItems="flex-start";else if(n==="center")r.left=0,r.width="100%",r.alignItems="center";else r.right=e.right??pn.right,r.alignItems="flex-end";return r}function Kl(t){return t.includes("center")}function Xl(t){return t.startsWith("top")}function ql(t,e={top:0,right:0,bottom:0,left:0}){if(!t)return{...e};let{padding:o,paddingX:n,paddingY:r}=t;return{top:t.paddingTop??r??o??e.top,right:t.paddingRight??n??o??e.right,bottom:t.paddingBottom??r??o??e.bottom,left:t.paddingLeft??n??o??e.left}}function Zl(...t){let e={};for(let o of t){if(!o)continue;Object.assign(e,o)}return e}function ts(t,e,o){let n=pr.style,r=pr[t]?.style,i=e?.style,s=e?.[t]?.style,c=Zl(n,r,i,s,o);if(c.border===!1)delete c.borderStyle,delete c.borderColor;return c}function es(t,e,o){if(o!==void 0)return o;let n=e?.[t]?.duration;if(n!==void 0)return n;if(e?.duration!==void 0)return e.duration;return pr.duration}var Tl,Gl=200,os=60,pn,vl,pr,Hl=1,Nl=class{subscribers=[];toasts=[];dismissedToasts=new Set;_activeToasts=[];_updateActiveToastsCache=()=>{let t=this.toasts.filter((e)=>!this.dismissedToasts.has(e.id));if(t.length!==this._activeToasts.length||t.some((e,o)=>e!==this._activeToasts[o]))this._activeToasts=t};subscribe=(t)=>{return this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);if(e>-1)this.subscribers.splice(e,1)}};publish=(t)=>{for(let e of this.subscribers)e(t)};addToast=(t)=>{this.toasts=[...this.toasts,t],this._updateActiveToastsCache(),this.publish(t)};create=(t)=>{let{message:e,...o}=t,n=typeof t.id==="number"||t.id&&t.id.length>0?t.id:Hl++,r=this.toasts.find((s)=>s.id===n),i=t.dismissible===void 0?!0:t.dismissible;if(this.dismissedToasts.has(n))this.dismissedToasts.delete(n);if(r)this.toasts=this.toasts.map((s)=>{if(s.id===n)return this.publish({...s,...t,id:n,title:e}),{...s,...t,id:n,dismissible:i,title:e};return s}),this._updateActiveToastsCache();else this.addToast({title:e,...o,dismissible:i,id:n,type:t.type??"default"});return n};dismiss=(t)=>{if(t!==void 0)this.dismissedToasts.add(t),this._updateActiveToastsCache(),setTimeout(()=>{for(let e of this.subscribers)e({id:t,dismiss:!0})},0);else{for(let e of this.toasts){this.dismissedToasts.add(e.id);for(let o of this.subscribers)o({id:e.id,dismiss:!0})}this._updateActiveToastsCache()}return t};message=(t,e)=>{return this.create({...e,message:t,type:"default"})};error=(t,e)=>{return this.create({...e,message:t,type:"error"})};success=(t,e)=>{return this.create({...e,message:t,type:"success"})};info=(t,e)=>{return this.create({...e,message:t,type:"info"})};warning=(t,e)=>{return this.create({...e,message:t,type:"warning"})};loading=(t,e)=>{return this.create({...e,message:t,type:"loading"})};promise=(t,e)=>{if(!e)return;let o;if(e.loading!==void 0)o=this.create({...e,type:"loading",message:e.loading,description:typeof e.description!=="function"?e.description:void 0});let n=t instanceof Function?t():t,r=o!==void 0,i,s=n.then(async(l)=>{if(i=["resolve",l],kl(l)&&!l.ok){r=!1;let a=typeof e.error==="function"?await e.error(`HTTP error! status: ${l.status}`):e.error,h=typeof e.description==="function"?await e.description(`HTTP error! status: ${l.status}`):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}else if(l instanceof Error){r=!1;let a=typeof e.error==="function"?await e.error(l):e.error,h=typeof e.description==="function"?await e.description(l):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}else if(e.success!==void 0){r=!1;let a=typeof e.success==="function"?await e.success(l):e.success,h=typeof e.description==="function"?await e.description(l):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"success",description:h,...u})}}).catch(async(l)=>{if(i=["reject",l],e.error!==void 0){r=!1;let a=typeof e.error==="function"?await e.error(l):e.error,h=typeof e.description==="function"?await e.description(l):e.description,u=typeof a==="object"&&a!==null?a:{message:a};this.create({id:o,type:"error",description:h,...u})}}).finally(()=>{if(r)this.dismiss(o),o=void 0;e.finally?.()}),c=()=>new Promise((l,a)=>s.then(()=>i[0]==="reject"?a(i[1]):l(i[1])).catch(a));if(typeof o!=="string"&&typeof o!=="number")return{unwrap:c};return Object.assign(o,{unwrap:c})};getActiveToasts=()=>{return this._activeToasts}},At,Jl=(t,e)=>At.message(t,e),zl=()=>At.toasts,Ul=()=>At.getActiveToasts(),no,Ql,ns;var rs=H(()=>{Yi();Tl={SHORT:2000,DEFAULT:4000,LONG:6000,EXTENDED:1e4,PERSISTENT:1/0},pn={top:1,right:2,bottom:1,left:2},vl={border:!0,borderStyle:"single",borderColor:"#333333",minHeight:3,backgroundColor:"#1a1a1a",foregroundColor:"#ffffff",mutedColor:"#6b7280"},pr={style:vl,duration:Tl.DEFAULT,default:{style:{borderColor:"#333333"}},success:{style:{borderColor:"#22c55e"}},error:{style:{borderColor:"#ef4444"}},warning:{style:{borderColor:"#f59e0b"}},info:{style:{borderColor:"#3b82f6"}},loading:{style:{borderColor:"#6b7280"}}};At=new Nl,no=Object.assign(Jl,{success:At.success,info:At.info,warning:At.warning,error:At.error,message:At.message,promise:At.promise,dismiss:At.dismiss,loading:At.loading},{getHistory:zl,getToasts:Ul});Ql=class extends dn{_toast;_icons;_toastOptions;_computedStyle;_closeButton;_onRemove;_remainingTime;_closeTimerStartTime=0;_lastCloseTimerStartTime=0;_timerHandle=null;_paused=!1;_dismissed=!1;_spinnerHandle=null;_spinnerFrameIndex=0;_spinnerConfig=null;_iconText=null;_contentBox=null;_titleText=null;_descriptionText=null;_actionsBox=null;constructor(t,e){let o=ts(e.toast.type,e.toastOptions,e.toast.style),n=es(e.toast.type,e.toastOptions,e.toast.duration),r=ql(o,{top:0,right:1,bottom:0,left:1});super(t,{id:`toast-${e.toast.id}`,flexDirection:"row",gap:1,border:o.border,borderStyle:o.borderStyle,borderColor:o.borderColor,customBorderChars:o.customBorderChars,backgroundColor:o.backgroundColor,minHeight:o.minHeight,maxWidth:o.maxWidth??os,minWidth:o.minWidth,paddingTop:r.top,paddingRight:r.right,paddingBottom:r.bottom,paddingLeft:r.left,onMouseOver:()=>this.pause(),onMouseOut:()=>this.resume()});if(this._toast=e.toast,this._icons=e.icons===!1?!1:{...Qi,...e.icons},this._toastOptions=e.toastOptions,this._computedStyle=o,this._closeButton=e.closeButton,this._onRemove=e.onRemove,this._remainingTime=n,this.setupContent(),this._remainingTime!==1/0&&this._toast.type!=="loading")this.startTimer();if(this._toast.type==="loading")this.startSpinner()}setupContent(){let t=this.ctx,e=this._toast,o=this._computedStyle,n=this._icons,r=o.iconColor??o.borderColor,i=e.type==="loading";if(i&&n!==!1)this._spinnerConfig=ur(n.loading);let s=e.icon??(n===!1?void 0:i?hr(n.loading):fr(e.type,n));if(s)this._iconText=new To(t,{id:`${this.id}-icon`,content:s,fg:r,flexShrink:0,paddingTop:0,paddingBottom:0}),this.add(this._iconText);this._contentBox=new dn(t,{id:`${this.id}-content`,flexDirection:"column",flexGrow:1,flexShrink:1,gap:0});let c=typeof e.title==="function"?e.title():e.title;if(c)this._titleText=new To(t,{id:`${this.id}-title`,content:c,fg:o.foregroundColor,attributes:jl.BOLD,wrapMode:"word"}),this._contentBox.add(this._titleText);let l=typeof e.description==="function"?e.description():e.description;if(l)this._descriptionText=new To(t,{id:`${this.id}-description`,content:l,fg:o.mutedColor,wrapMode:"word"}),this._contentBox.add(this._descriptionText);if(this.add(this._contentBox),e.action){if(this._actionsBox=new dn(t,{id:`${this.id}-actions`,flexDirection:"row",gap:1,flexShrink:0,alignItems:"center"}),e.action&&Zi(e.action)){let a=new To(t,{id:`${this.id}-action`,content:`[${e.action.label}]`,fg:o.foregroundColor,onMouseUp:()=>e.action?.onClick?.()});this._actionsBox.add(a)}this.add(this._actionsBox)}if((e.closeButton??this._closeButton)&&e.dismissible!==!1){let a=n===!1?"\xD7":n.close,h=new To(t,{id:`${this.id}-close`,content:a,fg:o.mutedColor,flexShrink:0,onMouseUp:()=>this.dismiss()});this.add(h)}}startTimer(){if(this._remainingTime===1/0)return;this._closeTimerStartTime=Date.now(),this._timerHandle=setTimeout(()=>{this._toast.onAutoClose?.(this._toast),this.dismiss()},this._remainingTime)}pause(){if(this._paused||this._remainingTime===1/0)return;if(this._paused=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;if(this._lastCloseTimerStartTime<this._closeTimerStartTime){let t=Date.now()-this._closeTimerStartTime;this._remainingTime=Math.max(0,this._remainingTime-t)}this._lastCloseTimerStartTime=Date.now()}resume(){if(!this._paused||this._remainingTime===1/0)return;this._paused=!1,this.startTimer()}startSpinner(){if(this._spinnerHandle||!this._spinnerConfig)return;let{frames:t,interval:e}=this._spinnerConfig;this._spinnerHandle=setInterval(()=>{this._spinnerFrameIndex=(this._spinnerFrameIndex+1)%t.length;let o=t[this._spinnerFrameIndex];if(this._iconText&&o)this._iconText.content=o,this.requestRender()},e)}stopSpinner(){if(this._spinnerHandle)clearInterval(this._spinnerHandle),this._spinnerHandle=null}dismiss(){if(this._dismissed)return;if(this._dismissed=!0,this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),this._toast.onDismiss?.(this._toast),At.dismiss(this._toast.id),setTimeout(()=>{this._onRemove?.(this._toast)},Gl)}updateToast(t){this._toast=t;let e=ts(t.type,this._toastOptions,t.style);if(this._computedStyle=e,e.borderColor)this.borderColor=e.borderColor;if(e.customBorderChars)this.customBorderChars=e.customBorderChars;let o=e.iconColor??e.borderColor;if(this._iconText){let i=t.icon??(this._icons===!1?void 0:fr(t.type,this._icons));if(i)this._iconText.content=i;if(o)this._iconText.fg=_l(o)}if(this._titleText){let i=typeof t.title==="function"?t.title():t.title;if(i)this._titleText.content=i}if(this._descriptionText){let i=typeof t.description==="function"?t.description():t.description;if(i)this._descriptionText.content=i}let n=this._spinnerHandle!==null,r=t.type==="loading";if(n&&!r)this.stopSpinner(),this._spinnerConfig=null;else if(!n&&r){if(this._icons!==!1)this._spinnerConfig=ur(this._icons.loading);this.startSpinner()}if(t.type!=="loading"){if(this._timerHandle)clearTimeout(this._timerHandle);if(this._remainingTime=es(t.type,this._toastOptions,t.duration),this._remainingTime!==1/0)this.startTimer()}this.requestRender()}get toast(){return this._toast}get isDismissed(){return this._dismissed}destroy(){if(this._timerHandle)clearTimeout(this._timerHandle),this._timerHandle=null;this.stopSpinner(),super.destroy()}},ns=class extends dn{_options={};_toastRenderables=new Map;_unsubscribe=null;constructor(t,e={}){super(t,{id:"toaster",flexDirection:"column",gap:1,zIndex:9999});this._options=e,this.applyLayoutOptions(),this.subscribe()}applyLayoutOptions(){let t=this._options.position??"bottom-right",e=Vl(t,this._options.offset??{}),o=Kl(t);if(Object.assign(this,e),super.gap=this._options.gap??1,!o)super.maxWidth=this._options.maxWidth??os}isToastPosition(t){return t==="top-left"||t==="top-center"||t==="top-right"||t==="bottom-left"||t==="bottom-center"||t==="bottom-right"}set position(t){if(this.isToastPosition(t))this._options.position=t,this.applyLayoutOptions();else super.position=t}set offset(t){this._options.offset=t,this.applyLayoutOptions()}set gap(t){this._options.gap=t,super.gap=t}set visibleToasts(t){this._options.visibleToasts=t}set closeButton(t){this._options.closeButton=t}set icons(t){this._options.icons=t}set stackingMode(t){this._options.stackingMode=t}set maxWidth(t){this._options.maxWidth=t,super.maxWidth=t}set toastOptions(t){this._options.toastOptions=t}subscribe(){this._unsubscribe=At.subscribe((t)=>{if("dismiss"in t&&t.dismiss)this.removeToast(t.id);else this.addOrUpdateToast(t)})}addOrUpdateToast(t){let e=this._toastRenderables.get(t.id);if(e){e.updateToast(t);return}if((this._options.stackingMode??"single")==="single")for(let[n]of this._toastRenderables)this.removeToast(n);else{let n=this._options.visibleToasts??3,r=this._toastRenderables.size;if(r>=n){let i=r-n+1,s=Array.from(this._toastRenderables.keys());for(let c=0;c<i;c++){let l=s[c];if(l!==void 0)this.removeToast(l)}}}let o=new Ql(this.ctx,{toast:t,icons:this._options.icons,toastOptions:this._options.toastOptions,closeButton:this._options.closeButton,onRemove:(n)=>this.handleToastRemoved(n)});if(this._toastRenderables.set(t.id,o),Xl(this._options.position??"bottom-right"))this.add(o);else this.add(o,0);this.requestRender()}removeToast(t){let e=this._toastRenderables.get(t);if(e)e.dismiss()}handleToastRemoved(t){let e=this._toastRenderables.get(t.id);if(e)this._toastRenderables.delete(t.id),this.remove(e.id),e.destroy(),this.requestRender()}get toastCount(){return this._toastRenderables.size}dismissAll(){for(let[t]of this._toastRenderables)this.removeToast(t)}destroy(){this._unsubscribe?.();for(let[,t]of this._toastRenderables)t.destroy();this._toastRenderables.clear(),super.destroy()}}});import{createElement as Zm,extend as Yl,spread as Qm}from"@opentui/solid";var dr=H(()=>{rs();Yl({toaster:ns})});function ss(t){let[e,o]=N("list"),[n,r]=N(0),[i,s]=N(null),[c,l]=N(!1),[a,h]=N(!1),[u,d]=N(!1),[g,x]=N(!1),[m,b]=N(new Set),[$,E]=N(!1),R=(I)=>{let Y=new Set(m());if(Y.has(I))Y.delete(I);else Y.add(I);b(Y)},P=(I)=>{b(new Set(I))},rt=(I)=>{let Y=new Set(I),et=m(),It=new Set;for(let F of et)if(Y.has(F))It.add(F);if(It.size!==et.size)b(It)},at=()=>{b(new Set)};return React.createElement(is.Provider,{value:{activeTab:e,setActiveTab:o,selectedWorktreeIndex:n,setSelectedWorktreeIndex:r,selectedWorktreePath:i,setSelectedWorktreePath:s,showRemove:c,setShowRemove:l,showCommandPalette:a,setShowCommandPalette:h,showDetailView:u,setShowDetailView:d,inputFocused:g,setInputFocused:x,repoPath:()=>t.repoPath,repoPaths:()=>t.repoPaths,selectedWorktrees:m,toggleWorktreeSelection:R,selectAllNonMain:P,pruneSelectedWorktrees:rt,clearSelection:at,showBulkActions:$,setShowBulkActions:E}},t.children)}function Rt(){let t=oo(is);if(!t)throw Error("useApp must be used within AppProvider");return t}var is;var ae=H(()=>{Et();is=eo()});var Ht,Go,mr,vo;var Qt=H(()=>{Ht=class Ht extends Error{exitCode;stderr;command;constructor(t,e,o,n){super(t);this.exitCode=e;this.stderr=o;this.command=n;this.name="GitError"}};Go=class Go extends Error{installed;required;constructor(t,e){super(`git version ${t} is below minimum required ${e}`);this.installed=t;this.required=e;this.name="GitVersionError"}};mr=class mr extends Error{branch;reason;constructor(t,e,o){super(t);this.branch=e;this.reason=o;this.name="ArchiveError"}};vo=class vo extends Error{path;reason;constructor(t,e,o){super(t);this.path=e;this.reason=o;this.name="ImportError"}}});async function Yt(t,e,o){let n=Array(t.length),r=0;async function i(){while(r<t.length){let c=r++;n[c]=await o(t[c])}}let s=Array.from({length:Math.min(e,t.length)},()=>i());return await Promise.all(s),n}import{resolve as cs,dirname as ef}from"path";import{mkdirSync as of,existsSync as nf}from"fs";function Ho(t){let e=mn.get(t);if(!e)return;if(Date.now()>e.expires){mn.delete(t);return}return e.data}function le(t,e,o=rf){return mn.set(t,{data:e,expires:Date.now()+o}),e}function Mt(){mn.clear()}class M{static gitVersionChecked=!1;static async run(t,e){let o=Bun.spawn(["git",...t],{cwd:e??Bun.cwd,stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[n,r,i]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(i!==0)throw new Ht(`git ${t[0]} failed: ${r.trim()}`,i,r.trim(),`git ${t.join(" ")}`);return n.trim()}static async exec(t,e){return this.run(t,e)}static async checkVersion(){if(this.gitVersionChecked)return;let e=(await this.run(["--version"])).match(/git version (\d+)\.(\d+)\.?((\d+)?)/);if(!e)throw Error("Cannot parse git version");let[,o,n]=e.map(Number);if(o<2||o===2&&n<17)throw new Go(`${o}.${n}`,"2.17");this.gitVersionChecked=!0}static async list(t){await this.checkVersion();let e=t??Bun.cwd,o=await this.getMainRepoPath(e).catch(()=>e),n=`list:${o}`,r=Ho(n);if(r)return r;let i=o.split("/").pop()??"",s=await this.run(["worktree","list","--porcelain"],e),c=this.parsePorcelain(s,i,o),l=await Yt(c,10,async(a)=>({...a,isDirty:await this.isDirty(a.path).catch(()=>!1)}));return le(n,l)}static async listAll(t){await this.checkVersion();let e=new Set,o=[];for(let r of t){let i=cs(r);if(!e.has(i))e.add(i),o.push(i)}return(await Yt(o,5,async(r)=>{try{return await this.list(r)}catch{return[]}})).flat()}static parsePorcelain(t,e,o){let n=t.trim();if(!n)return[];return n.split(/\n\n+/).filter(Boolean).map((i,s)=>{let c=i.split(`
4
+ `),l=c.find((b)=>b.startsWith("worktree ")),a=c.find((b)=>b.startsWith("HEAD ")),h=c.find((b)=>b.startsWith("branch ")),u=c.find((b)=>b.startsWith("locked")),d=l?.slice(9)??"",g=a?.slice(5)??"",x=null;if(h)x=h.slice(7).replace(/^refs\/heads\//,"");let m=u&&u.startsWith("locked ")?u.slice(7):void 0;return{path:d,branch:x,head:g,isMain:s===0,isDirty:!1,isLocked:Boolean(u),lockReason:m,repoName:e,repoPath:o}})}static async add(t,e,o,n){await this.checkVersion();let r=ef(e);if(!nf(r))of(r,{recursive:!0});let s=!await this.localBranchExists(t,n),c=["worktree","add",e,t];if(s)c=["worktree","add","-b",t,e,o?.base??"HEAD"];await this.run(c,n),Mt()}static async localBranchExists(t,e){try{return await this.run(["rev-parse","--verify",`refs/heads/${t}`],e??Bun.cwd),!0}catch{return!1}}static async remove(t,e,o){await this.checkVersion();let n=["worktree","remove",t];if(e?.force)n.push("--force");await this.run(n,o),Mt()}static async move(t,e,o){await this.checkVersion(),await this.run(["worktree","move",t,e],o),Mt()}static async prune(t){await this.checkVersion(),await this.run(["worktree","prune"],t),Mt()}static async isWorktree(t){let e=t??Bun.cwd;try{let o=await this.run(["rev-parse","--git-dir"],e),n=await this.run(["rev-parse","--git-common-dir"],e);return o!==n&&!o.endsWith("/.git")&&!o.endsWith("\\.git")}catch{return!1}}static async getMainRepoPath(t){let e=t??Bun.cwd,o=await this.run(["rev-parse","--git-common-dir"],e),n=cs(e,o);return n.endsWith("/.git")?n.slice(0,-5):n}static async getBranchForWorktree(t){try{let e=await this.run(["rev-parse","--abbrev-ref","HEAD"],t);return e==="HEAD"?null:e}catch{return null}}static async isDirty(t){try{return(await this.run(["status","--porcelain"],t??Bun.cwd)).length>0}catch{return!1}}static async getAheadBehind(t,e){let o=e??Bun.cwd,n=`ahead-behind:${o}:${t}`,r=Ho(n);if(r)return r;try{let i=await this.run(["rev-parse","--abbrev-ref",`${t}@{upstream}`],o),s=await this.run(["rev-list","--left-right","--count",`${i}...${t}`],o),[c,l]=s.split(/\s+/).map(Number);return le(n,{ahead:l??0,behind:c??0})}catch{return le(n,{ahead:0,behind:0})}}static async getLastCommit(t){let e=t??Bun.cwd,o=`last-commit:${e}`,n=Ho(o);if(n!==void 0)return n;try{let r=await this.run(["log","-1","--format=%h\x1F%s\x1F%cr"],e);if(!r)return le(o,null);let[i,s,c]=r.split("\x1F");return le(o,{hash:i??"",message:s??"",relativeDate:c??""})}catch{return le(o,null)}}static async getDirtyCount(t){let e=t??Bun.cwd,o=`dirty-count:${e}`,n=Ho(o);if(n!==void 0)return n;try{let r=await this.run(["status","--porcelain"],e);if(!r)return le(o,0);return le(o,r.split(`
5
+ `).filter(Boolean).length)}catch{return le(o,0)}}static async unlock(t,e){await this.checkVersion(),await this.run(["worktree","unlock",t],e),Mt()}static async isMergedInto(t,e,o){try{return(await this.run(["branch","--merged",e],o??Bun.cwd)).split(`
6
+ `).some((r)=>r.trim().replace(/^[*+] /,"")===t)}catch{return!1}}static async getDefaultRemote(t){try{return await this.run(["config","checkout.defaultRemote"],t??Bun.cwd)||"origin"}catch{return"origin"}}static async remoteBranchExists(t,e,o){let n=e??await this.getDefaultRemote(o);try{return await this.run(["rev-parse","--verify",`refs/remotes/${n}/${t}`],o??Bun.cwd),!0}catch{return!1}}static async listBranches(t){let e=t??Bun.cwd,o=`branches:${e}`,n=Ho(o);if(n)return n;let[r,i]=await Promise.all([this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/heads/"],e).catch(()=>""),this.run(["for-each-ref","--sort=-committerdate","--format=%(refname:short)\x1F%(committerdate:relative)","refs/remotes/"],e).catch(()=>"")]),s=[];for(let c of r.split(`
7
+ `).filter(Boolean)){let[l,a]=c.split("\x1F");s.push({name:l??"",isRemote:!1,lastCommitDate:a??""})}for(let c of i.split(`
8
+ `).filter(Boolean)){let[l,a]=c.split("\x1F");if(!l||l.endsWith("/HEAD"))continue;let h=l.replace(/^[^/]+\//,"");if(s.some((u)=>u.name===h))continue;s.push({name:h,isRemote:!0,lastCommitDate:a??""})}return le(o,s)}static async diffBetween(t,e,o,n){let r=["diff"];if(o?.stat)r.push("--stat");if(o?.nameOnly)r.push("--name-only");return r.push(t,e),this.run(r,n)}static async getWorktreeLastActivity(t){try{let e=await this.run(["log","-1","--format=%ci"],t);return e?new Date(e):null}catch{return null}}static async setUpstream(t,e,o){let n=e??await this.getDefaultRemote(o),r=o??Bun.cwd;try{if(await this.run(["config",`branch.${t}.remote`],r))return}catch{}await this.run(["branch",`--set-upstream-to=${n}/${t}`,t],r)}}var rf=3000,mn;var st=H(()=>{Qt();mn=new Map});function ls(t){let[e,{refetch:o}]=Xi(async()=>{try{if(t.repoPaths.length<=1)return await M.list(t.repoPaths[0]);return await M.listAll(t.repoPaths)}catch(s){throw s}}),n=()=>{Mt(),o()},r=se(()=>{let s=e()??[],c=new Set,l=[];for(let a of s)if(!c.has(a.repoName))c.add(a.repoName),l.push(a.repoName);return l}),i=se(()=>r().length>1);return React.createElement(as.Provider,{value:{worktrees:()=>e(),refetch:n,loading:()=>e.loading,error:()=>e.error,repoNames:r,isMultiRepo:i}},t.children)}function Ot(){let t=oo(as);if(!t)throw Error("useGit must be used within GitProvider");return t}var as;var xe=H(()=>{Et();st();as=eo()});var sf,xn,fs,cf,gn,f;var jt=H(()=>{Et();sf={opencode:{bg:{base:"#090909",surface:"#111111",elevated:"#1a1a1a",overlay:"#000000"},border:{default:"#2a2a2a",active:"#4fc3f7",subtle:"#1e1e1e"},text:{primary:"#e8e8e8",secondary:"#666666",accent:"#4fc3f7",success:"#4ade80",warning:"#fbbf24",error:"#f87171",selected:"#ffffff"},tab:{active:"#4fc3f7",activeBg:"#1a1a1a",inactive:"#555555",inactiveBg:"#000000"},select:{focusedBg:"#1a2a3a",focusedFg:"#4fc3f7",selectedBg:"#161616",selectedFg:"#e8e8e8",normalFg:"#e8e8e8",descFg:"#666666"}},"tokyo-night":{bg:{base:"#1a1b26",surface:"#1f2335",elevated:"#24283b",overlay:"#0d1117"},border:{default:"#3b4261",active:"#7aa2f7",subtle:"#292e42"},text:{primary:"#c0caf5",secondary:"#565f89",accent:"#7aa2f7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",selected:"#ffffff"},tab:{active:"#7aa2f7",activeBg:"#24283b",inactive:"#565f89",inactiveBg:"#1a1b26"},select:{focusedBg:"#283457",focusedFg:"#7aa2f7",selectedBg:"#2a2f44",selectedFg:"#c0caf5",normalFg:"#c0caf5",descFg:"#565f89"}},dracula:{bg:{base:"#282a36",surface:"#21222c",elevated:"#343746",overlay:"#191a21"},border:{default:"#6272a4",active:"#bd93f9",subtle:"#44475a"},text:{primary:"#f8f8f2",secondary:"#6272a4",accent:"#bd93f9",success:"#50fa7b",warning:"#ffb86c",error:"#ff5555",selected:"#ffffff"},tab:{active:"#bd93f9",activeBg:"#343746",inactive:"#6272a4",inactiveBg:"#282a36"},select:{focusedBg:"#44475a",focusedFg:"#bd93f9",selectedBg:"#383a4a",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#6272a4"}},nord:{bg:{base:"#2e3440",surface:"#3b4252",elevated:"#434c5e",overlay:"#242933"},border:{default:"#4c566a",active:"#81a1c1",subtle:"#3b4252"},text:{primary:"#eceff4",secondary:"#4c566a",accent:"#81a1c1",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",selected:"#ffffff"},tab:{active:"#88c0d0",activeBg:"#434c5e",inactive:"#4c566a",inactiveBg:"#2e3440"},select:{focusedBg:"#3b4252",focusedFg:"#88c0d0",selectedBg:"#3b4252",selectedFg:"#eceff4",normalFg:"#eceff4",descFg:"#4c566a"}},catppuccin:{bg:{base:"#1e1e2e",surface:"#181825",elevated:"#313244",overlay:"#11111b"},border:{default:"#45475a",active:"#cba6f7",subtle:"#313244"},text:{primary:"#cdd6f4",secondary:"#585b70",accent:"#cba6f7",success:"#a6e3a1",warning:"#fab387",error:"#f38ba8",selected:"#ffffff"},tab:{active:"#cba6f7",activeBg:"#313244",inactive:"#585b70",inactiveBg:"#1e1e2e"},select:{focusedBg:"#313244",focusedFg:"#cba6f7",selectedBg:"#313244",selectedFg:"#cdd6f4",normalFg:"#cdd6f4",descFg:"#585b70"}},"github-dark":{bg:{base:"#0d1117",surface:"#161b22",elevated:"#21262d",overlay:"#010409"},border:{default:"#30363d",active:"#58a6ff",subtle:"#21262d"},text:{primary:"#e6edf3",secondary:"#484f58",accent:"#58a6ff",success:"#3fb950",warning:"#d29922",error:"#f85149",selected:"#ffffff"},tab:{active:"#58a6ff",activeBg:"#21262d",inactive:"#484f58",inactiveBg:"#0d1117"},select:{focusedBg:"#1f2937",focusedFg:"#58a6ff",selectedBg:"#1f2937",selectedFg:"#e6edf3",normalFg:"#e6edf3",descFg:"#484f58"}},"one-dark":{bg:{base:"#282c34",surface:"#21252b",elevated:"#2c313a",overlay:"#1b1f27"},border:{default:"#3e4451",active:"#61afef",subtle:"#2c313a"},text:{primary:"#abb2bf",secondary:"#5c6370",accent:"#61afef",success:"#98c379",warning:"#e5c07b",error:"#e06c75",selected:"#ffffff"},tab:{active:"#61afef",activeBg:"#2c313a",inactive:"#5c6370",inactiveBg:"#282c34"},select:{focusedBg:"#2c313a",focusedFg:"#61afef",selectedBg:"#2c313a",selectedFg:"#abb2bf",normalFg:"#abb2bf",descFg:"#5c6370"}},monokai:{bg:{base:"#272822",surface:"#1e1f1c",elevated:"#3e3d32",overlay:"#1a1b18"},border:{default:"#49483e",active:"#a6e22e",subtle:"#3e3d32"},text:{primary:"#f8f8f2",secondary:"#75715e",accent:"#66d9ef",success:"#a6e22e",warning:"#e6db74",error:"#f92672",selected:"#ffffff"},tab:{active:"#a6e22e",activeBg:"#3e3d32",inactive:"#75715e",inactiveBg:"#272822"},select:{focusedBg:"#3e3d32",focusedFg:"#66d9ef",selectedBg:"#3e3d32",selectedFg:"#f8f8f2",normalFg:"#f8f8f2",descFg:"#75715e"}},"github-light":{bg:{base:"#ffffff",surface:"#f6f8fa",elevated:"#eaeef2",overlay:"#d0d7de"},border:{default:"#d0d7de",active:"#0969da",subtle:"#eaeef2"},text:{primary:"#1f2328",secondary:"#656d76",accent:"#0969da",success:"#1a7f37",warning:"#9a6700",error:"#cf222e",selected:"#000000"},tab:{active:"#0969da",activeBg:"#eaeef2",inactive:"#656d76",inactiveBg:"#ffffff"},select:{focusedBg:"#ddf4ff",focusedFg:"#0969da",selectedBg:"#eaeef2",selectedFg:"#1f2328",normalFg:"#1f2328",descFg:"#656d76"}}},xn=["opencode","tokyo-night","dracula","nord","catppuccin","github-dark","one-dark","monokai","github-light"],fs={opencode:"OpenCode","tokyo-night":"Tokyo Night",dracula:"Dracula",nord:"Nord",catppuccin:"Catppuccin Mocha","github-dark":"GitHub Dark","one-dark":"One Dark",monokai:"Monokai","github-light":"GitHub Light"},[cf,gn]=N("opencode"),f=new Proxy({},{get(t,e){return new Proxy({},{get(o,n){return sf[cf()][e]?.[n]}})}})});import{readFileSync as af,statSync as lf}from"fs";import{join as hs,resolve as ff}from"path";function ko(t){let e=hs(t,".git"),o=lf(e,{throwIfNoEntry:!1});if(!o||o.isDirectory())return e;let r=af(e,"utf-8").trim().replace(/^gitdir:\s*/,"").trim();return ff(t,r)}function fe(t,e){return hs(ko(t),e)}var Fe=()=>{};import{existsSync as hf,mkdirSync as uf,readFileSync as pf,writeFileSync as df}from"fs";import{dirname as mf}from"path";function us(t){return fe(t,"omw-focus")}function uo(t,e){let o=us(t);uf(mf(o),{recursive:!0}),df(o,e.join(`
9
+ `),{encoding:"utf-8",mode:384})}function te(t){let e=us(t);if(!hf(e))return null;return pf(e,"utf-8").split(/\r?\n/).filter(Boolean)}var ge=H(()=>{Fe()});import{existsSync as gr,mkdirSync as xf,readFileSync as gf,writeFileSync as wf,unlinkSync as bf}from"fs";import{dirname as Cf}from"path";function xr(t){return t.replace(/\//g,"-").replace(/[^a-zA-Z0-9._-]/g,"_")}async function we(t){let e=Bun.spawn(["tmux",...t],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C"}}),[o,n,r]=await Promise.all([new Response(e.stdout).text(),new Response(e.stderr).text(),e.exited]);if(r!==0)throw new po(`tmux ${t[0]} failed: ${n.trim()}`,n.trim());return o.trim()}function Be(t,e){let o=xr(e??ps),n=xr(t);return`${o}_${n}`}function wr(t){return fe(t,"omw-session")}function Sf(t,e){let o=wr(t);xf(Cf(o),{recursive:!0}),wf(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}function Kt(t){let e=wr(t);if(!gr(e))return null;try{return JSON.parse(gf(e,"utf-8"))}catch{return null}}function br(t){let e=wr(t);if(gr(e))bf(e)}async function mo(){try{return await Bun.spawn(["tmux","-V"],{stdout:"pipe",stderr:"pipe"}).exited===0}catch{return!1}}function Cr(){return Boolean(Bun.env.TMUX)}async function be(t){try{return await we(["has-session","-t",t]),!0}catch{return!1}}async function $f(t,e,o){if(await be(t))throw new po(`Session '${t}' already exists`,"session_exists");if(!gr(e))throw new po(`Worktree path does not exist: ${e}`,"path_not_found");let n=o?.windows??[],r=n[0],i=["new-session","-d","-s",t,"-c",e];if(r)i.push("-n",r.name);if(await we(i),r?.command)await we(["send-keys","-t",`${t}:${r.name}`,r.command,"Enter"]);for(let s=1;s<n.length;s++){let c=n[s];if(await we(["new-window","-t",t,"-n",c.name,"-c",e]),c.command)await we(["send-keys","-t",`${t}:${c.name}`,c.command,"Enter"])}if(n.length>0)await we(["select-window","-t",`${t}:${n[0].name}`])}async function Sr(t){if(!await be(t))return;await we(["kill-session","-t",t])}async function wn(t){if(!await be(t))throw new po(`Session '${t}' does not exist`,"session_not_found");if(Cr())await we(["switch-client","-t",t]);else if(await Bun.spawn(["tmux","attach-session","-t",t],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw new po(`Failed to attach to session '${t}'`,"attach_failed")}async function $r(t){let e=xr(t??ps);try{let o=await we(["list-sessions","-F","#{session_name}|#{session_windows}|#{session_attached}|#{session_created}"]);if(!o)return[];return o.split(`
10
+ `).filter(Boolean).filter((n)=>n.startsWith(`${e}_`)||n.startsWith(`${e}:`)).map((n)=>{let[r,i,s,c]=n.split("|");return{name:r??"",windows:parseInt(i??"0",10),attached:s==="1",created:c??""}})}catch{return[]}}async function bn(t,e,o){let n=Be(t,o?.prefix),r=o?.attach??!0;if(await be(n)){if(r)await wn(n);return n}if(await $f(n,e,o?.layout),Sf(e,{name:n,branch:t,worktreePath:e,createdAt:new Date().toISOString(),layout:o?.layoutName}),r)await wn(n);return n}async function Cn(t,e,o){let n=Be(t,o),r=await be(n);if(r)await Sr(n);return br(e),r}var po,ps="omw";var Le=H(()=>{Fe();po=class po extends Error{reason;constructor(t,e){super(t);this.reason=e;this.name="SessionError"}}});function ms(t){let[e,o]=N([]),n=(i)=>{o((s)=>s.filter((c)=>c.id!==i))},r=(i)=>{let s=`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`,c=i.duration??3000;o((l)=>[...l,{...i,id:s}].slice(-5)),setTimeout(()=>{n(s)},c)};return React.createElement(ds.Provider,{value:{toasts:e,addToast:r,removeToast:n}},t.children)}function xo(){let t=oo(ds);if(!t)throw Error("useToast must be used within ToastProvider");return t}var ds;var No=H(()=>{Et();ds=eo()});function go(t){let[e,o]=N(0),n=setInterval(()=>{o((r)=>(r+1)%xs.length)},80);return ce(()=>clearInterval(n)),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:t.color??f.text.accent},xs[e()]),t.label&&React.createElement("text",{fg:f.text.secondary},t.label))}var xs;var Sn=H(()=>{Et();jt();xs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});import{useTerminalDimensions as Pf,useRenderer as yf,useSelectionHandler as Ef}from"@opentui/solid";function gs(t){let e=Ot(),o=xo(),n=yf(),r=Pf(),i=()=>r().width,s=()=>r().height,[c,l]=N(null),[a,h]=N(!0),[u,d]=N("");Ef((P)=>{let rt=P.getSelectedText();if(!rt)return;n.copyToClipboardOSC52(rt),o.addToast({type:"info",message:"Copied to clipboard"})});let g;ce(()=>{if(g)clearTimeout(g)});let x=()=>{return(e.worktrees()??[]).find((at)=>at.isMain)?.branch??"main"};ie(De(()=>t.worktree.path,(P)=>{if(g)clearTimeout(g);if(!P){l(null),d(""),h(!1);return}l(null),d(""),h(!0),g=setTimeout(async()=>{if(t.worktree.path!==P)return;try{let[rt,[at,I],Y]=await Promise.all([Mf(P),t.worktree.branch&&!t.worktree.isMain?Promise.all([M.diffBetween(x(),t.worktree.branch,{stat:!0},P).catch(()=>""),M.diffBetween(x(),t.worktree.branch,void 0,P).catch(()=>"")]):Promise.resolve(["",""]),t.worktree.branch?M.getAheadBehind(t.worktree.branch,P):Promise.resolve({ahead:0,behind:0})]);if(t.worktree.path!==P)return;let et=null;try{et=te(P)}catch{}let It=null,F=Kt(P);if(F){let D=await be(F.name).catch(()=>!1);It={meta:F,active:D}}if(t.worktree.path!==P)return;l({commits:rt,diffStat:at,fullDiff:I,aheadBehind:Y,focus:et,session:It}),d("")}catch(rt){if(t.worktree.path!==P)return;l(null),d(rt.message)}finally{if(t.worktree.path===P)h(!1)}},Rf)}));let m=()=>{let P=t.worktree;if(P.isLocked)return"\uD83D\uDD12 locked";if(P.isDirty)return"\u25CF dirty";return"\u2713 clean"},b=()=>{let P=t.worktree;if(P.isLocked)return f.text.warning;if(P.isDirty)return f.text.error;return f.text.success},$=()=>{let P=c();if(!P)return"";let rt=[];if(P.aheadBehind.ahead>0)rt.push(`\u2191${P.aheadBehind.ahead}`);if(P.aheadBehind.behind>0)rt.push(`\u2193${P.aheadBehind.behind}`);return rt.length>0?rt.join(" "):"\u2713 up to date"},E=()=>{let P=c();if(!P)return f.text.secondary;return P.aheadBehind.ahead||P.aheadBehind.behind?f.text.warning:f.text.success},R=()=>"\u2500".repeat(Math.max(i()-7,10));return React.createElement("box",{x:0,y:0,width:i(),height:s(),backgroundColor:f.bg.base},React.createElement("scrollbox",{x:2,y:1,width:i()-3,height:s()-3},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},"Worktree Detail"),React.createElement("text",{x:17,y:0,fg:f.text.secondary,selectable:!0},"(Esc to close)")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Branch")),React.createElement("text",{selectable:!0,fg:f.text.accent},t.worktree.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Path")),React.createElement("text",{selectable:!0,fg:f.text.primary},t.worktree.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Status")),React.createElement("text",{selectable:!0,fg:b()},m())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"HEAD")),React.createElement("text",{selectable:!0,fg:f.text.secondary},t.worktree.head?.slice(0,8))),React.createElement(O,{when:a()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement(go,{label:"Loading details..."}))),React.createElement(O,{when:!a()&&!!u()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error,selectable:!0},`Failed to load details: ${u()}`))),React.createElement(O,{when:!a()&&!u()&&!!c()},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},"Upstream")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Sync")),React.createElement("text",{selectable:!0,fg:E()},$())),React.createElement(O,{when:c().aheadBehind.ahead>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Ahead")),React.createElement("text",{selectable:!0,fg:f.text.warning},`${c().aheadBehind.ahead} commit(s)`))),React.createElement(O,{when:c().aheadBehind.behind>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Behind")),React.createElement("text",{selectable:!0,fg:f.text.warning},`${c().aheadBehind.behind} commit(s)`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},"Recent Commits")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement(O,{when:c().commits.length>0,fallback:React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"No commits found"))},React.createElement($t,{each:c().commits},(P)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.primary,selectable:!0},P)))),React.createElement(O,{when:!t.worktree.isMain},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},`Diff vs ${x()}`)),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement(O,{when:c().diffStat.length>0},React.createElement("code",{language:"diff",code:c().diffStat})),React.createElement("box",{height:1}),React.createElement(O,{when:c().fullDiff.length>0,fallback:React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"No changes"))},React.createElement("scrollbox",{height:15,width:i()-3},React.createElement("diff",{diff:c().fullDiff,view:"unified"})))),React.createElement(O,{when:c().focus&&c().focus.length>0},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},"Focus Paths")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement($t,{each:c().focus},(P)=>React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.primary,selectable:!0},` \u2022 ${P}`)))),React.createElement(O,{when:c().session},React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.accent,bold:!0,selectable:!0},"Session")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Name")),React.createElement("text",{selectable:!0,fg:f.text.primary},c().session.meta.name)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Status")),React.createElement("text",{selectable:!0,fg:c().session.active?f.text.success:f.text.error},c().session.active?"\u25CF active":"\u25CB inactive")),React.createElement(O,{when:c().session.meta.layout},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Layout")),React.createElement("text",{selectable:!0,fg:f.text.primary},c().session.meta.layout)))),React.createElement(O,{when:t.worktree.isMain},React.createElement("box",{height:1}),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:ee,height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Type")),React.createElement("text",{selectable:!0,fg:f.text.accent},"main worktree")))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle,selectable:!0},R())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary,selectable:!0},"Esc:back d:delete o:open r:refresh"))))}async function Mf(t){try{let e=Bun.spawn(["git","log","--oneline","-10"],{cwd:t,stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}}),o=await new Response(e.stdout).text();if(await e.exited,e.exitCode!==0)return[];return o.trim().split(`
11
+ `).filter(Boolean)}catch{return[]}}var Rf=150,ee=16;var ws=H(()=>{Et();xe();No();jt();ge();Le();st();Sn()});import{useKeyboard as Of,useTerminalDimensions as Wf}from"@opentui/solid";function bs(){let t=Rt(),e=Ot(),o=Wf(),n=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let $=m.find((E)=>E.path===b);if($)return $}return m[t.selectedWorktreeIndex()]},r=()=>o().width,i=14,[s,c]=N(null),[l,a]=N(!1),[h,u]=N(""),d;ce(()=>{if(d)clearTimeout(d)}),ie(De(()=>n()?.path,(m)=>{if(d)clearTimeout(d);if(!m){c(null),a(!1),u("");return}c(null),a(!0),u(""),d=setTimeout(async()=>{let b=n();if(!b||b.path!==m)return;try{let[$,E,R]=await Promise.all([b.branch?M.getAheadBehind(b.branch,b.path):Promise.resolve({ahead:0,behind:0}),M.getLastCommit(b.path),M.getDirtyCount(b.path)]);if(n()?.path===m)c({aheadBehind:$,lastCommit:E,dirtyCount:R}),u("")}catch($){if(n()?.path===m)c(null),u($.message)}finally{if(n()?.path===m)a(!1)}},Df)}));let g=()=>{if(l())return"Loading...";if(h())return"Unavailable";let m=s();if(!m)return"";let b=[];if(m.aheadBehind.ahead>0)b.push(`\u2191${m.aheadBehind.ahead}`);if(m.aheadBehind.behind>0)b.push(`\u2193${m.aheadBehind.behind}`);return b.length>0?b.join(" "):"\u2713 up to date"},x=()=>{let m=n();if(!m)return"";if(m.isLocked)return"\uD83D\uDD12 locked";let b=s();if(b&&b.dirtyCount>0)return`\u25CF ${b.dirtyCount} file(s) dirty`;if(m.isDirty)return"\u25CF dirty";return"\u2713 clean"};return Of((m)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;let b=m.name;if(b==="x"&&t.selectedWorktrees().size>0){t.setShowBulkActions(!0);return}if(b==="return"&&!t.showDetailView()&&n()){t.setShowDetailView(!0);return}if(b==="escape"&&t.showDetailView()){t.setShowDetailView(!1);return}}),React.createElement("box",{width:"100%",height:"100%",backgroundColor:f.bg.base},React.createElement(O,{when:t.showDetailView()&&!!n()},React.createElement(gs,{worktree:n()})),React.createElement(O,{when:!t.showDetailView()},React.createElement(O,{when:e.loading()},React.createElement(go,{label:"Loading worktrees..."})),React.createElement(O,{when:!e.loading()&&!!e.error()},React.createElement("text",{x:2,y:2,fg:f.text.error},"Error: ",e.error()?.message),React.createElement("text",{x:2,y:3,fg:f.text.secondary},"Not in a git repository?")),React.createElement(O,{when:!e.loading()&&!e.error()&&!!n()},React.createElement("box",{width:"100%",height:"100%",flexDirection:"column",backgroundColor:f.bg.surface,paddingX:2,paddingY:1},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("text",{fg:f.text.accent},"Worktree Details")),React.createElement("box",{height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement(O,{when:e.isMultiRepo()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Repo")),React.createElement("text",{fg:f.text.warning},n()?.repoName))),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},n()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},n()?.path)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Status")),React.createElement("text",{fg:n()?.isDirty?f.text.error:n()?.isLocked?f.text.warning:f.text.success},x())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Sync")),React.createElement("text",{fg:h()?f.text.error:l()?f.text.secondary:s()?.aheadBehind?.ahead||s()?.aheadBehind?.behind?f.text.warning:f.text.success},g())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"HEAD")),React.createElement("text",{fg:f.text.secondary},n()?.head?.slice(0,8))),React.createElement(O,{when:s()?.lastCommit},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Last Commit")),React.createElement("text",{fg:f.text.primary},s().lastCommit.relativeDate)),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"")),React.createElement("text",{fg:f.text.secondary},s().lastCommit.message.length>50?s().lastCommit.message.slice(0,47)+"...":s().lastCommit.message))),React.createElement(O,{when:(()=>{let m=te(n()?.path??"");return m&&m.length>0})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},te(n()?.path??"")?.join(", ")??""))),React.createElement(O,{when:(()=>{return!!Kt(n()?.path??"")})()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Session")),React.createElement("text",{fg:f.text.accent},(()=>{let m=Kt(n()?.path??"");if(!m)return"";return m.layout?`${m.name} [${m.layout}]`:m.name})()))),React.createElement(O,{when:n()?.isMain},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Type")),React.createElement("text",{fg:f.text.accent},"main worktree"))),React.createElement("box",{height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(r()-38,10)))),React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:detail"),React.createElement("text",{fg:f.text.secondary},"d:delete"),React.createElement("text",{fg:f.text.secondary},"a:add"),React.createElement("text",{fg:f.text.secondary},"o:open"),React.createElement("text",{fg:f.text.secondary},"r:refresh"),React.createElement("text",{fg:f.text.secondary},"^P:commands")))),React.createElement(O,{when:!e.loading()&&!e.error()&&!n()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.secondary},"No worktree selected."),React.createElement("text",{fg:f.text.accent},"Press 'a' to create one.")))))}var Df=150;var Cs=H(()=>{Et();ae();xe();jt();ge();Le();st();ws();Sn()});import{join as Pr,resolve as $n}from"path";import*as Ie from"fs";function he(t,e,o){if(!Array.isArray(t)||t.some((n)=>typeof n!=="string"))o.push({field:e,message:"Must be an array of strings"})}function ys(){let e=Bun.env.XDG_CONFIG_HOME??Pr(Bun.env.HOME??"~",".config");return Pr(e,"oh-my-worktree")}function kt(){return Pr(ys(),"config.json")}function zo(t){let e=[];if(typeof t!=="object"||t===null)return e.push({field:"root",message:"Config must be a JSON object"}),e;let o=t;if(!("version"in o))e.push({field:"version",message:"Required field 'version' is missing"});else if(o.version!==1)e.push({field:"version",message:`Expected version 1, got ${JSON.stringify(o.version)}`});for(let n of Object.keys(o))if(!Ff.has(n))e.push({field:n,message:`Unknown field '${n}'`});if("defaults"in o&&o.defaults!==void 0)if(typeof o.defaults!=="object"||o.defaults===null)e.push({field:"defaults",message:"Must be an object"});else{let n=o.defaults;for(let r of Object.keys(n))if(!Bf.has(r))e.push({field:`defaults.${r}`,message:`Unknown field '${r}'`});if("worktreeDir"in n&&typeof n.worktreeDir!=="string")e.push({field:"defaults.worktreeDir",message:"Must be a string"});if("autoUpstream"in n&&typeof n.autoUpstream!=="boolean")e.push({field:"defaults.autoUpstream",message:"Must be a boolean"});for(let r of["copyFiles","linkFiles","postCreate","postRemove"])if(r in n)he(n[r],`defaults.${r}`,e);if("sharedDeps"in n&&n.sharedDeps!==void 0)if(typeof n.sharedDeps!=="object"||n.sharedDeps===null)e.push({field:"defaults.sharedDeps",message:"Must be an object"});else Ss(n.sharedDeps,"defaults.sharedDeps",e)}if("repos"in o&&o.repos!==void 0)if(!Array.isArray(o.repos))e.push({field:"repos",message:"Must be an array"});else for(let n=0;n<o.repos.length;n++){let r=o.repos[n],i=`repos[${n}]`;if(typeof r!=="object"||r===null){e.push({field:i,message:"Must be an object"});continue}let s=r;for(let c of Object.keys(s))if(!Lf.has(c))e.push({field:`${i}.${c}`,message:`Unknown field '${c}'`});if(!("path"in s)||typeof s.path!=="string")e.push({field:`${i}.path`,message:"Required string field 'path' is missing"});if("worktreeDir"in s&&typeof s.worktreeDir!=="string")e.push({field:`${i}.worktreeDir`,message:"Must be a string"});if("autoUpstream"in s&&typeof s.autoUpstream!=="boolean")e.push({field:`${i}.autoUpstream`,message:"Must be a boolean"});for(let c of["copyFiles","linkFiles","postCreate","postRemove"])if(c in s)he(s[c],`${i}.${c}`,e);if("sharedDeps"in s&&s.sharedDeps!==void 0)if(typeof s.sharedDeps!=="object"||s.sharedDeps===null)e.push({field:`${i}.sharedDeps`,message:"Must be an object"});else Ss(s.sharedDeps,`${i}.sharedDeps`,e);if("monorepo"in s&&s.monorepo!==void 0)if(typeof s.monorepo!=="object"||s.monorepo===null)e.push({field:`${i}.monorepo`,message:"Must be an object"});else{let c=s.monorepo;for(let l of Object.keys(c))if(!If.has(l))e.push({field:`${i}.monorepo.${l}`,message:`Unknown field '${l}'`});if("autoDetect"in c&&typeof c.autoDetect!=="boolean")e.push({field:`${i}.monorepo.autoDetect`,message:"Must be a boolean"});if("extraPatterns"in c&&c.extraPatterns!==void 0)he(c.extraPatterns,`${i}.monorepo.extraPatterns`,e);if("hooks"in c&&c.hooks!==void 0)if(!Array.isArray(c.hooks))e.push({field:`${i}.monorepo.hooks`,message:"Must be an array"});else for(let l=0;l<c.hooks.length;l++){let a=c.hooks[l];if(typeof a!=="object"||a===null){e.push({field:`${i}.monorepo.hooks[${l}]`,message:"Must be an object"});continue}if(!("glob"in a)||typeof a.glob!=="string")e.push({field:`${i}.monorepo.hooks[${l}].glob`,message:"Required string field"});if("copyFiles"in a&&a.copyFiles!==void 0)he(a.copyFiles,`${i}.monorepo.hooks[${l}].copyFiles`,e);if("linkFiles"in a&&a.linkFiles!==void 0)he(a.linkFiles,`${i}.monorepo.hooks[${l}].linkFiles`,e);if("postCreate"in a&&a.postCreate!==void 0)he(a.postCreate,`${i}.monorepo.hooks[${l}].postCreate`,e);if("postRemove"in a&&a.postRemove!==void 0)he(a.postRemove,`${i}.monorepo.hooks[${l}].postRemove`,e)}}}if("templates"in o&&o.templates!==void 0)if(typeof o.templates!=="object"||o.templates===null||Array.isArray(o.templates))e.push({field:"templates",message:"Must be an object (key-value map)"});else{let n=o.templates;for(let[r,i]of Object.entries(n)){let s=`templates.${r}`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i;for(let l of Object.keys(c))if(!Af.has(l))e.push({field:`${s}.${l}`,message:`Unknown field '${l}'`});if("worktreeDir"in c&&typeof c.worktreeDir!=="string")e.push({field:`${s}.worktreeDir`,message:"Must be a string"});if("base"in c&&typeof c.base!=="string")e.push({field:`${s}.base`,message:"Must be a string"});if("autoUpstream"in c&&typeof c.autoUpstream!=="boolean")e.push({field:`${s}.autoUpstream`,message:"Must be a boolean"});for(let l of["copyFiles","linkFiles","postCreate","postRemove"])if(l in c)he(c[l],`${s}.${l}`,e)}}if("lifecycle"in o&&o.lifecycle!==void 0)if(typeof o.lifecycle!=="object"||o.lifecycle===null)e.push({field:"lifecycle",message:"Must be an object"});else{let n=o.lifecycle;for(let r of Object.keys(n))if(!jf.has(r))e.push({field:`lifecycle.${r}`,message:`Unknown field '${r}'`});if("autoCleanMerged"in n&&typeof n.autoCleanMerged!=="boolean")e.push({field:"lifecycle.autoCleanMerged",message:"Must be a boolean"});if("staleAfterDays"in n&&(typeof n.staleAfterDays!=="number"||n.staleAfterDays<1))e.push({field:"lifecycle.staleAfterDays",message:"Must be a positive number"});if("maxWorktrees"in n&&(typeof n.maxWorktrees!=="number"||n.maxWorktrees<1))e.push({field:"lifecycle.maxWorktrees",message:"Must be a positive number"})}if("sessions"in o&&o.sessions!==void 0)if(typeof o.sessions!=="object"||o.sessions===null)e.push({field:"sessions",message:"Must be an object"});else{let n=o.sessions;for(let r of Object.keys(n))if(!_f.has(r))e.push({field:`sessions.${r}`,message:`Unknown field '${r}'`});for(let r of["enabled","autoCreate","autoKill"])if(r in n&&typeof n[r]!=="boolean")e.push({field:`sessions.${r}`,message:"Must be a boolean"});if("prefix"in n&&typeof n.prefix!=="string")e.push({field:"sessions.prefix",message:"Must be a string"});if("defaultLayout"in n&&typeof n.defaultLayout!=="string")e.push({field:"sessions.defaultLayout",message:"Must be a string"});if("layouts"in n&&n.layouts!==void 0)if(typeof n.layouts!=="object"||n.layouts===null||Array.isArray(n.layouts))e.push({field:"sessions.layouts",message:"Must be an object (key-value map)"});else{let r=n.layouts;for(let[i,s]of Object.entries(r)){let c=`sessions.layouts.${i}`;if(typeof s!=="object"||s===null){e.push({field:c,message:"Must be an object"});continue}let l=s;if(!("windows"in l)||!Array.isArray(l.windows))e.push({field:`${c}.windows`,message:"Required array field"});else for(let a=0;a<l.windows.length;a++){let h=l.windows[a];if(typeof h!=="object"||h===null){e.push({field:`${c}.windows[${a}]`,message:"Must be an object"});continue}if(!("name"in h)||typeof h.name!=="string")e.push({field:`${c}.windows[${a}].name`,message:"Required string field"});if("command"in h&&typeof h.command!=="string")e.push({field:`${c}.windows[${a}].command`,message:"Must be a string"})}}}if("defaultLayout"in n&&typeof n.defaultLayout==="string"&&"layouts"in n&&typeof n.layouts==="object"&&n.layouts!==null){let r=n.layouts;if(!(n.defaultLayout in r))e.push({field:"sessions.defaultLayout",message:`Layout '${n.defaultLayout}' does not exist in sessions.layouts`})}}if("profiles"in o&&o.profiles!==void 0)if(typeof o.profiles!=="object"||o.profiles===null||Array.isArray(o.profiles))e.push({field:"profiles",message:"Must be an object (key-value map)"});else{let n=o.profiles;for(let[r,i]of Object.entries(n)){let s=`profiles.${r}`;if(typeof i!=="object"||i===null){e.push({field:s,message:"Must be an object"});continue}let c=i;for(let l of Object.keys(c))if(!Tf.has(l))e.push({field:`${s}.${l}`,message:`Unknown field '${l}'`})}}if("activeProfile"in o&&o.activeProfile!==void 0){if(typeof o.activeProfile!=="string")e.push({field:"activeProfile",message:"Must be a string"});else if("profiles"in o&&o.profiles!==void 0&&typeof o.profiles==="object"&&o.profiles!==null&&!Array.isArray(o.profiles)){let n=o.profiles;if(!(o.activeProfile in n))e.push({field:"activeProfile",message:`Profile '${o.activeProfile}' does not exist in profiles`})}else if(!("profiles"in o)||o.profiles===void 0)e.push({field:"activeProfile",message:"Cannot set activeProfile without profiles"})}return e}function Ss(t,e,o){let n=new Set(["strategy","paths","invalidateOn"]);for(let r of Object.keys(t))if(!n.has(r))o.push({field:`${e}.${r}`,message:`Unknown field '${r}'`});if("strategy"in t&&!["hardlink","symlink","copy"].includes(t.strategy))o.push({field:`${e}.strategy`,message:'Must be "hardlink", "symlink", or "copy"'});if("paths"in t)he(t.paths,`${e}.paths`,o);if("invalidateOn"in t)he(t.invalidateOn,`${e}.invalidateOn`,o)}function Jo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function ro(t){if(Array.isArray(t))return t.map((e)=>ro(e));if(Jo(t)){let e={};for(let[o,n]of Object.entries(t))e[o]=ro(n);return e}return t}function Es(t,e){if(e===void 0)return ro(t);if(Array.isArray(e))return e.map((r)=>ro(r));if(!Jo(e))return ro(e);let o=Jo(t)?t:{},n={};for(let[r,i]of Object.entries(o))n[r]=ro(i);for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let s=o[r];if(Jo(s)&&Jo(i)){n[r]=Es(s,i);continue}n[r]=ro(i)}return n}function Gf(t){if(!t.activeProfile)return structuredClone(t);let e=t.profiles?.[t.activeProfile];if(!e||typeof e!=="object"||Array.isArray(e))throw Error(`Active profile '${t.activeProfile}' does not exist`);return Es(t,e)}function Q(t){let e=t??kt();if(!Ie.existsSync(e))return structuredClone(Ps);let o;try{let s=Pn.readFileSync(e,"utf-8");o=JSON.parse(s)}catch(s){let c=s.message;if(c.includes("JSON"))throw Error(`Invalid JSON in config file: ${c}`);if(s instanceof SyntaxError)throw Error(`Invalid JSON in config file: ${c}`);throw Error(`Failed to read config file: ${c}`)}let n=zo(o);if(n.length>0){let s=n.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed: ${s}`)}let r=Gf(o),i=zo(r);if(i.length>0){let s=i.map((c)=>`${c.field}: ${c.message}`).join("; ");throw Error(`Config validation failed after applying activeProfile: ${s}`)}return r}function Lt(t,e){let o=$n(e),n=t.repos?.find((r)=>$n(r.path)===o);return{worktreeDir:n?.worktreeDir??t.defaults?.worktreeDir??wo.worktreeDir,copyFiles:n?.copyFiles??t.defaults?.copyFiles??wo.copyFiles,linkFiles:n?.linkFiles??t.defaults?.linkFiles??wo.linkFiles,postCreate:n?.postCreate??t.defaults?.postCreate??wo.postCreate,postRemove:n?.postRemove??t.defaults?.postRemove??wo.postRemove,autoUpstream:n?.autoUpstream??t.defaults?.autoUpstream??wo.autoUpstream,monorepo:n?.monorepo,sharedDeps:n?.sharedDeps??t.defaults?.sharedDeps}}function Ae(t){return(t.repos??[]).map((e)=>$n(e.path))}function yn(t,e){let o=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,o).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}function ue(t){let e=t??kt(),o=t?$n(e,".."):ys();if(!Ie.existsSync(o))Pn.mkdirSync(o,{recursive:!0,mode:448});if(Ie.existsSync(e))return e;return Uo(e,`${JSON.stringify(Ps,null,2)}
12
+ `),e}function En(t,e){return t.templates?.[e]}function Rn(t,e){return{worktreeDir:e.worktreeDir??t.worktreeDir,copyFiles:e.copyFiles??t.copyFiles,linkFiles:e.linkFiles??t.linkFiles,postCreate:e.postCreate??t.postCreate,postRemove:e.postRemove??t.postRemove,autoUpstream:e.autoUpstream??t.autoUpstream,monorepo:t.monorepo,sharedDeps:t.sharedDeps}}function je(t){return t.sessions??{}}function Mn(t,e){let o=t.sessions;if(!o?.layouts)return;let n=e??o.defaultLayout;if(!n)return;return o.layouts[n]}function Uo(t,e){let o=`${t}.tmp.${Date.now()}`;try{Ie.writeFileSync(o,e,{encoding:"utf-8",mode:384});let n=JSON.parse(e),r=zo(n);if(r.length>0)throw Error(`Validation failed: ${r.map((i)=>i.message).join("; ")}`);Pn.renameSync(o,t)}catch(n){if(Ie.existsSync(o))Pn.unlinkSync(o);throw n}}var Pn,$s="~/.omw/worktrees/{repo}-{branch}",Ps,wo,Ff,Bf,Lf,If,Af,jf,_f,Tf;var St=H(()=>{Pn=Ie,Ps={version:1,defaults:{worktreeDir:$s,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0},repos:[]},wo={worktreeDir:$s,copyFiles:[],linkFiles:[],postCreate:[],postRemove:[],autoUpstream:!0,sharedDeps:void 0};Ff=new Set(["version","defaults","repos","$schema","theme","templates","lifecycle","sessions","profiles","activeProfile"]),Bf=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","sharedDeps"]),Lf=new Set(["path","worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","monorepo","sharedDeps"]),If=new Set(["autoDetect","extraPatterns","hooks"]),Af=new Set(["worktreeDir","copyFiles","linkFiles","postCreate","postRemove","autoUpstream","base"]),jf=new Set(["autoCleanMerged","staleAfterDays","maxWorktrees"]),_f=new Set(["enabled","autoCreate","autoKill","prefix","defaultLayout","layouts"]),Tf=new Set(["defaults","repos","theme","templates","lifecycle","sessions"])});import*as vf from"fs";import{join as _e,resolve as Ce,dirname as Vo}from"path";function Co(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=_e(Ce(t),r),s=_e(Ce(e),r);if(!Se(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping copy: ${r}`);continue}if(Se(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping copy: ${r}`);continue}try{bo(Vo(s),{recursive:!0}),Ms(i,s),n.copied.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to copy ${r}: ${c.message}`)}}return n}function So(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]};for(let r of o){let i=Ce(_e(Ce(t),r)),s=_e(Ce(e),r);if(!Se(i)){n.skipped.push(r),n.warnings.push(`Source not found, skipping symlink: ${r}`);continue}if(Se(s)){n.skipped.push(r),n.warnings.push(`Target already exists, skipping symlink: ${r}`);continue}try{bo(Vo(s),{recursive:!0}),Os(i,s),n.linked.push(r)}catch(c){n.skipped.push(r),n.warnings.push(`Failed to symlink ${r}: ${c.message}`)}}return n}function Ws(t,e,o=0){let n=0,r=[];if(o>Jf)return{linked:0,errors:[`Max directory depth exceeded at ${t}`]};let i=Ce(t),s=Ce(e);if(!Se(i))return{linked:0,errors:[`Source not found: ${t}`]};let c=Nf(i,{throwIfNoEntry:!1});if(!c||!c.isDirectory())try{return bo(Vo(s),{recursive:!0}),Rs(i,s),{linked:1,errors:[]}}catch(l){return{linked:0,errors:[`Failed to hardlink ${t}: ${l.message}`]}}if(!Se(s))bo(s,{recursive:!0});try{let l=kf(i,{withFileTypes:!0});for(let a of l){let h=_e(i,a.name),u=_e(s,a.name);if(a.isDirectory()){let d=Ws(h,u,o+1);if(n+=d.linked,d.errors.length>0)r.push(...d.errors)}else if(a.isFile()){if(Se(u))continue;try{Rs(h,u),n++}catch(d){try{Ms(h,u),n++}catch(g){r.push(`Failed to link/copy ${a.name}: ${g.message}`)}}}}}catch(l){r.push(`Failed to read directory ${t}: ${l.message}`)}return{linked:n,errors:r}}function Ds(t,e,o){let n={copied:[],linked:[],skipped:[],warnings:[]},r=o.paths??[],i=o.strategy??"symlink";for(let s of r){let c=_e(Ce(t),s),l=_e(Ce(e),s);if(!Se(c)){n.skipped.push(s),n.warnings.push(`Source not found, skipping shared dep: ${s}`);continue}if(Se(l)){n.skipped.push(s);continue}try{if(i==="symlink")bo(Vo(l),{recursive:!0}),Os(c,l),n.linked.push(s);else if(i==="hardlink"){let a=Ws(c,l);if(a.linked>0)n.linked.push(s);for(let h of a.errors)n.warnings.push(h)}else bo(Vo(l),{recursive:!0}),Hf(c,l,{recursive:!0}),n.copied.push(s)}catch(a){n.skipped.push(s),n.warnings.push(`Failed to share dep ${s}: ${a.message}`)}}return n}var Ms,Hf,Se,Os,tg,Rs,kf,Nf,bo,Jf=30;var On=H(()=>{({copyFileSync:Ms,cpSync:Hf,existsSync:Se,symlinkSync:Os,unlinkSync:tg,linkSync:Rs,readdirSync:kf,statSync:Nf,mkdirSync:bo}=vf)});import{existsSync as zf,mkdirSync as Uf}from"fs";async function Wt(t,e){let o=e.timeout??30000;for(let n of t)await Vf(n,e.cwd,o,e.env??{},e.onOutput)}async function Vf(t,e,o,n,r){if(!zf(e))Uf(e,{recursive:!0});let i;try{i=Bun.spawn(["sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}catch(a){if(a.code!=="ENOENT")throw a;i=Bun.spawn(["/bin/sh","-c",t],{cwd:e,env:{...process.env,...n},stdout:"pipe",stderr:"pipe"})}let s=!1,c=setTimeout(()=>{s=!0,i.kill()},o),l=i.stderr?new Response(i.stderr).text():Promise.resolve("");try{if(r&&i.stdout){let h=i.stdout.getReader(),u=new TextDecoder,d=[];while(!0){let{done:x,value:m}=await h.read();if(x)break;let $=u.decode(m,{stream:!0}).split(`
13
+ `);if($.length===1)d.push($[0]);else{d.push($[0]);let E=d.join("");if(d.length=0,E)r(E);for(let P=1;P<$.length-1;P++)if($[P])r($[P]);let R=$[$.length-1];if(R)d.push(R)}}let g=d.join("")+u.decode();if(g)r(g)}let a=await i.exited;if(s)throw new Po(t,o);if(a!==0){let h=(await l).trim();throw new $o(t,a,h)}}finally{clearTimeout(c)}}var $o,Po;var $e=H(()=>{$o=class $o extends Error{command;exitCode;stderr;constructor(t,e,o){super(`Hook command failed (exit ${e}): ${t}
14
+ ${o}`);this.command=t;this.exitCode=e;this.stderr=o;this.name="HookError"}};Po=class Po extends Error{command;timeoutMs;constructor(t,e){super(`Hook command timed out after ${e}ms: ${t}`);this.command=t;this.timeoutMs=e;this.name="HookTimeoutError"}}});import{existsSync as Kf,readdirSync as ig,readFileSync as sg,statSync as Xf}from"fs";import{join as qf,relative as ag}from"path";function Wn(t,e){let o=[],n=[];for(let r of e){let i=r.trim();if(!i){n.push(i);continue}let s=qf(t,i);try{if(Kf(s)&&Xf(s).isDirectory())o.push(i);else n.push(i)}catch{n.push(i)}}return{valid:o,invalid:n}}var yr=()=>{};function io(t,e){return t.map((o)=>{let n=new Bun.Glob(o.glob),r=e.filter((i)=>n.match(i));return{glob:o.glob,matchedPaths:r,copyFiles:o.copyFiles??[],linkFiles:o.linkFiles??[],postCreate:o.postCreate??[],postRemove:o.postRemove??[]}}).filter((o)=>o.matchedPaths.length>0)}function Zf(t,e){return t.replace(/\{packagePath\}/g,e.packagePath).replace(/\{repo\}/g,e.repo).replace(/\{branch\}/g,e.branch)}async function yo(t,e,o){for(let n of t){let r=n[e],i=e==="postCreate"&&n.copyFiles.length>0,s=e==="postCreate"&&n.linkFiles.length>0,c=r.length>0;if(!i&&!s&&!c)continue;for(let l of n.matchedPaths){let{join:a}=await import("path"),h=a(o.mainRepoPath,l),u=a(o.cwd,l);if(i){let d=Co(h,u,n.copyFiles);for(let g of d.copied)o.onOutput?.(`Copied ${l}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(s){let d=So(h,u,n.linkFiles);for(let g of d.linked)o.onOutput?.(`Linked ${l}/${g}`);for(let g of d.warnings)o.onOutput?.(`\u26A0 ${g}`)}if(c){let d=r.map((x)=>Zf(x,{packagePath:l,repo:o.repo,branch:o.branch})),g={...o.env??{},OMW_FOCUS_PATHS:o.focusPaths.join(","),OMW_PACKAGE_PATH:l};await Wt(d,{cwd:o.cwd,timeout:o.timeout,env:g,onOutput:o.onOutput})}}}}var Dn=H(()=>{$e();On()});import{useTerminalDimensions as Qf}from"@opentui/solid";function Te(t){let e=Qf(),o=()=>Math.max(0,Math.floor((e().width-t.width)/2)),n=()=>Math.max(0,Math.floor((e().height-t.height)/2)),r=()=>React.createElement("box",{x:o(),y:n(),width:t.width,height:t.height,border:!0,borderStyle:"rounded",borderColor:t.borderColor??f.border.active,backgroundColor:t.backgroundColor??f.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:t.gap??0,title:t.title,titleAlignment:"left",position:"absolute"},t.children,React.createElement(O,{when:t.footer},t.footer));return React.createElement(O,{when:t.backdrop,fallback:r()},React.createElement("box",{x:0,y:0,width:e().width,height:e().height,backgroundColor:t.backdropColor??f.bg.overlay,position:"absolute"},r()))}var Ko=H(()=>{Et();jt()});import{useKeyboard as Yf,usePaste as th,useTerminalDimensions as eh}from"@opentui/solid";import{decodePasteBytes as oh}from"@opentui/core";import{basename as Fs,resolve as nh}from"path";function Bs(){let t=Rt(),e=Ot(),o=eh(),[n,r]=N("input"),[i,s]=N(""),[c,l]=N(""),[a,h]=N("branch"),[u,d]=N(""),[g,x]=N([]),[m,b]=N(""),[$,E]=N([]),[R,P]=N(-1),[rt,at]=N(!1),I=()=>{let J=i().toLowerCase();if(!J)return $().slice(0,10);return $().filter((G)=>G.name.toLowerCase().includes(J)).slice(0,10)};ie(De(()=>et(),async()=>{try{let J=et(),G=await M.listBranches(J);E(G)}catch{E([])}})),un(()=>{queueMicrotask(()=>{s(""),l("")})}),ie(De(i,()=>{P(-1),at(i().length>0&&I().length>0)})),ie(De(n,(J)=>{t.setInputFocused(J==="input")})),ce(()=>{t.setInputFocused(!1)});let Y=(J,G)=>{x((it)=>it.map((dt,j)=>j===J?{...dt,...G}:dt))},et=()=>{let J=e.worktrees()??[],G=t.selectedWorktreePath();return(G?J.find((dt)=>dt.path===G)??J[t.selectedWorktreeIndex()]:J[t.selectedWorktreeIndex()])?.repoPath??t.repoPath()},It=()=>{let J=e.worktrees()??[],G=t.selectedWorktreePath();return(G?J.find((dt)=>dt.path===G)??J[t.selectedWorktreeIndex()]:J[t.selectedWorktreeIndex()])?.repoName??t.repoPath().split("/").pop()??""},F=()=>{let J=i();if(!J)return"";let G=et(),it=Q(),dt=Lt(it,G),j=J.replace(/\//g,"-"),oe=Fs(G);return nh(yn(dt.worktreeDir,{repo:oe,branch:j}))};Yf(async(J)=>{if(t.activeTab()!=="add")return;if(t.showCommandPalette())return;let G=J.name;if(G==="escape"){if(n()==="preview"){r("input");return}t.setActiveTab("list"),s(""),l(""),h("branch"),r("input");return}if(n()==="input"){if(G==="tab"){if(rt()&&a()==="branch")at(!1),P(-1);h((it)=>it==="branch"?"focus":"branch");return}if(a()==="branch"&&rt()&&I().length>0){if(G==="down"||J.sequence==="\x1B[B"){P((it)=>Math.min(it+1,I().length-1));return}if(G==="up"||J.sequence==="\x1B[A"){P((it)=>Math.max(it-1,-1));return}}if(G==="return"||G==="enter"){if(a()==="branch"&&R()>=0){let it=I()[R()];if(it){s(it.name),at(!1),P(-1);return}}if(!i())return;at(!1),d(F()),r("preview");return}}if(n()==="preview"){if(G==="return"||G==="enter"){r("creating");let it=i(),dt=u(),j=et(),oe=Fs(j);try{let Pe=Q(),B=Lt(Pe,j),ot=[{label:"Creating worktree",status:"pending"}];if(B.autoUpstream)ot.push({label:"Setting upstream",status:"pending"});if(B.copyFiles.length>0)ot.push({label:"Copying files",status:"pending"});if(B.linkFiles.length>0)ot.push({label:"Creating symlinks",status:"pending"});if(B.postCreate.length>0)ot.push({label:"Running hooks",status:"pending"});let pt=c(),U=[];if(pt)U=pt.split(/[,\s]+/).map((nt)=>nt.trim()).filter(Boolean);if(U.length>0)ot.push({label:"Setting focus",status:"pending"});if(U.length>0&&B.monorepo?.hooks&&B.monorepo.hooks.length>0){if(io(B.monorepo.hooks,U).length>0)ot.push({label:"Running monorepo hooks",status:"pending"})}x(ot);let Z=0;if(Y(Z,{status:"running"}),await M.add(it,dt,{createBranch:!0},j),Y(Z,{status:"done"}),Z++,B.autoUpstream){Y(Z,{status:"running"});try{let nt=await M.getDefaultRemote(j);if(await M.remoteBranchExists(it,nt,j))await M.setUpstream(it,nt,j),Y(Z,{status:"done",message:`\u2192 ${nt}/${it}`});else Y(Z,{status:"done",message:"no remote branch"})}catch(nt){Y(Z,{status:"error",message:nt.message})}Z++}if(B.copyFiles.length>0)Y(Z,{status:"running"}),Co(j,dt,B.copyFiles),Y(Z,{status:"done"}),Z++;if(B.linkFiles.length>0)Y(Z,{status:"running"}),So(j,dt,B.linkFiles),Y(Z,{status:"done"}),Z++;let lt={OMW_BRANCH:it,OMW_WORKTREE_PATH:dt,OMW_REPO_PATH:j};if(B.postCreate.length>0)Y(Z,{status:"running"}),await Wt(B.postCreate,{cwd:dt,env:lt,onOutput:(nt)=>Y(Z,{message:nt})}),Y(Z,{status:"done"}),Z++;if(U.length>0){Y(Z,{status:"running"});let{valid:nt}=Wn(dt,U);if(U=nt,nt.length>0)uo(dt,nt),lt.OMW_FOCUS_PATHS=nt.join(",");Y(Z,{status:"done"}),Z++}if(U.length>0&&B.monorepo?.hooks&&B.monorepo.hooks.length>0){Y(Z,{status:"running"});let nt=io(B.monorepo.hooks,U);if(nt.length>0)await yo(nt,"postCreate",{cwd:dt,env:lt,repo:oe,branch:it,focusPaths:U,mainRepoPath:j,onOutput:(so)=>Y(Z,{message:so})});Y(Z,{status:"done"}),Z++}b("Worktree created successfully!"),r("done"),no.success(`Worktree created: ${it}`),e.refetch(),setTimeout(()=>{t.setActiveTab("list"),s(""),l(""),h("branch"),r("input")},1500)}catch(Pe){no.error(Pe.message);let ot=g().findIndex((pt)=>pt.status==="running");if(ot>=0)Y(ot,{status:"error",message:Pe.message});b(`${Pe.message}`),r("error")}return}}if(n()==="error"){if(G==="escape"||G==="return"||G==="enter")r("input"),b("")}}),th((J)=>{if(!t.inputFocused())return;let G=oh(J.bytes).replace(/\r?\n/g,"");if(!G)return;if(a()==="branch"){s((it)=>it+G);return}if(a()==="focus")l((it)=>it+G)});let D=()=>o().width,A=()=>o().height,V=()=>Math.max(50,Math.min(80,D()-4)),tt=4,mt=()=>{if(n()==="input"){let J=rt()&&a()==="branch"?I().length*2:0,G=i().length>0?4:0;return Math.max(21+tt,Math.min(21+tt+J+G,A()-4))}if(n()==="preview")return Math.max(13+tt,Math.min((c().length>0?15:13)+tt,A()-4));if(n()==="creating")return Math.max(9+tt,Math.min(g().length*2+7+tt,A()-4));if(n()==="done")return Math.max(11+tt,Math.min((c().length>0?15:13)+tt,A()-4));return Math.max(11+tt,Math.min(11+tt,A()-4))},X=()=>Math.max(V()-4,10),ut=()=>Math.max(X(),20);return React.createElement(Te,{width:V(),height:mt(),borderColor:n()==="done"?f.text.success:n()==="error"?f.text.error:f.border.active,backgroundColor:f.bg.surface,gap:1,title:" Create Worktree ",footer:React.createElement(Ig,null,React.createElement("box",{height:1,width:X()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(X(),1)))),React.createElement(O,{when:n()==="input"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Tab:switch"),React.createElement("text",{fg:f.text.secondary},"\u2191\u2193:pick"),React.createElement("text",{fg:f.text.secondary},"Enter:confirm"),React.createElement("text",{fg:f.text.secondary},"Esc:cancel"))),React.createElement(O,{when:n()==="preview"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:create"),React.createElement("text",{fg:f.text.secondary},"Esc:back"))),React.createElement(O,{when:n()==="creating"},React.createElement("text",{fg:f.text.secondary},"Creating worktree...")),React.createElement(O,{when:n()==="done"},React.createElement("text",{fg:f.text.secondary},"\u2713 Done \u2014 returning to list")),React.createElement(O,{when:n()==="error"},React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"Enter:retry"),React.createElement("text",{fg:f.text.secondary},"Esc:back"))))},React.createElement(O,{when:n()==="input"},React.createElement("box",{height:1,width:X(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"New Worktree"),React.createElement("text",{x:17,y:0,fg:f.text.secondary},It())),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(X())),React.createElement("text",{fg:a()==="branch"?f.text.accent:f.text.secondary},"Branch name"),React.createElement("input",{value:i(),onInput:(J)=>s(J),placeholder:"Branch name or search...",focused:a()==="branch",width:ut(),backgroundColor:f.bg.elevated,cursorColor:f.text.accent}),React.createElement(O,{when:rt()&&a()==="branch"&&I().length>0},React.createElement($t,{each:I()},(J,G)=>React.createElement("box",{height:1,width:X(),backgroundColor:G()===R()?f.select.focusedBg:f.bg.surface},React.createElement("text",{x:1,y:0,fg:G()===R()?f.tab.active:f.text.primary},G()===R()?"\u25B8 ":" ",J.name),React.createElement("text",{x:Math.max(1+J.name.length+4,27),y:0,fg:f.text.secondary},J.isRemote?"(remote) ":"",J.lastCommitDate)))),React.createElement("text",{fg:f.text.secondary},"Tab to switch fields \xB7 \u2191\u2193 to select branch"),React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:a()==="focus"?f.text.accent:f.text.secondary},"Focus "),React.createElement("text",{fg:f.text.secondary},"(optional)")),React.createElement("input",{value:c(),onInput:(J)=>l(J),placeholder:"apps/web,apps/api (optional)",focused:a()==="focus",width:ut(),backgroundColor:f.bg.elevated,cursorColor:f.text.accent}),React.createElement("text",{fg:f.text.secondary},"comma-separated paths, e.g. apps/web,apps/api"),React.createElement(O,{when:i().length>0},React.createElement("text",{fg:f.text.secondary},"Target path"),React.createElement("text",{fg:f.text.primary},F())),React.createElement("text",{fg:f.text.primary},"Type a branch name, e.g. feature/my-feature")),React.createElement(O,{when:n()==="preview"},React.createElement("box",{height:1,width:X(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Confirm Worktree")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(X())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},u())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},c()))),React.createElement("text",{fg:f.text.success},"\u2713 Ready to create. Press Enter to confirm.")),React.createElement(O,{when:n()==="creating"},React.createElement("box",{height:1,width:X(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.accent},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Creating Worktree")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(X())),React.createElement($t,{each:g()},(J)=>React.createElement("box",{height:1},React.createElement("text",{fg:J.status==="done"?f.text.success:J.status==="running"?f.text.accent:J.status==="error"?f.text.error:f.text.secondary},J.status==="done"?"\u2713":J.status==="running"?"\u27F3":J.status==="error"?"\u2717":"\u25CB"," ",J.label),React.createElement(O,{when:J.message},React.createElement("text",{x:J.label.length+4,y:0,fg:f.text.secondary},J.message))))),React.createElement(O,{when:n()==="done"},React.createElement("box",{height:1,width:X(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.success},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Worktree Created")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(X())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},i())),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},u())),React.createElement(O,{when:c().length>0},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:14,height:1},React.createElement("text",{fg:f.text.secondary},"Focus")),React.createElement("text",{fg:f.text.accent},c()))),React.createElement("text",{fg:f.text.success},"\u2713 ",m())),React.createElement(O,{when:n()==="error"},React.createElement("box",{height:1,width:X(),backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.error},">"),React.createElement("text",{x:3,y:0,fg:f.text.primary},"Error")),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(X())),React.createElement("text",{fg:f.text.error},"\u2717 Failed"),React.createElement("box",{width:ut(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:f.text.primary},m().slice(0,Math.max(ut()-3,10)))),React.createElement("text",{fg:f.text.secondary},"Press Enter or Escape to try again")))}var Ls=H(()=>{Et();ae();xe();st();St();On();$e();ge();yr();Dn();dr();jt();Ko()});import{useKeyboard as rh,useTerminalDimensions as ih}from"@opentui/solid";function Is(){let t=Rt(),e=Ot(),o=ih(),[n,r]=N(!1),[i,s]=N(""),[c,l]=N(!1),a=()=>{let m=e.worktrees()??[],b=t.selectedWorktreePath();if(b){let $=m.find((E)=>E.path===b);if($)return $}return m[t.selectedWorktreeIndex()]},h=()=>{t.setShowRemove(!1),r(!1),s(""),l(!1)},u=async(m)=>{let b=a();if(!b){h();return}r(!0),s("Removing...");try{let $=Q(),E=Lt($,b.repoPath);if(E.postRemove.length>0)s("Running postRemove hooks..."),await Wt(E.postRemove,{cwd:b.path,env:{OMW_BRANCH:b.branch??"",OMW_WORKTREE_PATH:b.path,OMW_REPO_PATH:b.repoPath}}).catch(()=>{});await M.remove(b.path,{force:m},b.repoPath),s("Removed successfully!"),no.success("Worktree removed");let R=e.worktrees()??[],P=t.selectedWorktreeIndex(),rt=R[P-1]??R[P+1]??null;if(P>0)t.setSelectedWorktreeIndex(P-1);else t.setSelectedWorktreeIndex(0);t.setSelectedWorktreePath(rt?.path??null),e.refetch(),setTimeout(h,1000)}catch($){let E=$.message;if(!m&&E.includes("dirty"))s("Worktree has changes. Press Enter to force remove."),r(!1),l(!0);else s(`Failed: ${E}`),r(!1),no.error(`Failed: ${E}`)}};rh(async(m)=>{if(!t.showRemove())return;if(t.showCommandPalette())return;let b=m.name;if(b==="escape"){h();return}if(c()&&(b==="return"||b==="enter")){l(!1),await u(!0);return}if((b==="return"||b==="enter")&&!n())await u(!1)});let d=()=>a(),g=()=>Math.max(50,Math.min(80,o().width-4)),x=()=>10;return React.createElement(Te,{width:g(),height:x(),borderColor:f.border.active,backgroundColor:f.bg.elevated,gap:1,title:" Remove Worktree ",backdrop:!0,footer:React.createElement("box",{flexDirection:"column"},React.createElement(O,{when:!n()&&!c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"[Enter] Confirm"),React.createElement("text",{fg:f.text.secondary},"[Esc] Cancel"))),React.createElement(O,{when:c()},React.createElement("box",{height:1,flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"[Enter] Force remove"),React.createElement("text",{fg:f.text.secondary},"[Esc] Cancel"))))},React.createElement(O,{when:!!d()},React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:f.text.secondary},"Branch")),React.createElement("text",{fg:f.text.accent},d()?.branch??"(detached)")),React.createElement("box",{height:1,flexDirection:"row"},React.createElement("box",{width:10,height:1},React.createElement("text",{fg:f.text.secondary},"Path")),React.createElement("text",{fg:f.text.primary},d()?.path)),React.createElement(O,{when:c()},React.createElement("text",{fg:f.text.warning},i())),React.createElement(O,{when:n()},React.createElement("text",{fg:i().startsWith("Failed")?f.text.error:f.text.success},i()))),React.createElement(O,{when:!d()},React.createElement("text",{fg:f.text.secondary},"No worktree selected.")))}var As=H(()=>{Et();ae();xe();st();St();$e();dr();jt();Ko()});import{useKeyboard as sh}from"@opentui/solid";function js(t){let e=Rt(),o=Ot(),n=xo(),[r,i]=N("confirming"),[s,c]=N(""),[l,a]=N(0),h=()=>{let x=o.worktrees()??[],m=e.selectedWorktrees(),b=[];for(let $ of m){let E=x.find((R)=>R.path===$);if(E&&!E.isMain)b.push({branch:E.branch??"(detached)",path:E.path,repoPath:E.repoPath})}return b},u=()=>{e.setShowBulkActions(!1),i("confirming"),c(""),a(0)},d=async()=>{let x=h();if(x.length===0){u();return}i("executing"),a(0);let m=[];for(let b=0;b<x.length;b++){let $=x[b];c(`Removing ${$.branch} (${b+1}/${x.length})...`),a(b);try{let E=Q(),R=Lt(E,$.repoPath);if(R.postRemove.length>0)await Wt(R.postRemove,{cwd:$.path,env:{OMW_BRANCH:$.branch,OMW_WORKTREE_PATH:$.path,OMW_REPO_PATH:$.repoPath}}).catch(()=>{});await M.remove($.path,{force:!1},$.repoPath)}catch(E){m.push(`${$.branch}: ${E.message}`)}}if(Mt(),e.clearSelection(),e.setSelectedWorktreeIndex(0),e.setSelectedWorktreePath(null),o.refetch(),m.length>0)i("error"),c(`Failed: ${m.join("; ")}`),n.addToast({message:`Failed to remove ${m.length} worktree(s)`,type:"error"}),setTimeout(u,3000);else i("done"),c(`Removed ${x.length} worktree(s) successfully!`),n.addToast({message:`Removed ${x.length} worktrees`,type:"success"}),setTimeout(u,1500)};sh(async(x)=>{if(!e.showBulkActions())return;if(e.showCommandPalette())return;let m=x.name;if(r()==="executing")return;if(m==="escape"){u();return}if((m==="return"||m==="enter")&&r()==="confirming")await d()});let g=()=>h().length;return React.createElement("box",{x:0,y:0,width:t.w,height:t.h,backgroundColor:f.bg.base},React.createElement("box",{x:2,y:1,width:t.w-3,height:t.h-2,flexDirection:"column",backgroundColor:f.bg.base},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error},"Bulk Delete Worktrees")),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.border.subtle},"\u2500".repeat(Math.max(t.w-5,10)))),React.createElement("box",{height:1}),React.createElement(O,{when:r()==="confirming"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.warning},`Delete ${g()} worktree(s)?`)),React.createElement("box",{height:1}),React.createElement($t,{each:h().slice(0,Math.max(t.h-10,5))},(x)=>React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.accent},`\u2022 ${x.branch}`))),React.createElement(O,{when:g()>Math.max(t.h-10,5)},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.secondary},`... and ${g()-Math.max(t.h-10,5)} more`))),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},"Enter:delete all Esc:cancel"))),React.createElement(O,{when:r()==="executing"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.warning},s())),React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.secondary},`Progress: ${l()+1}/${g()}`))),React.createElement(O,{when:r()==="done"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.success},s()))),React.createElement(O,{when:r()==="error"},React.createElement("box",{height:1},React.createElement("text",{x:0,y:0,fg:f.text.error},s())))))}var _s=H(()=>{Et();ae();No();xe();st();St();$e();jt()});import{useKeyboard as ch,useTerminalDimensions as ah}from"@opentui/solid";import{spawnSync as lh}from"child_process";function Ts(){let t=Rt(),e=ah(),o=kt(),n=()=>{try{return Q()}catch{return null}},[r,i]=N(n()),[s,c]=N("");ch((h)=>{if(t.activeTab()!=="config")return;if(t.showCommandPalette())return;let u=h.name;if(u==="e"){let d=process.env.EDITOR??process.env.VISUAL??"vi";ue(),lh(d,[o],{stdio:"inherit"}),i(n()),c("Config reloaded"),setTimeout(()=>c(""),2000)}if(u==="r")i(n()),c("Reloaded"),setTimeout(()=>c(""),2000);if(u==="i")ue(),i(n()),c("Config initialized"),setTimeout(()=>c(""),2000)});let l=()=>e().width,a=()=>e().height;return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:f.bg.base,flexDirection:"column"},React.createElement("box",{width:"100%",height:"100%",backgroundColor:f.bg.surface,flexDirection:"column",paddingX:2,paddingY:1},React.createElement("box",{height:1},React.createElement("text",{fg:f.text.accent},React.createElement("b",null,"Configuration"))),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:f.text.secondary},"Path:"),React.createElement("text",{fg:f.text.primary},o)),React.createElement(O,{when:!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.warning},"No config file found."),React.createElement("box",{flexDirection:"row",gap:1},React.createElement("text",{fg:f.text.secondary},"Press"),React.createElement("text",{fg:f.text.accent},"i"),React.createElement("text",{fg:f.text.secondary},"to initialize with defaults.")))),React.createElement(O,{when:!!r()},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.accent},"Defaults"),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"worktreeDir")),React.createElement("text",{fg:f.text.primary},r()?.defaults?.worktreeDir??"../{repo}-{branch}")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"copyFiles")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.copyFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"linkFiles")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.linkFiles??[]).join(", "),"]")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:14},React.createElement("text",{fg:f.text.secondary},"postCreate")),React.createElement("text",{fg:f.text.primary},"[",(r()?.defaults?.postCreate??[]).join(", "),"]"))),React.createElement("box",null,React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(l()-34,10)))),React.createElement(O,{when:(r()?.repos?.length??0)>0},React.createElement("box",{flexDirection:"column",gap:1},React.createElement("text",{fg:f.text.accent},"Repos (",r()?.repos?.length,")"),React.createElement($t,{each:r()?.repos?.slice(0,4)},(h)=>React.createElement("box",{flexDirection:"column",gap:0},React.createElement("text",{fg:f.text.primary},h.path.split("/").pop()??h.path),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:f.text.secondary},"copyFiles")),React.createElement("text",{fg:f.text.primary},(h.copyFiles??[]).length>0?(h.copyFiles??[]).join(", "):"\u2014")),React.createElement("box",{flexDirection:"row"},React.createElement("box",{width:11},React.createElement("text",{fg:f.text.secondary},"postCreate")),React.createElement("text",{fg:f.text.primary},(h.postCreate??[]).length>0?(h.postCreate??[]).join(", "):"\u2014")))))),React.createElement(O,{when:(r()?.repos?.length??0)===0},React.createElement("text",{fg:f.text.secondary},"No per-repo configs defined."))),React.createElement(O,{when:!!s()},React.createElement("text",{fg:f.text.success},s()))),React.createElement("box",{width:"100%",height:1,backgroundColor:f.bg.base,flexDirection:"row",gap:2},React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"e"),React.createElement("text",{fg:f.text.primary},":edit")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"r"),React.createElement("text",{fg:f.text.primary},":reload")),React.createElement("box",{flexDirection:"row"},React.createElement("text",{fg:f.text.secondary},"i"),React.createElement("text",{fg:f.text.primary},":init"))))}var Gs=H(()=>{Et();ae();St();jt()});import{existsSync as Ro,readdirSync as fh,rmSync as hh}from"fs";import{basename as Er,dirname as Rr,join as uh,resolve as Eo}from"path";function ph(t){let e=Bun.env.HOME??"~";return t.replace(/^~(?=\/|$)/,e)}function vs(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ks(t){if(!Ro(kt()))return[];let e=t.find((c)=>c.isMain);if(!e)return[];let o=Q(),n=Eo(e.path),r=Er(n);return[o.repos?.find((c)=>Eo(c.path)===n)?.worktreeDir??o.defaults?.worktreeDir].filter((c)=>typeof c==="string").map((c)=>ph(c)).filter((c)=>!Rr(c).includes("{")&&Er(c).includes("{")).map((c)=>{let l=Er(c),a=`^${vs(l).replace(/\\\{repo\\\}/g,vs(r)).replace(/\\\{branch\\\}/g,".+")}$`,h=new RegExp(a);return{path:Eo(Rr(c)),matches:(u)=>h.test(u)}})}function Ns(t){let e=new Set;for(let o of t)if(!o.isMain)e.add(Eo(Rr(o.path)));return[...e]}function Hs(t,e,o,n){if(!Ro(t))return;let r=fh(t,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;if(n&&!n(i.name))continue;let s=Eo(uh(t,i.name));if(!e.has(s))o.add(s)}}function Js(t){let e=new Set(t.map((r)=>Eo(r.path))),o=new Set,n=new Set;for(let r of ks(t))n.add(r.path),Hs(r.path,e,o,r.matches);for(let r of Ns(t)){if(n.has(r))continue;Hs(r,e,o)}return[...o]}function dh(t){return ks(t).some((e)=>Ro(e.path))||Ns(t).some((e)=>Ro(e))}async function mh(){let t=Bun.spawn(["git","--version"],{stdout:"pipe",stderr:"pipe",env:{...Bun.env,LC_ALL:"C",LANG:"C"}}),[e,o]=await Promise.all([new Response(t.stdout).text(),t.exited]);if(o!==0)return null;return e.trim().match(/git version (\d+\.\d+(?:\.\d+)?)/)?.[1]??null}async function xh(){try{return await M.checkVersion(),{name:"Git version",status:"pass",message:`${await mh()??"unknown"} (>= 2.17 required)`}}catch(e){if(e instanceof Go)return{name:"Git version",status:"fail",message:e.message};return{name:"Git version",status:"fail",message:`Check failed: ${e.message}`}}}async function gh(){try{let o=(Q().repos??[]).map((n)=>n.path).filter((n)=>!Ro(n));if(o.length>0)return{name:"Configuration",status:"warn",message:"missing repository paths",detail:o};return{name:"Configuration",status:"pass",message:"valid"}}catch(e){return{name:"Configuration",status:"fail",message:`Check failed: ${e.message}`}}}function wh(t){let o=t.map((n)=>n.path).filter((n)=>!Ro(n));if(o.length>0)return{name:"Stale worktrees",status:"warn",message:"missing worktree paths",detail:o};return{name:"Stale worktrees",status:"pass",message:"none"}}function bh(t){try{let o=Js(t);if(o.length===0)return{name:"Orphaned directories",status:"pass",message:dh(t)?"none":"no worktree directory"};return{name:"Orphaned directories",status:"warn",message:"orphaned worktree directories found",detail:o}}catch(o){return{name:"Orphaned directories",status:"fail",message:`Check failed: ${o.message}`}}}function Ch(t){let o=t.filter((r)=>r.isLocked);if(o.length===0)return{name:"Worktree locks",status:"pass",message:"all clear"};return{name:"Worktree locks",status:"warn",message:"locked worktrees present",detail:o.map((r)=>{let i=r.branch??"detached";if(!r.lockReason)return`${i} - ${r.path} (potential stale lock: no reason)`;return`${i} - ${r.path} (reason: ${r.lockReason})`})}}function Sh(t){let o=t.filter((n)=>n.isDirty&&!n.isMain);if(o.length===0)return{name:"Dirty worktrees",status:"pass",message:"none"};return{name:"Dirty worktrees",status:"warn",message:"dirty non-main worktrees found",detail:o.map((n)=>`${n.branch??"detached"} - ${n.path}`)}}async function Mo(t){let e=await M.list(t).catch(()=>[]),o=[await xh(),await gh(),wh(e),bh(e),Ch(e),Sh(e)];return{checks:o,healthy:o.every((n)=>n.status==="pass")}}async function $h(t){try{return await M.prune(t),{action:"Prune stale worktrees",success:!0}}catch(e){return{action:"Prune stale worktrees",success:!1,detail:e.message}}}async function Ph(t){let e=[];try{let o=Js(await M.list(t).catch(()=>[]));for(let n of o)try{hh(n,{recursive:!0,force:!0}),e.push({action:"Remove orphaned directory",success:!0,detail:n})}catch(r){e.push({action:"Remove orphaned directory",success:!1,detail:`${n}: ${r.message}`})}}catch(o){e.push({action:"Remove orphaned directories",success:!1,detail:o.message})}return e}async function yh(t){let e=[];try{let n=(await M.list(t)).filter((r)=>r.isLocked&&!r.lockReason);for(let r of n)try{await M.unlock(r.path,t),e.push({action:"Unlock stale lock",success:!0,detail:`${r.branch??"detached"} - ${r.path}`})}catch(i){e.push({action:"Unlock stale lock",success:!1,detail:`${r.path}: ${i.message}`})}}catch(o){e.push({action:"Fix stale locks",success:!1,detail:o.message})}return e}async function Fn(t){let e=[];return e.push(await $h(t)),e.push(...await Ph(t)),e.push(...await yh(t)),e}var Mr=H(()=>{St();st();Qt()});import{useKeyboard as Eh,useTerminalDimensions as Rh}from"@opentui/solid";function zs(){let t=Rt(),e=Rh(),[o,n]=N(null),[r,i]=N(!0),[s,c]=N(""),[l,a]=N(!1),[h,u]=N([]),d=async()=>{i(!0),c(""),u([]);try{let I=await Mo();n(I)}catch(I){c(I.message)}i(!1)},g=async()=>{if(o()?.healthy)return;a(!0);try{let I=await Fn();u(I);let Y=await Mo();n(Y)}catch(I){c(I.message)}a(!1)};d(),Eh((I)=>{if(t.activeTab()!=="doctor")return;if(t.showCommandPalette())return;let Y=I.name;if(Y==="r")d();if(Y==="f"&&!r()&&!l()&&!o()?.healthy)g()});let x=()=>e().width,m=()=>e().height,b=()=>Math.max(50,Math.min(80,x()-4)),$=()=>{let I=rt()+at()+8+(at()>0?2:0);return Math.max(12,Math.min(I,m()-4))},E=()=>Math.max(b()-4,10),R=(I)=>{if(I==="pass")return"\u2713";if(I==="warn")return"\u26A0";return"\u2717"},P=(I)=>{if(I==="pass")return f.text.success;if(I==="warn")return f.text.warning;return f.text.error},rt=()=>o()?.checks.length??0,at=()=>h().length;return React.createElement(Te,{width:b(),height:$(),borderColor:o()?.healthy?f.text.success:o()?f.text.warning:f.border.default,backgroundColor:f.bg.surface,title:" Doctor ",footer:React.createElement(Pw,null,React.createElement("box",{height:1,width:E()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(E(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"r:recheck"),React.createElement(O,{when:!o()?.healthy},React.createElement("text",{fg:f.text.secondary},"f:fix")),React.createElement("text",{fg:f.text.secondary},"Esc:back")))},React.createElement(O,{when:r()},React.createElement(go,{label:"Running checks..."})),React.createElement(O,{when:l()},React.createElement("text",{fg:f.text.accent},"Running auto-fix...")),React.createElement(O,{when:!r()&&!l()&&!!s()},React.createElement("text",{fg:f.text.error},"Error: ",s())),React.createElement(O,{when:!r()&&!l()&&!s()&&!!o()},React.createElement("text",{fg:f.text.accent},"Health Checks"),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(E())),React.createElement($t,{each:o().checks},(I)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:P(I.status)},R(I.status)),React.createElement("text",{x:2,y:0,fg:f.text.primary},I.name,":"),React.createElement("text",{x:I.name.length+4,y:0,fg:f.text.secondary},I.message))}),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(E())),React.createElement("text",{fg:o().healthy?f.text.success:f.text.warning},o().healthy?"\u2713 All checks passed":`${o().checks.filter((I)=>I.status==="fail").length} error(s), ${o().checks.filter((I)=>I.status==="warn").length} warning(s) found`),React.createElement(O,{when:at()>0},React.createElement("text",{fg:f.text.accent},"Fix Results"),React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(E())),React.createElement($t,{each:h()},(I)=>{return React.createElement("box",{width:"100%",height:1,flexDirection:"row"},React.createElement("text",{fg:I.success?f.text.success:f.text.error},I.success?"\u2713":"\u2717"),React.createElement("text",{x:2,y:0,fg:f.text.primary},I.action),React.createElement(O,{when:!!I.detail},React.createElement("text",{x:I.action.length+3,y:0,fg:f.text.secondary},"(",I.detail,")")))}))))}var Us=H(()=>{Et();ae();Mr();jt();Ko();Sn()});var Xs={};xt(Xs,{writePin:()=>Wr,removePin:()=>Dr,readPin:()=>qo,listPinnedWorktrees:()=>Fr,isPinned:()=>Ge});import{readFileSync as Vs,writeFileSync as Mh,unlinkSync as Oh,mkdirSync as Wh,existsSync as Or}from"fs";import{join as Dh,dirname as Ks}from"path";function Xo(t){return fe(t,"omw-pin")}function Fh(t){let e=Xo(t),o=Ks(e),n=Dh(o,"HEAD"),r=Vs(n,"utf-8").trim(),i=r.match(/^ref:\s+refs\/heads\/(.+)$/);return i?i[1]:r}function Wr(t,e){let o=Xo(t),n={branch:Fh(t),pinnedAt:new Date().toISOString(),...e?{reason:e}:{}};Wh(Ks(o),{recursive:!0}),Mh(o,JSON.stringify(n),{encoding:"utf-8",mode:384})}function qo(t){let e=Xo(t);if(!Or(e))return null;return JSON.parse(Vs(e,"utf-8"))}function Dr(t){let e=Xo(t);if(!Or(e))return;Oh(e)}function Ge(t){return Or(Xo(t))}function Fr(t){return t.filter((e)=>Ge(e.path))}var Oo=H(()=>{Fe()});import{useKeyboard as Bh}from"@opentui/solid";function qs(){let t=Rt(),e=Ot(),o=()=>e.worktrees()??[],n=()=>t.selectedWorktreeIndex(),r=(h)=>{let u=Math.max(0,Math.min(h,Math.max(o().length-1,0))),d=o()[u];t.setSelectedWorktreeIndex(u),t.setSelectedWorktreePath(d?.path??null)},i=se(()=>{let h=o(),u=[],d=new Map;for(let m of h){let b=d.get(m.repoName);if(b)b.push(m);else d.set(m.repoName,[m])}let g=0,x=!0;for(let[m,b]of d){if(!x)u.push({type:"separator"});x=!1,u.push({type:"header",repoName:m});for(let $ of b)u.push({type:"worktree",wt:$,flatIdx:g}),g++}return u}),s=()=>t.selectedWorktrees().size;Bh((h)=>{if(t.activeTab()!=="list")return;if(t.showCommandPalette())return;if(t.showRemove())return;if(t.showBulkActions())return;if(t.inputFocused())return;let u=h.name,d=o();if(u==="j"||u==="down")r(Math.min(n()+1,d.length-1));if(u==="k"||u==="up")r(Math.max(n()-1,0));if(u==="space"){let g=n(),x=d[g];if(x&&!x.isMain)t.toggleWorktreeSelection(x.path)}if(h.ctrl&&u==="a")t.selectAllNonMain(d.filter((g)=>!g.isMain).map((g)=>g.path))});let c=(h)=>{if(h.isLocked)return"\uD83D\uDD12";if(h.isDirty)return"\u25CF";return"\u2713"},l=(h)=>{if(h.isLocked)return f.text.warning;if(h.isDirty)return f.text.error;return f.text.success},a=(h,u)=>{let d=h.branch??"(detached)",g=Math.max(8,Zo-(u?9:7));return d.length>g?d.slice(0,g-1)+"\u2026":d};return React.createElement("box",{x:0,y:0,width:"100%",height:"100%",backgroundColor:f.bg.surface,flexDirection:"column",paddingX:1,paddingY:1,gap:0},React.createElement(O,{when:e.loading()},React.createElement("text",{fg:f.text.secondary},"Loading...")),React.createElement(O,{when:!e.loading()},React.createElement($t,{each:i()},(h)=>{if(h.type==="header")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.text.accent},React.createElement("b",null,h.repoName)));if(h.type==="separator")return React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Zo)));let u=h.wt,d=()=>h.flatIdx===n(),g=()=>t.selectedWorktrees().has(u.path);return React.createElement("box",{width:"100%",height:1,backgroundColor:d()?f.select.focusedBg:g()?f.bg.elevated:f.bg.surface,paddingX:1,onMouseDown:()=>r(h.flatIdx)},React.createElement("text",{x:0,y:0,fg:l(u)},c(u)),React.createElement("text",{x:2,y:0,fg:d()?f.tab.active:f.text.primary},a(u,!1)),React.createElement(O,{when:g()},React.createElement("text",{x:Zo-1,y:0,fg:f.text.accent},"\u2713")),React.createElement(O,{when:!!Kt(u.path)},React.createElement("text",{x:Zo-(g()?3:1),y:0,fg:f.text.accent},"S")),React.createElement(O,{when:Ge(u.path)},React.createElement("text",{x:Zo-(g()?5:3)+(Kt(u.path)?0:2),y:0,fg:f.text.warning},"P")))}),React.createElement(O,{when:s()>0},React.createElement("box",{width:"100%",height:1},React.createElement("text",{fg:f.text.accent},`Selected: ${s()}`)))))}var Zo=24;var Zs=H(()=>{Et();ae();xe();jt();Oo();Le()});import{useKeyboard as Lh,usePaste as Ih,useTerminalDimensions as Ah}from"@opentui/solid";import{decodePasteBytes as jh}from"@opentui/core";function Qs(){let t=Rt(),e=Ot(),o=Ah(),[n,r]=N(""),[i,s]=N(0);un(()=>{t.setInputFocused(!0)}),ce(()=>{t.setInputFocused(!1)});let c=()=>{let $=e.worktrees()??[],E=t.selectedWorktreePath();if(E){let R=$.find((P)=>P.path===E);if(R)return R}return $[t.selectedWorktreeIndex()]},l=()=>{let $=process.env.VISUAL||process.env.EDITOR;if($)return $;let E=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let R of E)try{if(Bun.spawnSync(["which",R],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return R}catch{}return null},a=se(()=>[{id:"add",label:"Add Worktree",description:"Create a new git worktree",action:()=>{t.setActiveTab("add"),t.setShowCommandPalette(!1)}},{id:"delete",label:"Delete Worktree",description:"Remove the selected worktree",action:()=>{let $=c();if(!$||$.isMain)return;t.setShowRemove(!0),t.setShowCommandPalette(!1)}},{id:"open-editor",label:"Open in Editor",description:"Open selected worktree in IDE",action:()=>{let $=c();if(!$)return;let E=l();if(!E)return;t.setShowCommandPalette(!1),Bun.spawn([E,$.path],{stdout:"inherit",stderr:"inherit"})}},{id:"refresh",label:"Refresh",description:"Reload worktree list",action:()=>{e.refetch(),t.setShowCommandPalette(!1)}},{id:"config",label:"Open Config",description:"View configuration",action:()=>{t.setActiveTab("config"),t.setShowCommandPalette(!1)}},{id:"doctor",label:"Run Doctor",description:"Check worktree health",action:()=>{t.setActiveTab("doctor"),t.setShowCommandPalette(!1)}},...xn.map(($)=>({id:`theme:${$}`,label:`Theme: ${fs[$]}`,description:"Switch color theme",action:()=>{gn($);try{let E=kt(),R={...Q()};R.theme=$,Uo(E,JSON.stringify(R,null,2))}catch{}t.setShowCommandPalette(!1)}})),{id:"quit",label:"Quit",description:"Exit oh-my-worktree",action:()=>process.exit(0)}]),h=se(()=>{let $=n().toLowerCase();if(!$)return a();return a().filter((E)=>E.label.toLowerCase().includes($)||E.description.toLowerCase().includes($))});Lh(($)=>{if(!t.showCommandPalette())return;let E=$.name;if(E==="escape"){t.setInputFocused(!1),t.setShowCommandPalette(!1),r(""),s(0);return}if(E==="return"||E==="enter"){let R=h()[i()];if(R)R.action();r(""),s(0);return}if(E==="down"||E==="j"){s((R)=>Math.min(R+1,h().length-1));return}if(E==="up"||E==="k"){s((R)=>Math.max(R-1,0));return}}),Ih(($)=>{if(!t.inputFocused())return;let E=jh($.bytes).replace(/\r?\n/g,"");if(!E)return;r((R)=>R+E),s(0)});let u=($)=>{r($),s(0)},d=()=>Math.max(50,Math.min(80,o().width-4)),g=()=>Math.max(10,Math.min(h().length+8,o().height-4)),x=()=>d()-4,m=()=>Math.max(x()-2,1),b=()=>g()-8;return React.createElement(Te,{width:d(),height:g(),borderColor:f.border.active,backgroundColor:f.bg.surface,title:" Command Palette ",footer:React.createElement(Jw,null,React.createElement("box",{height:1,width:x()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(x(),1)))),React.createElement("box",{flexDirection:"row",gap:2},React.createElement("text",{fg:f.text.secondary},"\u2191\u2193:navigate"),React.createElement("text",{fg:f.text.secondary},"Enter:run"),React.createElement("text",{fg:f.text.secondary},"Esc:close")))},React.createElement("box",{height:1,width:x(),backgroundColor:f.bg.elevated,flexDirection:"row"},React.createElement("text",{fg:f.text.accent},"> "),React.createElement("input",{value:n(),onInput:u,placeholder:"Search commands...",focused:!0,width:m(),backgroundColor:f.bg.elevated,textColor:f.text.primary,placeholderColor:f.text.secondary,cursorColor:f.text.accent,focusedBackgroundColor:f.bg.elevated})),React.createElement("box",{height:1,width:x()},React.createElement("text",{fg:f.border.subtle},"\u2500".repeat(Math.max(x(),1)))),React.createElement("box",{width:x(),height:b(),backgroundColor:f.bg.surface,flexDirection:"column"},React.createElement($t,{each:h().slice(0,b())},($,E)=>{let R=()=>E()===i();return React.createElement("box",{height:1,width:x(),backgroundColor:R()?f.select.focusedBg:f.bg.surface,onMouseDown:()=>{s(E()),$.action()}},React.createElement("text",{x:2,y:0,fg:R()?f.tab.active:f.text.primary},$.label),React.createElement("text",{x:Math.max(25,$.label.length+4),y:0,fg:f.text.secondary},$.description))}),React.createElement(O,{when:h().length===0},React.createElement("box",{height:1},React.createElement("text",{x:2,y:0,fg:f.text.secondary},"No commands found")))))}var Ys=H(()=>{Et();ae();xe();jt();Ko();St()});import{useTerminalDimensions as _h}from"@opentui/solid";function Th(t){if(t==="success")return"\u2713";if(t==="warning")return"\u26A0";if(t==="error")return"\u2717";return"\u2139"}function Gh(t){if(t==="success")return f.text.success;if(t==="warning")return f.text.warning;if(t==="error")return f.text.error;return f.text.primary}function tc(){let t=_h(),e=()=>Math.min(60,Math.max(24,t().width-4));return React.createElement("box",{x:(()=>Math.max(0,t().width-e()-1))(),y:1,width:e(),height:5,flexDirection:"column"},React.createElement($t,{each:xo().toasts()},(n,r)=>React.createElement("box",{x:0,y:r(),width:e(),height:1,backgroundColor:f.bg.elevated},React.createElement("text",{x:1,y:0,fg:Gh(n.type)},`${Th(n.type)} ${n.message}`))))}var ec=H(()=>{Et();No();jt()});var rc={};xt(rc,{launchTUI:()=>Uh});import{render as vh,useKeyboard as Hh,useTerminalDimensions as kh,useRenderer as Nh}from"@opentui/solid";import{resolve as oc}from"path";function Jh(){let t=["code","cursor","vim","nvim","zed","subl","idea","webstorm"];for(let e of t)try{if(Bun.spawnSync(["which",e],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return e}catch{}return null}function zh(t){let e=Rt(),o=Ot(),n=Nh(),[r,i]=N(!1),s=kh(),c=()=>{let m=o.worktrees()??[],b=e.selectedWorktreePath();if(b){let $=m.find((E)=>E.path===b);if($)return $}return m[e.selectedWorktreeIndex()]};ie(()=>{let m=o.worktrees()??[],b=m.map((P)=>P.path);if(e.pruneSelectedWorktrees(b),m.length===0){if(e.selectedWorktreeIndex()!==0)e.setSelectedWorktreeIndex(0);if(e.selectedWorktreePath()!==null)e.setSelectedWorktreePath(null);return}let $=e.selectedWorktreePath();if($){let P=m.findIndex((rt)=>rt.path===$);if(P>=0){if(P!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(P);return}}let E=Math.min(e.selectedWorktreeIndex(),m.length-1),R=m[E]?.path??null;if(E!==e.selectedWorktreeIndex())e.setSelectedWorktreeIndex(E);if(R!==e.selectedWorktreePath())e.setSelectedWorktreePath(R)}),Hh((m)=>{let b=m.name;if(b==="escape"){if(e.showBulkActions()){e.setShowBulkActions(!1);return}if(e.showDetailView()){e.setShowDetailView(!1);return}if(e.showRemove()){e.setShowRemove(!1);return}if(r()){i(!1);return}if(e.activeTab()!=="list"){e.setActiveTab("list");return}}if(m.ctrl&&b==="p"){e.setShowCommandPalette(!0);return}if(e.inputFocused())return;if(e.showCommandPalette())return;if(e.showBulkActions())return;if(e.showRemove())return;if(e.activeTab()==="add")return;if(e.activeTab()==="list"){if(e.showDetailView())return;if(b==="a"){e.setActiveTab("add");return}if(b==="r"){o.refetch();return}if(b==="d"){let $=c();if($&&!$.isMain)e.setShowRemove(!0);return}if(b==="o"){let $=c();if($){let E=process.env.VISUAL||process.env.EDITOR||Jh();if(E)Bun.spawn([E,$.path],{stdout:"inherit",stderr:"inherit"})}return}}if(b==="h"){e.setActiveTab("doctor");return}if(b==="q"||b==="Q")n.destroy();if(b==="?")i(($)=>!$)});let l=()=>s().width,a=()=>s().height,h=()=>t.repoPath.split("/").pop()??"",u=()=>{let m=o.repoNames();if(m.length<=1)return h();return`${m.length} repos`},d=()=>{let m=o.worktrees()??[];return`${h()} \xB7 ${m.length} worktrees`},g=()=>{return` Worktrees (${(o.worktrees()??[]).length}) `},x=()=>l()-nc-1;return React.createElement("box",{width:l(),height:a(),backgroundColor:f.bg.base,flexDirection:"column"},React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:1,y:0,fg:f.text.accent},"\uD83C\uDF33 oh-my-worktree"),React.createElement("text",{x:l()-u().length-2,y:0,fg:f.text.secondary},u())),React.createElement("box",{flexGrow:1,flexDirection:"row"},React.createElement("box",{width:nc,flexShrink:0,backgroundColor:f.bg.surface,flexDirection:"column"},React.createElement("box",{height:1,paddingX:1},React.createElement("text",{fg:f.text.accent},React.createElement("b",null,g()))),React.createElement(qs,null)),React.createElement("box",{width:1}),React.createElement("box",{flexGrow:1,backgroundColor:f.bg.base},React.createElement(O,{when:e.activeTab()!=="config"&&!e.showRemove()&&!e.showBulkActions()},React.createElement(bs,null)),React.createElement(O,{when:e.activeTab()==="list"&&e.showBulkActions()},React.createElement(js,{w:x(),h:a()-3})),React.createElement(O,{when:e.activeTab()==="config"},React.createElement(Ts,null)))),React.createElement(tc,null),React.createElement("toaster",{position:"bottom-right"}),React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:0,y:0,fg:f.border.subtle},"\u2500".repeat(l()))),React.createElement("box",{height:1,backgroundColor:f.bg.overlay},React.createElement("text",{x:1,y:0,fg:f.text.secondary},"d:delete a:add o:open r:refresh ^P:cmd h:health q:quit")),React.createElement(O,{when:r()&&!e.showCommandPalette()},React.createElement("box",{x:Math.max(0,Math.floor((l()-Math.max(40,Math.min(60,l()-4)))/2)),y:Math.max(0,Math.floor((a()-14)/2)),width:Math.max(40,Math.min(60,l()-4)),height:14,border:!0,borderStyle:"rounded",borderColor:f.border.active,backgroundColor:f.bg.elevated,title:" Keyboard Shortcuts ",titleAlignment:"left",flexDirection:"column",paddingX:1,paddingY:1,position:"absolute"},React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"q"),React.createElement("text",{x:8,fg:f.text.primary},"Quit")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"j/k"),React.createElement("text",{x:8,fg:f.text.primary},"Navigate list")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"a"),React.createElement("text",{x:8,fg:f.text.primary},"Add worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"d"),React.createElement("text",{x:8,fg:f.text.primary},"Delete worktree")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"r"),React.createElement("text",{x:8,fg:f.text.primary},"Refresh list")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"Ctrl+P"),React.createElement("text",{x:8,fg:f.text.primary},"Command palette")),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.secondary},"?"),React.createElement("text",{x:8,fg:f.text.primary},"Toggle help")),React.createElement("box",{height:1}),React.createElement("box",{height:1},React.createElement("text",{x:1,fg:f.text.accent},"Press ? to close")))),React.createElement(O,{when:e.activeTab()==="add"},React.createElement(Bs,null)),React.createElement(O,{when:e.activeTab()==="doctor"},React.createElement(zs,null)),React.createElement(O,{when:e.showRemove()},React.createElement(Is,null)),React.createElement(O,{when:e.showCommandPalette()},React.createElement(Qs,null)))}async function Uh(){if(process.stdout.isTTY)process.stdout.write("\x1B]0;Oh My Worktree\x07");let t=await M.getMainRepoPath().catch(()=>process.cwd()),e=[t];try{let o={...Q()},n=Ae(o),r=new Set([oc(t)]);for(let i of n){let s=oc(i);if(!r.has(s))r.add(s),e.push(i)}if(o.theme&&xn.includes(o.theme))gn(o.theme)}catch{}await vh(()=>React.createElement(ss,{repoPath:t,repoPaths:e},React.createElement(ls,{repoPaths:e},React.createElement(ms,null,React.createElement(zh,{repoPath:t})))),{exitOnCtrlC:!0,useMouse:!0})}var nc=28;var ic=H(()=>{Et();ae();xe();st();Cs();Ls();As();_s();Gs();Us();Zs();jt();Ys();No();ec();St()});import*as sc from"readline";async function ve(t){let e=sc.createInterface({input:process.stdin,output:process.stdout});return new Promise((o)=>{e.question(t,(n)=>{e.close(),o(n.toLowerCase()==="y"||n.toLowerCase()==="yes")})})}async function ct(){return M.getMainRepoPath().catch(()=>process.cwd())}function Xt(t,e){let o=t.find((n)=>n.branch===e||n.path===e||n.path.endsWith("/"+e));if(!o)console.error(`Error: no worktree found for '${e}'`),process.exit(1);return o}function wt(t){if(t instanceof Ht)console.error(`Git error: ${t.message}`);else console.error(`Error: ${t.message}`);process.exit(1)}var Dt=H(()=>{st();Qt()});import{mkdirSync as Vh,writeFileSync as Kh}from"fs";import{dirname as Xh}from"path";function qh(t){return fe(t,"omw-pr")}function cc(t,e){let o=qh(t);Vh(Xh(o),{recursive:!0}),Kh(o,JSON.stringify(e),{encoding:"utf-8",mode:384})}var ac=H(()=>{Fe()});import{appendFileSync as Zh,existsSync as Qh,mkdirSync as Yh,readFileSync as lc,rmSync as tu,statSync as eu,writeFileSync as ou}from"fs";import{dirname as nu}from"path";function Br(t){return fe(t,"omw-activity.log")}function qt(t,e){let o=Br(t);Yh(nu(o),{recursive:!0}),Zh(o,`${JSON.stringify(e)}
15
+ `,{encoding:"utf-8",mode:384});let n=eu(o,{throwIfNoEntry:!1});if(n&&n.size>iu){let r=lc(o,"utf-8").split(/\r?\n/).filter(Boolean);if(r.length>fc){let i=r.slice(-ru);ou(o,`${i.join(`
17
16
  `)}
18
- `,{encoding:"utf-8",mode:384})}}}function sc(t,e){let o=Wr(t),n=e?.limit??50;if(!Hh(o))return[];let i=rc(o,"utf-8").split(/\r?\n/).filter(Boolean),s=Math.max(0,i.length-n),c=[];for(let f=i.length-1;f>=s;f--)try{c.push(JSON.parse(i[f]))}catch{}return c}function cc(t){Jh(Wr(t),{force:!0})}var ic=1000,Uh=500,Vh;var Ge=N(()=>{We();Vh=80*ic});var ac={};xt(ac,{default:()=>Qh});import{basename as Kh,resolve as qh}from"path";import{existsSync as Xh}from"fs";var Zh,Qh;var fc=N(()=>{ct();Zt();$t();Dt();$e();En();Pn();xe();nc();Ge();$r();Fe();Zh={command:"add [branch] [path]",describe:"Create a new worktree for a branch",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).positional("path",{type:"string",describe:"Worktree directory path"}).option("create",{type:"boolean",alias:"c",describe:"Optional compatibility flag; missing branches are created automatically"}).option("base",{type:"string",alias:"b",describe:"Base branch/commit for new branch"}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("template",{type:"string",alias:"t",describe:"Use a named template from config"}).option("pr",{type:"number",describe:"Create worktree from a GitHub PR number (requires gh CLI)"}).option("session",{type:"boolean",alias:"s",describe:"Create a tmux session for this worktree"}).option("layout",{type:"string",describe:"Session layout name from config"}),handler:async(t)=>{let{branch:e,pr:o}=t,n=await at(),r=Kh(n);if(!e&&!o)console.error("Error: specify a branch or use --pr <number>."),process.exit(1);if(o)try{let x=Bun.spawn(["gh","pr","view",String(o),"--json","headRefName","--jq",".headRefName"],{cwd:n,stdout:"pipe",stderr:"pipe"}),[m,b,S]=await Promise.all([new Response(x.stdout).text(),new Response(x.stderr).text(),x.exited]);if(S!==0)console.error(`Error: failed to resolve PR #${o}: ${b.trim()}`),console.error("Make sure 'gh' CLI is installed and authenticated."),process.exit(1);if(e=m.trim(),!e)console.error(`Error: PR #${o} has no branch name`),process.exit(1);console.log(`PR #${o} \u2192 branch '${e}'`)}catch{console.error("Error: 'gh' CLI not found. Install it from https://cli.github.com"),process.exit(1)}if(!e)console.error("Error: could not determine branch name."),process.exit(1);let i=e.replace(/\//g,"-"),s=Y(),c=Lt(s,n),f=t.template;if(f){let x=Cn(s,f);if(!x){let m=Object.keys(s.templates??{});if(console.error(`Error: template '${f}' not found.`),m.length>0)console.error(`Available templates: ${m.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}if(c=$n(c,x),x.base&&!t.base)t.base=x.base;console.log(`Using template '${f}'`)}let a=t.path??c.worktreeDir,h=bn(a,{repo:r,branch:i}),u=qh(n,h);console.log(`Creating worktree for branch '${e}'...`),console.log(` Target: ${u}`);let g=(await M.list(n)).find((x)=>x.branch===e);if(g)console.error(`Error: branch '${e}' is already checked out in ${g.path}`),process.exit(1);if(Xh(u))console.error(`Error: directory already exists: ${u}`),process.exit(1);try{await M.add(e,u,{createBranch:Boolean(t.create),base:t.base},n),console.log(" \u2713 Worktree created");try{qt(n,{timestamp:new Date().toISOString(),event:"create",branch:e,path:u})}catch{}if(o)oc(u,{number:o,branch:e,createdAt:new Date().toISOString()}),console.log(` \u2713 PR #${o} metadata saved`)}catch(x){if(x instanceof Gt)console.error(`Error creating worktree: ${x.stderr||x.message}`);else console.error(`Error: ${x.message}`);process.exit(1)}if(c.autoUpstream)try{let x=await M.getDefaultRemote(n);if(await M.remoteBranchExists(e,x,n))await M.setUpstream(e,x,n),console.log(` \u2713 Upstream tracking set \u2192 ${x}/${e}`);else console.log(" \u2139 No remote branch found \u2014 upstream tracking skipped")}catch(x){console.warn(` \u26A0 Could not set upstream tracking: ${x.message}`)}try{if(c.copyFiles.length>0){console.log(` Copying files: ${c.copyFiles.join(", ")}`);let y=go(n,u,c.copyFiles);for(let R of y.warnings)console.log(` \u26A0 ${R}`);if(y.copied.length>0)console.log(` \u2713 Copied: ${y.copied.join(", ")}`)}if(c.linkFiles.length>0){console.log(` Linking files: ${c.linkFiles.join(", ")}`);let y=wo(n,u,c.linkFiles);for(let R of y.warnings)console.log(` \u26A0 ${R}`);if(y.linked.length>0)console.log(` \u2713 Linked: ${y.linked.join(", ")}`)}if(c.sharedDeps&&c.sharedDeps.paths&&c.sharedDeps.paths.length>0){let y=c.sharedDeps.strategy??"symlink";console.log(` Sharing dependencies (${y}): ${c.sharedDeps.paths.join(", ")}`);let R=Ps(n,u,c.sharedDeps);for(let it of R.warnings)console.log(` \u26A0 ${it}`);if(R.linked.length>0)console.log(` \u2713 Shared (${y}): ${R.linked.join(", ")}`);if(R.copied.length>0)console.log(` \u2713 Copied: ${R.copied.join(", ")}`)}let x={OMW_BRANCH:e,OMW_WORKTREE_PATH:u,OMW_REPO_PATH:n},m=t.focus,b=[];if(m&&m.length>0)b=m.flatMap((y)=>y.split(/[,\s]+/)).map((y)=>y.trim()).filter(Boolean);if(b.length>0){let{valid:y,invalid:R}=yn(u,b);if(R.length>0)console.log(` \u26A0 Focus paths not found (will be skipped): ${R.join(", ")}`);if(y.length>0)ho(u,y),console.log(` \u2713 Focus set: ${y.join(", ")}`);x.OMW_FOCUS_PATHS=y.join(",")}if(c.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(c.postCreate,{cwd:u,env:x,onOutput:(y)=>console.log(` ${y}`)}),console.log(" \u2713 Hooks completed");if(b.length>0&&c.monorepo?.hooks&&c.monorepo.hooks.length>0){let y=ro(c.monorepo.hooks,b);if(y.length>0)console.log(" Running monorepo hooks..."),await $o(y,"postCreate",{cwd:u,env:x,repo:r,branch:e,focusPaths:b,mainRepoPath:n,onOutput:(R)=>console.log(` ${R}`)}),console.log(" \u2713 Monorepo hooks completed")}let S=Ae(s);if(t.session||S.autoCreate)if(await po()){let R=t.layout??S.defaultLayout,it=Sn(s,R),st=await mn(e,u,{layout:it,prefix:S.prefix,attach:!1,layoutName:R});console.log(` \u2713 Session created: ${st}`)}else console.log(" \u26A0 tmux not found \u2014 session skipped");console.log(`
17
+ `,{encoding:"utf-8",mode:384})}}}function hc(t,e){let o=Br(t),n=e?.limit??50;if(!Qh(o))return[];let i=lc(o,"utf-8").split(/\r?\n/).filter(Boolean),s=Math.max(0,i.length-n),c=[];for(let l=i.length-1;l>=s;l--)try{c.push(JSON.parse(i[l]))}catch{}return c}function uc(t){tu(Br(t),{force:!0})}var fc=1000,ru=500,iu;var He=H(()=>{Fe();iu=80*fc});var pc={};xt(pc,{default:()=>fu});import{basename as su,resolve as cu}from"path";import{existsSync as au}from"fs";var lu,fu;var dc=H(()=>{st();Qt();St();Dt();$e();Dn();On();ge();ac();He();yr();Le();lu={command:"add [branch] [path]",describe:"Create a new worktree for a branch",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).positional("path",{type:"string",describe:"Worktree directory path"}).option("create",{type:"boolean",alias:"c",describe:"Optional compatibility flag; missing branches are created automatically"}).option("base",{type:"string",alias:"b",describe:"Base branch/commit for new branch"}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("template",{type:"string",alias:"t",describe:"Use a named template from config"}).option("pr",{type:"number",describe:"Create worktree from a GitHub PR number (requires gh CLI)"}).option("session",{type:"boolean",alias:"s",describe:"Create a tmux session for this worktree"}).option("layout",{type:"string",describe:"Session layout name from config"}),handler:async(t)=>{let{branch:e,pr:o}=t,n=await ct(),r=su(n);if(!e&&!o)console.error("Error: specify a branch or use --pr <number>."),process.exit(1);if(o)try{let x=Bun.spawn(["gh","pr","view",String(o),"--json","headRefName","--jq",".headRefName"],{cwd:n,stdout:"pipe",stderr:"pipe"}),[m,b,$]=await Promise.all([new Response(x.stdout).text(),new Response(x.stderr).text(),x.exited]);if($!==0)console.error(`Error: failed to resolve PR #${o}: ${b.trim()}`),console.error("Make sure 'gh' CLI is installed and authenticated."),process.exit(1);if(e=m.trim(),!e)console.error(`Error: PR #${o} has no branch name`),process.exit(1);console.log(`PR #${o} \u2192 branch '${e}'`)}catch{console.error("Error: 'gh' CLI not found. Install it from https://cli.github.com"),process.exit(1)}if(!e)console.error("Error: could not determine branch name."),process.exit(1);let i=e.replace(/\//g,"-"),s=Q(),c=Lt(s,n),l=t.template;if(l){let x=En(s,l);if(!x){let m=Object.keys(s.templates??{});if(console.error(`Error: template '${l}' not found.`),m.length>0)console.error(`Available templates: ${m.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}if(c=Rn(c,x),x.base&&!t.base)t.base=x.base;console.log(`Using template '${l}'`)}let a=t.path??c.worktreeDir,h=yn(a,{repo:r,branch:i}),u=cu(n,h);console.log(`Creating worktree for branch '${e}'...`),console.log(` Target: ${u}`);let g=(await M.list(n)).find((x)=>x.branch===e);if(g)console.error(`Error: branch '${e}' is already checked out in ${g.path}`),process.exit(1);if(au(u))console.error(`Error: directory already exists: ${u}`),process.exit(1);try{await M.add(e,u,{createBranch:Boolean(t.create),base:t.base},n),console.log(" \u2713 Worktree created");try{qt(n,{timestamp:new Date().toISOString(),event:"create",branch:e,path:u})}catch{}if(o)cc(u,{number:o,branch:e,createdAt:new Date().toISOString()}),console.log(` \u2713 PR #${o} metadata saved`)}catch(x){if(x instanceof Ht)console.error(`Error creating worktree: ${x.stderr||x.message}`);else console.error(`Error: ${x.message}`);process.exit(1)}if(c.autoUpstream)try{let x=await M.getDefaultRemote(n);if(await M.remoteBranchExists(e,x,n))await M.setUpstream(e,x,n),console.log(` \u2713 Upstream tracking set \u2192 ${x}/${e}`);else console.log(" \u2139 No remote branch found \u2014 upstream tracking skipped")}catch(x){console.warn(` \u26A0 Could not set upstream tracking: ${x.message}`)}try{if(c.copyFiles.length>0){console.log(` Copying files: ${c.copyFiles.join(", ")}`);let R=Co(n,u,c.copyFiles);for(let P of R.warnings)console.log(` \u26A0 ${P}`);if(R.copied.length>0)console.log(` \u2713 Copied: ${R.copied.join(", ")}`)}if(c.linkFiles.length>0){console.log(` Linking files: ${c.linkFiles.join(", ")}`);let R=So(n,u,c.linkFiles);for(let P of R.warnings)console.log(` \u26A0 ${P}`);if(R.linked.length>0)console.log(` \u2713 Linked: ${R.linked.join(", ")}`)}if(c.sharedDeps&&c.sharedDeps.paths&&c.sharedDeps.paths.length>0){let R=c.sharedDeps.strategy??"symlink";console.log(` Sharing dependencies (${R}): ${c.sharedDeps.paths.join(", ")}`);let P=Ds(n,u,c.sharedDeps);for(let rt of P.warnings)console.log(` \u26A0 ${rt}`);if(P.linked.length>0)console.log(` \u2713 Shared (${R}): ${P.linked.join(", ")}`);if(P.copied.length>0)console.log(` \u2713 Copied: ${P.copied.join(", ")}`)}let x={OMW_BRANCH:e,OMW_WORKTREE_PATH:u,OMW_REPO_PATH:n},m=t.focus,b=[];if(m&&m.length>0)b=m.flatMap((R)=>R.split(/[,\s]+/)).map((R)=>R.trim()).filter(Boolean);if(b.length>0){let{valid:R,invalid:P}=Wn(u,b);if(P.length>0)console.log(` \u26A0 Focus paths not found (will be skipped): ${P.join(", ")}`);if(R.length>0)uo(u,R),console.log(` \u2713 Focus set: ${R.join(", ")}`);x.OMW_FOCUS_PATHS=R.join(",")}if(c.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(c.postCreate,{cwd:u,env:x,onOutput:(R)=>console.log(` ${R}`)}),console.log(" \u2713 Hooks completed");if(b.length>0&&c.monorepo?.hooks&&c.monorepo.hooks.length>0){let R=io(c.monorepo.hooks,b);if(R.length>0)console.log(" Running monorepo hooks..."),await yo(R,"postCreate",{cwd:u,env:x,repo:r,branch:e,focusPaths:b,mainRepoPath:n,onOutput:(P)=>console.log(` ${P}`)}),console.log(" \u2713 Monorepo hooks completed")}let $=je(s);if(t.session||$.autoCreate)if(await mo()){let P=t.layout??$.defaultLayout,rt=Mn(s,P),at=await bn(e,u,{layout:rt,prefix:$.prefix,attach:!1,layoutName:P});console.log(` \u2713 Session created: ${at}`)}else console.log(" \u26A0 tmux not found \u2014 session skipped");console.log(`
19
18
  Worktree ready: ${u}`),process.exit(0)}catch(x){console.error(`
20
- Setup failed, rolling back...`);try{await M.remove(u,{force:!0},n),console.error("Rolled back worktree.")}catch(m){console.error(`Warning: rollback failed: ${m.message}`)}if(x instanceof Co)console.error(`Error: hook timed out: ${x.command}`);else if(x instanceof bo){if(console.error(`Error: hook failed (exit ${x.exitCode}): ${x.command}`),x.stderr)console.error(x.stderr)}else console.error(`Error: ${x.message}`);process.exit(1)}}},Qh=Zh});var lc={};xt(lc,{default:()=>eu});import{relative as Yh,resolve as Dr}from"path";var tu,eu;var hc=N(()=>{ct();Zt();$t();xe();Dt();tu={command:"list",aliases:["ls"],describe:"List all worktrees with their status",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("porcelain",{type:"boolean",alias:"p",describe:"Machine-readable output"}).option("all",{type:"boolean",alias:"a",describe:"List worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let s=Y(),c=await at(),f=Le(s),a=new Set([Dr(c)]),h=[c];for(let u of f){let d=Dr(u);if(!a.has(d))a.add(d),h.push(u)}e=await M.listAll(h)}else e=await M.list();let o=await Promise.all(e.map(async(s)=>({...s,focus:Yt(s.path)})));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);if(t.porcelain){for(let s of o){if(t.all)console.log(`repo ${s.repoName}`);if(console.log(`path ${s.path}`),console.log(`branch ${s.branch??"(detached)"}`),console.log(`head ${s.head}`),console.log(`dirty ${s.isDirty}`),console.log(`locked ${s.isLocked}`),s.focus&&s.focus.length>0)console.log(`focus ${s.focus.join(",")}`);console.log("")}process.exit(0)}if(e.length===0)console.log("No worktrees found."),process.exit(0);let n=Dr(process.cwd()),r=t.all&&new Set(o.map((s)=>s.repoName)).size>1,i=o.map((s)=>({repo:s.repoName,branch:s.branch??"(detached)",path:s.path===n?s.path:Yh(n,s.path)||s.path,status:s.isLocked?"locked":s.isDirty?"dirty":"clean",focus:s.focus?s.focus.join(", ").slice(0,40)+(s.focus.join(", ").length>40?"...":""):"\u2014"}));if(r){let s=Math.max(4,...i.map((u)=>u.repo.length)),c=Math.max(6,...i.map((u)=>u.branch.length)),f=Math.max(4,...i.map((u)=>u.path.length)),a=Math.max(6,...i.map((u)=>u.status.length)),h=Math.max(5,...i.map((u)=>u.focus.length));console.log(`${"Repo".padEnd(s)} ${"Branch".padEnd(c)} ${"Path".padEnd(f)} ${"Status".padEnd(a)} ${"Focus".padEnd(h)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(f)} ${"-".repeat(a)} ${"-".repeat(h)}`);for(let u of i)console.log(`${u.repo.padEnd(s)} ${u.branch.padEnd(c)} ${u.path.padEnd(f)} ${u.status.padEnd(a)} ${u.focus.padEnd(h)}`)}else{let s=Math.max(6,...i.map((h)=>h.branch.length)),c=Math.max(4,...i.map((h)=>h.path.length)),f=Math.max(6,...i.map((h)=>h.status.length)),a=Math.max(5,...i.map((h)=>h.focus.length));console.log(`${"Branch".padEnd(s)} ${"Path".padEnd(c)} ${"Status".padEnd(f)} ${"Focus".padEnd(a)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(f)} ${"-".repeat(a)}`);for(let h of i)console.log(`${h.branch.padEnd(s)} ${h.path.padEnd(c)} ${h.status.padEnd(f)} ${h.focus.padEnd(a)}`)}process.exit(0)}catch(e){if(e instanceof Gt)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},eu=tu});var pc={};xt(pc,{default:()=>nu});import{basename as uc}from"path";var ou,nu;var dc=N(()=>{ct();$t();$e();xe();En();Ge();Fe();Dt();ou={command:"remove <branch-or-path>",aliases:["rm"],describe:"Remove a worktree",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}).option("force",{type:"boolean",alias:"f",describe:"Force removal even with uncommitted changes"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.force,n=!!t.yes;try{let r=await at(),i=await M.list(r),s=Kt(i,e);if(s.isMain)console.error("Error: cannot remove the main worktree"),process.exit(1);if(await M.isDirty(s.path)&&!o)console.error(`Error: worktree has uncommitted changes: ${s.path}`),console.error("Use --force to remove anyway."),process.exit(1);if(s.isLocked){if(console.error(`Error: worktree is locked: ${s.path}`),s.lockReason)console.error(`Lock reason: ${s.lockReason}`);process.exit(1)}if(!n){if(!await Te(`Remove worktree '${s.branch??uc(s.path)}' at ${s.path}? [y/N] `))console.log("Cancelled."),process.exit(0)}let f=Y(),a=Lt(f,r);if(a.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(a.postRemove,{cwd:s.path,env:{OMW_BRANCH:s.branch??"",OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r},onOutput:(d)=>console.log(` ${d}`)}).catch((d)=>console.warn(`Warning: postRemove hook failed: ${d.message}`));let h=Yt(s.path)??[];if(h.length>0&&a.monorepo?.hooks&&a.monorepo.hooks.length>0){let d=ro(a.monorepo.hooks,h);if(d.length>0){let g=uc(r),x=s.branch??"unknown";console.log(" Running monorepo postRemove hooks..."),await $o(d,"postRemove",{cwd:s.path,env:{OMW_BRANCH:x,OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r,OMW_FOCUS_PATHS:h.join(",")},repo:g,branch:x,focusPaths:h,mainRepoPath:r,onOutput:(m)=>console.log(` ${m}`)}),console.log(" \u2713 Monorepo hooks completed")}}let u=Ae(f);if(u.autoKill){if(await po()){let g=s.branch??e;if(await xn(g,s.path,u.prefix))console.log(" \u2713 Session killed")}}await M.remove(s.path,{force:o},r),console.log(`Removed worktree: ${s.path}`);try{qt(r,{timestamp:new Date().toISOString(),event:"delete",branch:s.branch??e,path:s.path})}catch{}process.exit(0)}catch(r){wt(r)}}},nu=ou});var mc={};xt(mc,{default:()=>su});import{basename as ru}from"path";var iu,su;var xc=N(()=>{ct();Ge();$t();Fe();Dt();iu={command:"switch <branch-or-path>",aliases:["sw"],describe:"Switch to a worktree directory (outputs cd command for shell eval)",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}),handler:async(t)=>{let e=t["branch-or-path"];try{let o=await at(),n=await M.list(o),r=Kt(n,e);try{qt(o,{timestamp:new Date().toISOString(),event:"switch",branch:r.branch??e,path:r.path})}catch{}let i=Y(),s=Ae(i);if(s.enabled&&gr()){let c=r.branch??ru(r.path),f=De(c,s.prefix);if(await we(f))try{await dn(f),process.exit(0)}catch{}}console.log(`cd ${JSON.stringify(r.path)}`),process.exit(0)}catch(o){wt(o)}}},su=iu});async function gc(t,e,o,n){let r=t.filter((h)=>!h.isMain),i=r.filter((h)=>_e(h.path)),s=new Set(i.map((h)=>h.path)),c=[];if(e.autoCleanMerged){let h=r.filter((d)=>!s.has(d.path)&&d.branch);c=(await Qt(h,10,async(d)=>({wt:d,isMerged:await M.isMergedInto(d.branch,o,n)}))).filter((d)=>d.isMerged&&!d.wt.isDirty).map((d)=>d.wt)}let f=[];if(e.staleAfterDays&&e.staleAfterDays>0){let h=new Date,u=r.filter((g)=>!s.has(g.path));f=(await Qt(u,10,async(g)=>{let x=await M.getWorktreeLastActivity(g.path),m=x?Math.floor((h.getTime()-x.getTime())/86400000):1/0;return{wt:g,lastActivity:x,daysSince:m}})).filter((g)=>g.daysSince>=e.staleAfterDays).map((g)=>({worktree:g.wt,lastActivity:g.lastActivity,daysSinceActivity:g.daysSince===1/0?-1:g.daysSince}))}let a=e.maxWorktrees?r.length>e.maxWorktrees:!1;return{merged:c,stale:f,pinProtected:i,overLimit:a,totalCount:r.length,maxWorktrees:e.maxWorktrees??null}}function wc(t){let e=[];if(t.pinProtected.length>0){e.push(`Pin-protected worktrees (${t.pinProtected.length}):`);for(let o of t.pinProtected)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.merged.length>0){e.push(`Merged worktrees (${t.merged.length}):`);for(let o of t.merged)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.stale.length>0){e.push(`Stale worktrees (${t.stale.length}):`);for(let o of t.stale){let n=o.daysSinceActivity<0?"unknown":`${o.daysSinceActivity} days`;e.push(` ${o.worktree.branch??"(detached)"} \u2014 inactive ${n}`)}}if(t.overLimit)e.push(`Worktree limit exceeded: ${t.totalCount}/${t.maxWorktrees}`);if(e.length===0)e.push("All worktrees are healthy.");return e.join(`
21
- `)}var bc=N(()=>{ct();Eo()});var Cc={};xt(Cc,{default:()=>au});var cu,au;var $c=N(()=>{ct();$t();bc();Eo();Dt();cu={command:"clean",describe:"Remove merged worktrees and prune stale entries",builder:(t)=>t.option("dry-run",{type:"boolean",alias:"n",describe:"Show what would be removed"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation"}).option("stale",{type:"boolean",describe:"Also show stale worktrees (based on lifecycle config)"}),handler:async(t)=>{let e=!!(t["dry-run"]||t.n),o=!!t.yes;try{let n=await at(),r=await M.list(n),s=(r.find((h)=>h.isMain)??r[0])?.branch??"main",c=r.filter((h)=>{if(h.isMain)return!1;if(_e(h.path))return console.log(` Skipping (pinned): ${h.branch}`),!1;if(!h.branch)return!1;return!0}),f=await Qt(c,10,async(h)=>{let[u,d]=await Promise.all([M.isMergedInto(h.branch,s,n),M.isDirty(h.path)]);return{wt:h,merged:u,dirty:d}}),a=[];for(let{wt:h,merged:u,dirty:d}of f){if(!u)continue;if(d){console.log(` Skipping (dirty): ${h.branch}`);continue}a.push(h)}if(a.length===0)console.log("No merged worktrees to clean.");else{console.log(e?"Would remove:":"To remove:");for(let h of a)console.log(` ${h.branch} (${h.path})`)}if(!e&&a.length>0){if(!o){if(!await Te(`
22
- Remove ${a.length} worktree(s)? [y/N] `))console.log("Cancelled."),process.exit(0)}for(let h of a)await M.remove(h.path,{force:!1},n),console.log(` Removed: ${h.branch}`)}if(!e)await M.prune(n),console.log("Pruned stale worktree entries.");if(t.stale){let h=Y();if(h.lifecycle){let u=await gc(r,h.lifecycle,s,n);console.log(),console.log(wc(u))}else console.log(`
23
- No lifecycle config found. Add 'lifecycle' to your config to enable stale detection.`)}process.exit(0)}catch(n){wt(n)}}},au=cu});import{existsSync as fu,mkdirSync as lu,readFileSync as hu,writeFileSync as uu}from"fs";import{dirname as pu}from"path";function Sc(){let t=Nt();try{return Y(t)}catch{if(!fu(t))throw Error("Failed to load config");let e=hu(t,"utf-8");return JSON.parse(e)}}function Pc(t){let e=Nt(),o=pu(e);lu(o,{recursive:!0,mode:448});let n=`${JSON.stringify(t,null,2)}
24
- `;try{Jo(e,n)}catch{uu(e,n,{encoding:"utf-8",mode:384})}}function Fr(t){return Object.keys(t.profiles??{})}function yc(t){let e=Sc();Pc({...e,activeProfile:t})}function Ec(t){return t.activeProfile??null}function Rc(t){let e=Sc(),o={...e.profiles??{}};delete o[t],Pc({...e,profiles:o,activeProfile:e.activeProfile===t?void 0:e.activeProfile})}var Mc=N(()=>{$t()});var Oc={};xt(Oc,{default:()=>gu});import{spawnSync as du}from"child_process";import{readFileSync as mu}from"fs";var xu,gu;var Wc=N(()=>{$t();Mc();xu={command:"config",describe:"Manage oh-my-worktree configuration",builder:(t)=>t.option("init",{type:"boolean",describe:"Create default config file"}).option("show",{type:"boolean",alias:"s",describe:"Print current config as JSON"}).option("edit",{type:"boolean",alias:"e",describe:"Open config in $EDITOR"}).option("path",{type:"boolean",describe:"Print config file path"}).option("validate",{type:"boolean",describe:"Validate config against schema"}).option("profiles",{type:"boolean",describe:"List config profiles"}).option("profile",{type:"string",describe:"Profile name for activation/deletion"}).option("activate",{type:"boolean",describe:"Activate the specified profile"}).option("delete",{type:"boolean",describe:"Delete the specified profile"}),handler:async(t)=>{let e=Nt();if(t.init){let o=fe();console.log(`Config initialized: ${o}`),process.exit(0)}if(t.path)console.log(e),process.exit(0);if(t.show){try{let o=Y();console.log(JSON.stringify(o,null,2))}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.edit){let o=process.env.EDITOR??process.env.VISUAL??"vi";fe();let n=du(o,[e],{stdio:"inherit"});process.exit(n.status??0)}if(t.validate)try{let o=mu(e,"utf-8"),n;try{n=JSON.parse(o)}catch{console.error(`Error: invalid JSON in config file: ${e}`),process.exit(1)}let r=No(n);if(r.length===0)console.log(`\u2713 Config is valid: ${e}`),process.exit(0);else{console.error(`Config validation failed (${r.length} error(s)):`);for(let i of r)console.error(` ${i.field}: ${i.message}`);process.exit(1)}}catch(o){console.error(`Error reading config: ${o.message}`),process.exit(1)}if(t.profiles){try{let o=Y(),n=Fr(o),r=Ec(o);for(let i of n)console.log(`${i}${i===r?" \u2605":""}`)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.activate){try{let o=Y(),n=t.profile;if(!Fr(o).includes(n))console.error(`Error: profile '${n}' does not exist.`),process.exit(1);yc(n)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.delete)Rc(t.profile),process.exit(0);console.log("Usage: omw config [options]"),console.log(""),console.log("Options:"),console.log(" --init Create default config file"),console.log(" --show, -s Print current config as JSON"),console.log(" --edit, -e Open config in $EDITOR"),console.log(" --path Print config file path"),console.log(" --validate Validate config against schema"),console.log(" --profiles List config profiles"),console.log(" --profile Profile name for activation/deletion"),console.log(" --activate Activate the specified profile"),console.log(" --delete Delete the specified profile"),console.log(""),console.log(`Config path: ${e}`),process.exit(0)}},gu=xu});var Dc={};xt(Dc,{default:()=>bu});var wu,bu;var Fc=N(()=>{yr();wu={command:"doctor",describe:"Check worktree health and diagnose issues",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("fix",{type:"boolean",describe:"Auto-fix issues (prune stale, remove orphans, unlock stale locks)"}),handler:async(t)=>{let e=process.cwd(),o=await yo(e);if(t.json&&!t.fix){let i={pass:o.checks.filter((s)=>s.status==="pass").length,warn:o.checks.filter((s)=>s.status==="warn").length,fail:o.checks.filter((s)=>s.status==="fail").length};console.log(JSON.stringify({healthy:o.healthy,checks:o.checks,summary:i},null,2)),process.exit(o.healthy?0:1)}console.log(`oh-my-worktree doctor
19
+ Setup failed, rolling back...`);try{await M.remove(u,{force:!0},n),console.error("Rolled back worktree.")}catch(m){console.error(`Warning: rollback failed: ${m.message}`)}if(x instanceof Po)console.error(`Error: hook timed out: ${x.command}`);else if(x instanceof $o){if(console.error(`Error: hook failed (exit ${x.exitCode}): ${x.command}`),x.stderr)console.error(x.stderr)}else console.error(`Error: ${x.message}`);process.exit(1)}}},fu=lu});var mc={};xt(mc,{default:()=>pu});import{relative as hu,resolve as Lr}from"path";var uu,pu;var xc=H(()=>{st();Qt();St();ge();Dt();uu={command:"list",aliases:["ls"],describe:"List all worktrees with their status",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("porcelain",{type:"boolean",alias:"p",describe:"Machine-readable output"}).option("all",{type:"boolean",alias:"a",describe:"List worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let s=Q(),c=await ct(),l=Ae(s),a=new Set([Lr(c)]),h=[c];for(let u of l){let d=Lr(u);if(!a.has(d))a.add(d),h.push(u)}e=await M.listAll(h)}else e=await M.list();let o=await Promise.all(e.map(async(s)=>({...s,focus:te(s.path)})));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);if(t.porcelain){for(let s of o){if(t.all)console.log(`repo ${s.repoName}`);if(console.log(`path ${s.path}`),console.log(`branch ${s.branch??"(detached)"}`),console.log(`head ${s.head}`),console.log(`dirty ${s.isDirty}`),console.log(`locked ${s.isLocked}`),s.focus&&s.focus.length>0)console.log(`focus ${s.focus.join(",")}`);console.log("")}process.exit(0)}if(e.length===0)console.log("No worktrees found."),process.exit(0);let n=Lr(process.cwd()),r=t.all&&new Set(o.map((s)=>s.repoName)).size>1,i=o.map((s)=>({repo:s.repoName,branch:s.branch??"(detached)",path:s.path===n?s.path:hu(n,s.path)||s.path,status:s.isLocked?"locked":s.isDirty?"dirty":"clean",focus:s.focus?s.focus.join(", ").slice(0,40)+(s.focus.join(", ").length>40?"...":""):"\u2014"}));if(r){let s=Math.max(4,...i.map((u)=>u.repo.length)),c=Math.max(6,...i.map((u)=>u.branch.length)),l=Math.max(4,...i.map((u)=>u.path.length)),a=Math.max(6,...i.map((u)=>u.status.length)),h=Math.max(5,...i.map((u)=>u.focus.length));console.log(`${"Repo".padEnd(s)} ${"Branch".padEnd(c)} ${"Path".padEnd(l)} ${"Status".padEnd(a)} ${"Focus".padEnd(h)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(l)} ${"-".repeat(a)} ${"-".repeat(h)}`);for(let u of i)console.log(`${u.repo.padEnd(s)} ${u.branch.padEnd(c)} ${u.path.padEnd(l)} ${u.status.padEnd(a)} ${u.focus.padEnd(h)}`)}else{let s=Math.max(6,...i.map((h)=>h.branch.length)),c=Math.max(4,...i.map((h)=>h.path.length)),l=Math.max(6,...i.map((h)=>h.status.length)),a=Math.max(5,...i.map((h)=>h.focus.length));console.log(`${"Branch".padEnd(s)} ${"Path".padEnd(c)} ${"Status".padEnd(l)} ${"Focus".padEnd(a)}`),console.log(`${"-".repeat(s)} ${"-".repeat(c)} ${"-".repeat(l)} ${"-".repeat(a)}`);for(let h of i)console.log(`${h.branch.padEnd(s)} ${h.path.padEnd(c)} ${h.status.padEnd(l)} ${h.focus.padEnd(a)}`)}process.exit(0)}catch(e){if(e instanceof Ht)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}},pu=uu});var wc={};xt(wc,{default:()=>mu});import{basename as gc}from"path";var du,mu;var bc=H(()=>{st();St();$e();ge();Dn();He();Le();Dt();du={command:"remove <branch-or-path>",aliases:["rm"],describe:"Remove a worktree",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}).option("force",{type:"boolean",alias:"f",describe:"Force removal even with uncommitted changes"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.force,n=!!t.yes;try{let r=await ct(),i=await M.list(r),s=Xt(i,e);if(s.isMain)console.error("Error: cannot remove the main worktree"),process.exit(1);if(await M.isDirty(s.path)&&!o)console.error(`Error: worktree has uncommitted changes: ${s.path}`),console.error("Use --force to remove anyway."),process.exit(1);if(s.isLocked){if(console.error(`Error: worktree is locked: ${s.path}`),s.lockReason)console.error(`Lock reason: ${s.lockReason}`);process.exit(1)}if(!n){if(!await ve(`Remove worktree '${s.branch??gc(s.path)}' at ${s.path}? [y/N] `))console.log("Cancelled."),process.exit(0)}let l=Q(),a=Lt(l,r);if(a.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(a.postRemove,{cwd:s.path,env:{OMW_BRANCH:s.branch??"",OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r},onOutput:(d)=>console.log(` ${d}`)}).catch((d)=>console.warn(`Warning: postRemove hook failed: ${d.message}`));let h=te(s.path)??[];if(h.length>0&&a.monorepo?.hooks&&a.monorepo.hooks.length>0){let d=io(a.monorepo.hooks,h);if(d.length>0){let g=gc(r),x=s.branch??"unknown";console.log(" Running monorepo postRemove hooks..."),await yo(d,"postRemove",{cwd:s.path,env:{OMW_BRANCH:x,OMW_WORKTREE_PATH:s.path,OMW_REPO_PATH:r,OMW_FOCUS_PATHS:h.join(",")},repo:g,branch:x,focusPaths:h,mainRepoPath:r,onOutput:(m)=>console.log(` ${m}`)}),console.log(" \u2713 Monorepo hooks completed")}}let u=je(l);if(u.autoKill){if(await mo()){let g=s.branch??e;if(await Cn(g,s.path,u.prefix))console.log(" \u2713 Session killed")}}await M.remove(s.path,{force:o},r),console.log(`Removed worktree: ${s.path}`);try{qt(r,{timestamp:new Date().toISOString(),event:"delete",branch:s.branch??e,path:s.path})}catch{}process.exit(0)}catch(r){wt(r)}}},mu=du});var Cc={};xt(Cc,{default:()=>wu});import{basename as xu}from"path";var gu,wu;var Sc=H(()=>{st();He();St();Le();Dt();gu={command:"switch <branch-or-path>",aliases:["sw"],describe:"Switch to a worktree directory (outputs cd command for shell eval)",builder:(t)=>t.positional("branch-or-path",{type:"string",demandOption:!0}),handler:async(t)=>{let e=t["branch-or-path"];try{let o=await ct(),n=await M.list(o),r=Xt(n,e);try{qt(o,{timestamp:new Date().toISOString(),event:"switch",branch:r.branch??e,path:r.path})}catch{}let i=Q(),s=je(i);if(s.enabled&&Cr()){let c=r.branch??xu(r.path),l=Be(c,s.prefix);if(await be(l))try{await wn(l),process.exit(0)}catch{}}console.log(`cd ${JSON.stringify(r.path)}`),process.exit(0)}catch(o){wt(o)}}},wu=gu});async function $c(t,e,o,n){let r=t.filter((h)=>!h.isMain),i=r.filter((h)=>Ge(h.path)),s=new Set(i.map((h)=>h.path)),c=[];if(e.autoCleanMerged){let h=r.filter((d)=>!s.has(d.path)&&d.branch);c=(await Yt(h,10,async(d)=>({wt:d,isMerged:await M.isMergedInto(d.branch,o,n)}))).filter((d)=>d.isMerged&&!d.wt.isDirty).map((d)=>d.wt)}let l=[];if(e.staleAfterDays&&e.staleAfterDays>0){let h=new Date,u=r.filter((g)=>!s.has(g.path));l=(await Yt(u,10,async(g)=>{let x=await M.getWorktreeLastActivity(g.path),m=x?Math.floor((h.getTime()-x.getTime())/86400000):1/0;return{wt:g,lastActivity:x,daysSince:m}})).filter((g)=>g.daysSince>=e.staleAfterDays).map((g)=>({worktree:g.wt,lastActivity:g.lastActivity,daysSinceActivity:g.daysSince===1/0?-1:g.daysSince}))}let a=e.maxWorktrees?r.length>e.maxWorktrees:!1;return{merged:c,stale:l,pinProtected:i,overLimit:a,totalCount:r.length,maxWorktrees:e.maxWorktrees??null}}function Pc(t){let e=[];if(t.pinProtected.length>0){e.push(`Pin-protected worktrees (${t.pinProtected.length}):`);for(let o of t.pinProtected)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.merged.length>0){e.push(`Merged worktrees (${t.merged.length}):`);for(let o of t.merged)e.push(` ${o.branch??"(detached)"} \u2192 ${o.path}`)}if(t.stale.length>0){e.push(`Stale worktrees (${t.stale.length}):`);for(let o of t.stale){let n=o.daysSinceActivity<0?"unknown":`${o.daysSinceActivity} days`;e.push(` ${o.worktree.branch??"(detached)"} \u2014 inactive ${n}`)}}if(t.overLimit)e.push(`Worktree limit exceeded: ${t.totalCount}/${t.maxWorktrees}`);if(e.length===0)e.push("All worktrees are healthy.");return e.join(`
20
+ `)}var yc=H(()=>{st();Oo()});var Ec={};xt(Ec,{default:()=>Cu});var bu,Cu;var Rc=H(()=>{st();St();yc();Oo();Dt();bu={command:"clean",describe:"Remove merged worktrees and prune stale entries",builder:(t)=>t.option("dry-run",{type:"boolean",alias:"n",describe:"Show what would be removed"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation"}).option("stale",{type:"boolean",describe:"Also show stale worktrees (based on lifecycle config)"}),handler:async(t)=>{let e=!!(t["dry-run"]||t.n),o=!!t.yes;try{let n=await ct(),r=await M.list(n),s=(r.find((h)=>h.isMain)??r[0])?.branch??"main",c=r.filter((h)=>{if(h.isMain)return!1;if(Ge(h.path))return console.log(` Skipping (pinned): ${h.branch}`),!1;if(!h.branch)return!1;return!0}),l=await Yt(c,10,async(h)=>{let[u,d]=await Promise.all([M.isMergedInto(h.branch,s,n),M.isDirty(h.path)]);return{wt:h,merged:u,dirty:d}}),a=[];for(let{wt:h,merged:u,dirty:d}of l){if(!u)continue;if(d){console.log(` Skipping (dirty): ${h.branch}`);continue}a.push(h)}if(a.length===0)console.log("No merged worktrees to clean.");else{console.log(e?"Would remove:":"To remove:");for(let h of a)console.log(` ${h.branch} (${h.path})`)}if(!e&&a.length>0){if(!o){if(!await ve(`
21
+ Remove ${a.length} worktree(s)? [y/N] `))console.log("Cancelled."),process.exit(0)}for(let h of a)await M.remove(h.path,{force:!1},n),console.log(` Removed: ${h.branch}`)}if(!e)await M.prune(n),console.log("Pruned stale worktree entries.");if(t.stale){let h=Q();if(h.lifecycle){let u=await $c(r,h.lifecycle,s,n);console.log(),console.log(Pc(u))}else console.log(`
22
+ No lifecycle config found. Add 'lifecycle' to your config to enable stale detection.`)}process.exit(0)}catch(n){wt(n)}}},Cu=bu});import{existsSync as Su,mkdirSync as $u,readFileSync as Pu,writeFileSync as yu}from"fs";import{dirname as Eu}from"path";function Mc(){let t=kt();try{return Q(t)}catch{if(!Su(t))throw Error("Failed to load config");let e=Pu(t,"utf-8");return JSON.parse(e)}}function Oc(t){let e=kt(),o=Eu(e);$u(o,{recursive:!0,mode:448});let n=`${JSON.stringify(t,null,2)}
23
+ `;try{Uo(e,n)}catch{yu(e,n,{encoding:"utf-8",mode:384})}}function Ir(t){return Object.keys(t.profiles??{})}function Wc(t){let e=Mc();Oc({...e,activeProfile:t})}function Dc(t){return t.activeProfile??null}function Fc(t){let e=Mc(),o={...e.profiles??{}};delete o[t],Oc({...e,profiles:o,activeProfile:e.activeProfile===t?void 0:e.activeProfile})}var Bc=H(()=>{St()});var Lc={};xt(Lc,{default:()=>Wu});import{spawnSync as Ru}from"child_process";import{readFileSync as Mu}from"fs";var Ou,Wu;var Ic=H(()=>{St();Bc();Ou={command:"config",describe:"Manage oh-my-worktree configuration",builder:(t)=>t.option("init",{type:"boolean",describe:"Create default config file"}).option("show",{type:"boolean",alias:"s",describe:"Print current config as JSON"}).option("edit",{type:"boolean",alias:"e",describe:"Open config in $EDITOR"}).option("path",{type:"boolean",describe:"Print config file path"}).option("validate",{type:"boolean",describe:"Validate config against schema"}).option("profiles",{type:"boolean",describe:"List config profiles"}).option("profile",{type:"string",describe:"Profile name for activation/deletion"}).option("activate",{type:"boolean",describe:"Activate the specified profile"}).option("delete",{type:"boolean",describe:"Delete the specified profile"}),handler:async(t)=>{let e=kt();if(t.init){let o=ue();console.log(`Config initialized: ${o}`),process.exit(0)}if(t.path)console.log(e),process.exit(0);if(t.show){try{let o=Q();console.log(JSON.stringify(o,null,2))}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.edit){let o=process.env.EDITOR??process.env.VISUAL??"vi";ue();let n=Ru(o,[e],{stdio:"inherit"});process.exit(n.status??0)}if(t.validate)try{let o=Mu(e,"utf-8"),n;try{n=JSON.parse(o)}catch{console.error(`Error: invalid JSON in config file: ${e}`),process.exit(1)}let r=zo(n);if(r.length===0)console.log(`\u2713 Config is valid: ${e}`),process.exit(0);else{console.error(`Config validation failed (${r.length} error(s)):`);for(let i of r)console.error(` ${i.field}: ${i.message}`);process.exit(1)}}catch(o){console.error(`Error reading config: ${o.message}`),process.exit(1)}if(t.profiles){try{let o=Q(),n=Ir(o),r=Dc(o);for(let i of n)console.log(`${i}${i===r?" \u2605":""}`)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.activate){try{let o=Q(),n=t.profile;if(!Ir(o).includes(n))console.error(`Error: profile '${n}' does not exist.`),process.exit(1);Wc(n)}catch(o){console.error(`Error loading config: ${o.message}`),process.exit(1)}process.exit(0)}if(t.profile&&t.delete)Fc(t.profile),process.exit(0);console.log("Usage: omw config [options]"),console.log(""),console.log("Options:"),console.log(" --init Create default config file"),console.log(" --show, -s Print current config as JSON"),console.log(" --edit, -e Open config in $EDITOR"),console.log(" --path Print config file path"),console.log(" --validate Validate config against schema"),console.log(" --profiles List config profiles"),console.log(" --profile Profile name for activation/deletion"),console.log(" --activate Activate the specified profile"),console.log(" --delete Delete the specified profile"),console.log(""),console.log(`Config path: ${e}`),process.exit(0)}},Wu=Ou});var Ac={};xt(Ac,{default:()=>Fu});var Du,Fu;var jc=H(()=>{Mr();Du={command:"doctor",describe:"Check worktree health and diagnose issues",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("fix",{type:"boolean",describe:"Auto-fix issues (prune stale, remove orphans, unlock stale locks)"}),handler:async(t)=>{let e=process.cwd(),o=await Mo(e);if(t.json&&!t.fix){let i={pass:o.checks.filter((s)=>s.status==="pass").length,warn:o.checks.filter((s)=>s.status==="warn").length,fail:o.checks.filter((s)=>s.status==="fail").length};console.log(JSON.stringify({healthy:o.healthy,checks:o.checks,summary:i},null,2)),process.exit(o.healthy?0:1)}console.log(`oh-my-worktree doctor
25
24
  `);for(let i of o.checks){let s=i.status==="pass"?"\u2713":i.status==="warn"?"\u26A0":"\u2717";if(console.log(`${s} ${i.name}: ${i.message}`),i.detail)for(let c of i.detail)console.log(` \u2192 ${c}`)}let n=o.checks.filter((i)=>i.status==="warn").length,r=o.checks.filter((i)=>i.status==="fail").length;if(o.healthy)console.log(`
26
25
  All checks passed.`);else{let i=[];if(r>0)i.push(`${r} error(s)`);if(n>0)i.push(`${n} warning(s)`);console.log(`
27
26
  ${i.join(", ")} found.`)}if(t.fix){if(o.healthy)console.log(`
28
27
  Nothing to fix.`),process.exit(0);console.log(`
29
28
  Running auto-fix...
30
- `);let i=await On(e);if(i.length===0)console.log("No auto-fixable issues found.");else{for(let a of i){let h=a.success?"\u2713":"\u2717",u=a.detail?` (${a.detail})`:"";console.log(`${h} ${a.action}${u}`)}let c=i.filter((a)=>a.success).length,f=i.filter((a)=>!a.success).length;console.log(`
31
- Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await yo(e);if(s.healthy)console.log("All checks now pass.");process.exit(s.healthy?0:1)}process.exit(o.healthy?0:1)}},bu=wu});var Ac={};xt(Ac,{default:()=>Ru});function Cu(t){if(t?.includes("fish"))return"fish";if(t?.includes("bash"))return"bash";return"zsh"}function Bc(){return`omw() {
29
+ `);let i=await Fn(e);if(i.length===0)console.log("No auto-fixable issues found.");else{for(let a of i){let h=a.success?"\u2713":"\u2717",u=a.detail?` (${a.detail})`:"";console.log(`${h} ${a.action}${u}`)}let c=i.filter((a)=>a.success).length,l=i.filter((a)=>!a.success).length;console.log(`
30
+ Fixed ${c} issue(s)${l>0?`, ${l} failed`:""}.`)}let s=await Mo(e);if(s.healthy)console.log("All checks now pass.");process.exit(s.healthy?0:1)}process.exit(o.healthy?0:1)}},Fu=Du});var Gc={};xt(Gc,{default:()=>Tu});function Bu(t){if(t?.includes("fish"))return"fish";if(t?.includes("bash"))return"bash";return"zsh"}function _c(){return`omw() {
32
31
  if [ "$1" = "switch" ] || [ "$1" = "sw" ]; then
33
32
  local output
34
33
  output=$(command omw "$@" 2>/dev/null)
@@ -46,7 +45,7 @@ Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await yo(e);if(s.healthy)c
46
45
  else
47
46
  command omw "$@"
48
47
  fi
49
- }`}function Lc(){return`function omw
48
+ }`}function Tc(){return`function omw
50
49
  if test "$argv[1]" = "switch"; or test "$argv[1]" = "sw"
51
50
  set output (command omw $argv 2>/dev/null)
52
51
  set status_code $status
@@ -63,7 +62,7 @@ Fixed ${c} issue(s)${f>0?`, ${f} failed`:""}.`)}let s=await yo(e);if(s.healthy)c
63
62
  else
64
63
  command omw $argv
65
64
  end
66
- end`}function $u(){return`_omw_completions() {
65
+ end`}function Lu(){return`_omw_completions() {
67
66
  local cur="\${COMP_WORDS[COMP_CWORD]}"
68
67
  local prev="\${COMP_WORDS[COMP_CWORD-1]}"
69
68
  local commands="add list remove switch clean config doctor pin log archive rename clone import exec diff open status shell-init"
@@ -87,7 +86,7 @@ end`}function $u(){return`_omw_completions() {
87
86
  ;;
88
87
  esac
89
88
  }
90
- complete -F _omw_completions omw`}function Su(){return`_omw() {
89
+ complete -F _omw_completions omw`}function Iu(){return`_omw() {
91
90
  local -a commands
92
91
  commands=(
93
92
  'add:Add a new worktree'
@@ -124,7 +123,7 @@ complete -F _omw_completions omw`}function Su(){return`_omw() {
124
123
  esac
125
124
  fi
126
125
  }
127
- compdef _omw omw`}function Pu(){return`complete -c omw -f
126
+ compdef _omw omw`}function Au(){return`complete -c omw -f
128
127
  complete -c omw -n '__fish_use_subcommand' -a 'add' -d 'Add a new worktree'
129
128
  complete -c omw -n '__fish_use_subcommand' -a 'list' -d 'List worktrees'
130
129
  complete -c omw -n '__fish_use_subcommand' -a 'remove' -d 'Remove a worktree'
@@ -142,29 +141,29 @@ complete -c omw -n '__fish_use_subcommand' -a 'exec' -d 'Run command'
142
141
  complete -c omw -n '__fish_use_subcommand' -a 'diff' -d 'Show diff'
143
142
  complete -c omw -n '__fish_use_subcommand' -a 'open' -d 'Open in editor'
144
143
  complete -c omw -n '__fish_use_subcommand' -a 'status' -d 'Show status'
145
- complete -c omw -n '__fish_seen_subcommand_from add switch rename pin archive' -a '(git branch --format="%(refname:short)" 2>/dev/null)'`}function yu(t){switch(t){case"bash":return $u();case"zsh":return Su();case"fish":return Pu()}}var Eu,Ru;var Ic=N(()=>{Eu={command:"shell-init [shell]",describe:"Print shell integration code for omw switch",builder:(t)=>t.positional("shell",{type:"string",choices:["bash","zsh","fish"],describe:"Shell to generate integration for (auto-detected if omitted)"}).option("completions",{type:"string",describe:"Generate shell completions (bash, zsh, fish)",coerce:(e)=>e===!0?void 0:e}),handler:async(t)=>{let e="completions"in t,o=t.shell,n=t.completions,r=o??n??Cu(process.env.SHELL);if(e){let i=r==="fish"?Lc():Bc(),s=yu(r);console.log(i+`
146
- `+s),process.exit(0)}if(r==="fish")console.log(Lc()),process.exit(0);console.log(Bc()),process.exit(0)}},Ru=Eu});var _c={};xt(_c,{default:()=>Ou});import{resolve as Wn}from"path";function jc(t,e){if(t.length<=e)return t;return t.slice(0,e-3)+"..."}var Mu,Ou;var Tc=N(()=>{ct();Zt();$t();xe();Dt();Mu={command:"status",aliases:["st"],describe:"Show status overview of all worktrees",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("all",{type:"boolean",alias:"a",describe:"Show worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let c=Y(),f=await at(),a=Le(c),h=new Set([Wn(f)]),u=[f];for(let d of a){let g=Wn(d);if(!h.has(g))h.add(g),u.push(d)}e=await M.listAll(u)}else e=await M.list();if(e.length===0)console.log("No worktrees found."),process.exit(0);let o=await Promise.all(e.map(async(c)=>{let[f,a,h,u]=await Promise.all([c.branch?M.getAheadBehind(c.branch,c.path):Promise.resolve({ahead:0,behind:0}),M.getLastCommit(c.path),M.getDirtyCount(c.path),Promise.resolve(Yt(c.path))]);return{...c,aheadBehind:f,lastCommit:a,dirtyCount:h,focus:u}}));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);let n=Wn(process.cwd()),r=t.all&&new Set(o.map((c)=>c.repoName)).size>1,i=o.map((c)=>{let a=(Wn(c.path)===n?"* ":" ")+(c.branch??"(detached)"),h;if(c.isLocked)h="locked";else if(c.dirtyCount>0)h=`${c.dirtyCount} dirty`;else h="clean";let u=[];if(c.aheadBehind.ahead>0)u.push(`+${c.aheadBehind.ahead}`);if(c.aheadBehind.behind>0)u.push(`-${c.aheadBehind.behind}`);let d=u.length>0?u.join(" "):"=",g=c.lastCommit?`${c.lastCommit.relativeDate} ${jc(c.lastCommit.message,30)}`:"\u2014",x=c.focus&&c.focus.length>0?jc(c.focus.join(", "),30):"\u2014";return{repo:c.repoName,branch:a,dirty:h,sync:d,lastCommit:g,focus:x}}),s={branch:Math.max(6,...i.map((c)=>c.branch.length)),dirty:Math.max(6,...i.map((c)=>c.dirty.length)),sync:Math.max(4,...i.map((c)=>c.sync.length)),lastCommit:Math.max(11,...i.map((c)=>c.lastCommit.length)),focus:Math.max(5,...i.map((c)=>c.focus.length)),repo:Math.max(4,...i.map((c)=>c.repo.length))};if(r){let c=`${"Repo".padEnd(s.repo)} ${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,f=`${"-".repeat(s.repo)} ${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(f);for(let a of i)console.log(`${a.repo.padEnd(s.repo)} ${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}else{let c=`${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,f=`${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(f);for(let a of i)console.log(`${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}process.exit(0)}catch(e){if(e instanceof Gt)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}};Ou=Mu});var Hc={};xt(Hc,{default:()=>Bu});import{existsSync as Wu}from"fs";function Du(t){if(t)return t;let e=process.env.VISUAL||process.env.EDITOR;if(e)return e;for(let o of Gc)try{if(Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return o}catch{continue}return null}var Gc,Fu,Bu;var Nc=N(()=>{ct();Dt();Gc=["code","cursor","vim","nvim","emacs","nano","subl","zed","idea","webstorm"];Fu={command:"open [branch-or-path]",describe:"Open a worktree in your editor/IDE",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path (defaults to current worktree)"}).option("editor",{type:"string",alias:"e",describe:"Editor command to use (overrides $VISUAL/$EDITOR)"}).option("list-editors",{type:"boolean",describe:"List detected editors"}),handler:async(t)=>{if(t["list-editors"]){let e=process.env.VISUAL||process.env.EDITOR;if(e)console.log(`$VISUAL/$EDITOR: ${e}`);for(let o of Gc)try{let n=Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0){let r=new TextDecoder().decode(n.stdout).trim();console.log(` ${o}: ${r}`)}}catch{}process.exit(0)}try{let e=t["branch-or-path"],o;if(!e)o=process.cwd();else{let i=await at(),s=await M.list(i);o=Kt(s,e).path}if(!Wu(o))console.error(`Error: worktree path does not exist: ${o}`),process.exit(1);let n=Du(t.editor);if(!n)console.error("Error: no editor detected."),console.error("Set $VISUAL or $EDITOR, or use --editor <command>."),console.error("Detected editors can be listed with: omw open --list-editors"),process.exit(1);console.log(`Opening ${o} with ${n}...`),await Bun.spawn([n,o],{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited,process.exit(0)}catch(e){wt(e)}}},Bu=Fu});var kc={};xt(kc,{default:()=>Au});import{resolve as Jc}from"path";var Lu,Au;var zc=N(()=>{ct();$t();Dt();Lu={command:"exec <command>",describe:"Run a command in each worktree",builder:(t)=>t.positional("command",{type:"string",describe:"Shell command to execute",demandOption:!0}).option("all",{type:"boolean",alias:"a",describe:"Run across all configured repos"}).option("dirty",{type:"boolean",describe:"Only run in dirty worktrees"}).option("clean",{type:"boolean",describe:"Only run in clean worktrees"}).option("behind",{type:"boolean",describe:"Only run in worktrees behind upstream"}).option("parallel",{type:"boolean",alias:"p",describe:"Run commands in parallel (default: sequential)"}).option("json",{type:"boolean",alias:"j",describe:"Output results as JSON"}),handler:async(t)=>{let e=t.command,o=!!t.parallel,n=!!t.json;try{let r;if(t.all){let a=Y(),h=await at(),u=Le(a),d=new Set([Jc(h)]),g=[h];for(let x of u){let m=Jc(x);if(!d.has(m))d.add(m),g.push(x)}r=await M.listAll(g)}else r=await M.list();let i=r.filter((a)=>!a.isMain);if(t.dirty)i=i.filter((a)=>a.isDirty);if(t.clean)i=i.filter((a)=>!a.isDirty);if(t.behind)i=(await Qt(i,10,async(h)=>{if(!h.branch)return{wt:h,behind:!1};let u=await M.getAheadBehind(h.branch,h.path);return{wt:h,behind:u.behind>0}})).filter((h)=>h.behind).map((h)=>h.wt);if(i.length===0)console.log("No matching worktrees found."),process.exit(0);if(!n)console.log(`Running '${e}' in ${i.length} worktree(s)...
147
- `);let s=async(a)=>{let h=Bun.spawn(["sh","-c",e],{cwd:a.path,stdout:"pipe",stderr:"pipe",env:{...Bun.env,OMW_BRANCH:a.branch??"",OMW_WORKTREE_PATH:a.path,OMW_REPO_PATH:a.repoPath}}),[u,d,g]=await Promise.all([new Response(h.stdout).text(),new Response(h.stderr).text(),h.exited]);return{branch:a.branch??"(detached)",path:a.path,exitCode:g,stdout:u.trim(),stderr:d.trim()}},c;if(o)c=await Qt(i,10,s);else{c=[];for(let a of i)c.push(await s(a))}if(n)console.log(JSON.stringify(c,null,2));else{for(let u of c){let d=u.exitCode===0?"\u2713":"\u2717";if(console.log(`${d} ${u.branch} (exit ${u.exitCode})`),u.stdout)for(let g of u.stdout.split(`
144
+ complete -c omw -n '__fish_seen_subcommand_from add switch rename pin archive' -a '(git branch --format="%(refname:short)" 2>/dev/null)'`}function ju(t){switch(t){case"bash":return Lu();case"zsh":return Iu();case"fish":return Au()}}var _u,Tu;var vc=H(()=>{_u={command:"shell-init [shell]",describe:"Print shell integration code for omw switch",builder:(t)=>t.positional("shell",{type:"string",choices:["bash","zsh","fish"],describe:"Shell to generate integration for (auto-detected if omitted)"}).option("completions",{type:"string",describe:"Generate shell completions (bash, zsh, fish)",coerce:(e)=>e===!0?void 0:e}),handler:async(t)=>{let e="completions"in t,o=t.shell,n=t.completions,r=o??n??Bu(process.env.SHELL);if(e){let i=r==="fish"?Tc():_c(),s=ju(r);console.log(i+`
145
+ `+s),process.exit(0)}if(r==="fish")console.log(Tc()),process.exit(0);console.log(_c()),process.exit(0)}},Tu=_u});var kc={};xt(kc,{default:()=>vu});import{resolve as Bn}from"path";function Hc(t,e){if(t.length<=e)return t;return t.slice(0,e-3)+"..."}var Gu,vu;var Nc=H(()=>{st();Qt();St();ge();Dt();Gu={command:"status",aliases:["st"],describe:"Show status overview of all worktrees",builder:(t)=>t.option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("all",{type:"boolean",alias:"a",describe:"Show worktrees from all configured repos"}),handler:async(t)=>{try{let e;if(t.all){let c=Q(),l=await ct(),a=Ae(c),h=new Set([Bn(l)]),u=[l];for(let d of a){let g=Bn(d);if(!h.has(g))h.add(g),u.push(d)}e=await M.listAll(u)}else e=await M.list();if(e.length===0)console.log("No worktrees found."),process.exit(0);let o=await Promise.all(e.map(async(c)=>{let[l,a,h,u]=await Promise.all([c.branch?M.getAheadBehind(c.branch,c.path):Promise.resolve({ahead:0,behind:0}),M.getLastCommit(c.path),M.getDirtyCount(c.path),Promise.resolve(te(c.path))]);return{...c,aheadBehind:l,lastCommit:a,dirtyCount:h,focus:u}}));if(t.json)console.log(JSON.stringify(o,null,2)),process.exit(0);let n=Bn(process.cwd()),r=t.all&&new Set(o.map((c)=>c.repoName)).size>1,i=o.map((c)=>{let a=(Bn(c.path)===n?"* ":" ")+(c.branch??"(detached)"),h;if(c.isLocked)h="locked";else if(c.dirtyCount>0)h=`${c.dirtyCount} dirty`;else h="clean";let u=[];if(c.aheadBehind.ahead>0)u.push(`+${c.aheadBehind.ahead}`);if(c.aheadBehind.behind>0)u.push(`-${c.aheadBehind.behind}`);let d=u.length>0?u.join(" "):"=",g=c.lastCommit?`${c.lastCommit.relativeDate} ${Hc(c.lastCommit.message,30)}`:"\u2014",x=c.focus&&c.focus.length>0?Hc(c.focus.join(", "),30):"\u2014";return{repo:c.repoName,branch:a,dirty:h,sync:d,lastCommit:g,focus:x}}),s={branch:Math.max(6,...i.map((c)=>c.branch.length)),dirty:Math.max(6,...i.map((c)=>c.dirty.length)),sync:Math.max(4,...i.map((c)=>c.sync.length)),lastCommit:Math.max(11,...i.map((c)=>c.lastCommit.length)),focus:Math.max(5,...i.map((c)=>c.focus.length)),repo:Math.max(4,...i.map((c)=>c.repo.length))};if(r){let c=`${"Repo".padEnd(s.repo)} ${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,l=`${"-".repeat(s.repo)} ${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(l);for(let a of i)console.log(`${a.repo.padEnd(s.repo)} ${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}else{let c=`${"Branch".padEnd(s.branch)} ${"Status".padEnd(s.dirty)} ${"Sync".padEnd(s.sync)} ${"Last Commit".padEnd(s.lastCommit)} ${"Focus".padEnd(s.focus)}`,l=`${"-".repeat(s.branch)} ${"-".repeat(s.dirty)} ${"-".repeat(s.sync)} ${"-".repeat(s.lastCommit)} ${"-".repeat(s.focus)}`;console.log(c),console.log(l);for(let a of i)console.log(`${a.branch.padEnd(s.branch)} ${a.dirty.padEnd(s.dirty)} ${a.sync.padEnd(s.sync)} ${a.lastCommit.padEnd(s.lastCommit)} ${a.focus.padEnd(s.focus)}`)}process.exit(0)}catch(e){if(e instanceof Ht)if(e.stderr.includes("not a git repository"))console.error("Error: not a git repository (or any of the parent directories): .git"),console.error("Run omw from within a git repository.");else console.error(`Git error: ${e.message}`);else console.error(`Error: ${e.message}`);process.exit(1)}}};vu=Gu});var zc={};xt(zc,{default:()=>Ju});import{existsSync as Hu}from"fs";function ku(t){if(t)return t;let e=process.env.VISUAL||process.env.EDITOR;if(e)return e;for(let o of Jc)try{if(Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"}).exitCode===0)return o}catch{continue}return null}var Jc,Nu,Ju;var Uc=H(()=>{st();Dt();Jc=["code","cursor","vim","nvim","emacs","nano","subl","zed","idea","webstorm"];Nu={command:"open [branch-or-path]",describe:"Open a worktree in your editor/IDE",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path (defaults to current worktree)"}).option("editor",{type:"string",alias:"e",describe:"Editor command to use (overrides $VISUAL/$EDITOR)"}).option("list-editors",{type:"boolean",describe:"List detected editors"}),handler:async(t)=>{if(t["list-editors"]){let e=process.env.VISUAL||process.env.EDITOR;if(e)console.log(`$VISUAL/$EDITOR: ${e}`);for(let o of Jc)try{let n=Bun.spawnSync(["which",o],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0){let r=new TextDecoder().decode(n.stdout).trim();console.log(` ${o}: ${r}`)}}catch{}process.exit(0)}try{let e=t["branch-or-path"],o;if(!e)o=process.cwd();else{let i=await ct(),s=await M.list(i);o=Xt(s,e).path}if(!Hu(o))console.error(`Error: worktree path does not exist: ${o}`),process.exit(1);let n=ku(t.editor);if(!n)console.error("Error: no editor detected."),console.error("Set $VISUAL or $EDITOR, or use --editor <command>."),console.error("Detected editors can be listed with: omw open --list-editors"),process.exit(1);console.log(`Opening ${o} with ${n}...`),await Bun.spawn([n,o],{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited,process.exit(0)}catch(e){wt(e)}}},Ju=Nu});var Kc={};xt(Kc,{default:()=>Uu});import{resolve as Vc}from"path";var zu,Uu;var Xc=H(()=>{st();St();Dt();zu={command:"exec <command>",describe:"Run a command in each worktree",builder:(t)=>t.positional("command",{type:"string",describe:"Shell command to execute",demandOption:!0}).option("all",{type:"boolean",alias:"a",describe:"Run across all configured repos"}).option("dirty",{type:"boolean",describe:"Only run in dirty worktrees"}).option("clean",{type:"boolean",describe:"Only run in clean worktrees"}).option("behind",{type:"boolean",describe:"Only run in worktrees behind upstream"}).option("parallel",{type:"boolean",alias:"p",describe:"Run commands in parallel (default: sequential)"}).option("json",{type:"boolean",alias:"j",describe:"Output results as JSON"}),handler:async(t)=>{let e=t.command,o=!!t.parallel,n=!!t.json;try{let r;if(t.all){let a=Q(),h=await ct(),u=Ae(a),d=new Set([Vc(h)]),g=[h];for(let x of u){let m=Vc(x);if(!d.has(m))d.add(m),g.push(x)}r=await M.listAll(g)}else r=await M.list();let i=r.filter((a)=>!a.isMain);if(t.dirty)i=i.filter((a)=>a.isDirty);if(t.clean)i=i.filter((a)=>!a.isDirty);if(t.behind)i=(await Yt(i,10,async(h)=>{if(!h.branch)return{wt:h,behind:!1};let u=await M.getAheadBehind(h.branch,h.path);return{wt:h,behind:u.behind>0}})).filter((h)=>h.behind).map((h)=>h.wt);if(i.length===0)console.log("No matching worktrees found."),process.exit(0);if(!n)console.log(`Running '${e}' in ${i.length} worktree(s)...
146
+ `);let s=async(a)=>{let h=Bun.spawn(["sh","-c",e],{cwd:a.path,stdout:"pipe",stderr:"pipe",env:{...Bun.env,OMW_BRANCH:a.branch??"",OMW_WORKTREE_PATH:a.path,OMW_REPO_PATH:a.repoPath}}),[u,d,g]=await Promise.all([new Response(h.stdout).text(),new Response(h.stderr).text(),h.exited]);return{branch:a.branch??"(detached)",path:a.path,exitCode:g,stdout:u.trim(),stderr:d.trim()}},c;if(o)c=await Yt(i,10,s);else{c=[];for(let a of i)c.push(await s(a))}if(n)console.log(JSON.stringify(c,null,2));else{for(let u of c){let d=u.exitCode===0?"\u2713":"\u2717";if(console.log(`${d} ${u.branch} (exit ${u.exitCode})`),u.stdout)for(let g of u.stdout.split(`
148
147
  `))console.log(` ${g}`);if(u.stderr)for(let g of u.stderr.split(`
149
- `))console.log(` ${g}`);console.log()}let a=c.filter((u)=>u.exitCode===0).length,h=c.length-a;console.log(`Done: ${a} passed, ${h} failed`)}let f=c.some((a)=>a.exitCode!==0);process.exit(f?1:0)}catch(r){wt(r)}}},Au=Lu});var vc={};xt(vc,{default:()=>ju});var Iu,ju;var Uc=N(()=>{ct();Dt();Iu={command:"diff <ref1> [ref2]",describe:"Show diff between two worktrees or branches",builder:(t)=>t.positional("ref1",{type:"string",describe:"First worktree branch or ref",demandOption:!0}).positional("ref2",{type:"string",describe:"Second worktree branch or ref (default: current HEAD)"}).option("stat",{type:"boolean",alias:"s",describe:"Show diffstat summary only"}).option("name-only",{type:"boolean",alias:"n",describe:"Show only names of changed files"}),handler:async(t)=>{let e=t.ref1,o=t.ref2??"HEAD",n=!!t.stat,r=!!t["name-only"];try{let i=await at(),s=await M.list(i),c=(u)=>{return s.find((g)=>g.branch===u)?.branch??u},f=c(e),a=c(o),h=await M.diffBetween(f,a,{stat:n,nameOnly:r},i);if(!h)console.log(`No differences between ${e} and ${o==="HEAD"?"current HEAD":o}`);else console.log(h);process.exit(0)}catch(i){wt(i)}}},ju=Iu});var Vc={};xt(Vc,{default:()=>Tu});var _u,Tu;var Kc=N(()=>{ct();Eo();Dt();_u={command:"pin [branch]",aliases:["unpin"],describe:"Pin or unpin a worktree",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).option("reason",{type:"string",describe:"Reason for pinning"}).option("list",{type:"boolean",describe:"List pinned worktrees"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("unpin",{type:"boolean",describe:"Unpin instead of pinning"}),handler:async(t)=>{try{let e=t,o=await M.list();if(t.list){let c=Or(o).map((d)=>({...d,pin:Uo(d.path)}));if(t.json)console.log(JSON.stringify(c,null,2)),process.exit(0);if(c.length===0)console.log("No pinned worktrees found."),process.exit(0);let f=Math.max(6,...c.map((d)=>(d.branch??"(detached)").length)),a=Math.max(4,...c.map((d)=>d.path.length)),h=Math.max(6,...c.map((d)=>(d.pin?.reason??"\u2014").length)),u=Math.max(9,...c.map((d)=>(d.pin?.pinnedAt??"\u2014").length));console.log(`${"Branch".padEnd(f)} ${"Path".padEnd(a)} ${"Reason".padEnd(h)} ${"Pinned At".padEnd(u)}`),console.log(`${"-".repeat(f)} ${"-".repeat(a)} ${"-".repeat(h)} ${"-".repeat(u)}`);for(let d of c)console.log(`${(d.branch??"(detached)").padEnd(f)} ${d.path.padEnd(a)} ${(d.pin?.reason??"\u2014").padEnd(h)} ${(d.pin?.pinnedAt??"\u2014").padEnd(u)}`);process.exit(0)}let n=t._[0]==="unpin"||!!t.unpin,r=typeof e.branch==="string"?e.branch:typeof t._[1]==="string"?t._[1]:void 0;if(!r)console.error("Error: branch is required"),process.exit(1);let i=o.find((c)=>c.branch===r);if(!i)console.error(`Error: no worktree found for '${r}'`),process.exit(1);if(n){if(!Uo(i.path))console.warn(`Warning: worktree is not pinned: ${i.path}`),process.exit(0);Mr(i.path),console.log(`Unpinned worktree: ${i.path}`),process.exit(0)}if(Uo(i.path))console.warn(`Warning: worktree is already pinned: ${i.path}`),process.exit(0);let s=typeof e.reason==="string"?e.reason:void 0;Rr(i.path,s),console.log(`Pinned worktree: ${i.path}`),process.exit(0)}catch(e){wt(e)}}},Tu=_u});var qc={};xt(qc,{default:()=>Nu});function Gu(t){let e={create:"\x1B[32m",delete:"\x1B[31m",switch:"\x1B[34m",rename:"\x1B[33m",archive:"\x1B[35m",import:"\x1B[36m",reset:"\x1B[0m"};return`${e[t]??e.reset}${t}${e.reset}`}var Hu,Nu;var Xc=N(()=>{Ge();Dt();Hu={command:"log",aliases:["logs"],describe:"Show worktree activity log",builder:(t)=>t.option("limit",{type:"number",default:20,describe:"Show the last N entries"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("clear",{type:"boolean",describe:"Clear the activity log"}),handler:async(t)=>{try{let e=await at();if(t.clear){if(!await Te("Clear activity log? [y/N] "))console.log("Cancelled."),process.exit(0);cc(e),console.log("Activity log cleared."),process.exit(0)}let o=typeof t.limit==="number"?t.limit:20,n=sc(e,{limit:o});if(t.json)console.log(JSON.stringify(n,null,2)),process.exit(0);for(let r of n){let i=Gu(r.event),s=r.branch??"(unknown)",c=r.details?Object.entries(r.details).map(([f,a])=>`${f}=${a}`).join(" "):"";console.log(`[${r.timestamp}] ${i} ${s}${c?` (${c})`:""}`)}process.exit(0)}catch(e){wt(e)}}},Nu=Hu});import{existsSync as Yc,mkdirSync as Ju,readFileSync as ta,writeFileSync as Zc}from"fs";import{homedir as ku}from"os";import{basename as zu,join as Dn}from"path";function vu(t){let e=Go(t),o=Dn(e,"HEAD");if(!Yc(o))return null;let r=ta(o,"utf-8").trim().match(/^ref:\s+(.+)$/);if(!r)return null;return r[1]?.replace(/^refs\/heads\//,"")??null}async function Qc(t,e){return M.exec(t,e)}function ea(){let t=Bun.env.HOME??ku();return Dn(t,".omw","archives")}async function oa(t,e){let o=zu(e),n=await M.getBranchForWorktree(t)??vu(t)??"detached-head",r=n.replaceAll("/","-"),i=new Date().toISOString(),s=i.replaceAll(":","-"),c=Dn(ea(),o);Ju(c,{recursive:!0});let f=Dn(c,`${r}-${s}`),a=`${f}.patch`,h=`${f}.json`;try{let[u,d,g]=await Promise.all([Qc(["diff"],t),Qc(["format-patch","-5","HEAD","--stdout"],t),M.getLastCommit(t)]),x=["# OMW archive",`# repo: ${o}`,`# branch: ${n}`,`# archivedAt: ${i}`,"","# Uncommitted diff",u||"# (no uncommitted changes)","","# Recent commits (git format-patch -5 HEAD --stdout)",d||"# (no recent commits)"].join(`
150
- `);Zc(a,x,"utf-8");let m={branch:n,repo:o,archivedAt:i,patchPath:a,commitHash:g?.hash??"",message:g?.message??""};return Zc(h,JSON.stringify(m,null,2),"utf-8"),m}catch(u){let d=u instanceof Error?u.message:"Unknown archive error";throw new ur(`Failed to archive worktree: ${d}`,n,"archive_failed")}}async function na(t){let e=ea();if(!Yc(e))return[];let o=t?`${t}/*.json`:"**/*.json",n=new Bun.Glob(o),r=[];for await(let i of n.scan({cwd:e,absolute:!0}))try{let s=ta(i,"utf-8");r.push(JSON.parse(s))}catch{}return r.sort((i,s)=>{let c=Date.parse(i.archivedAt);return Date.parse(s.archivedAt)-c})}var ra=N(()=>{ct();Zt();We()});var ia={};xt(ia,{default:()=>Ku});import{basename as Uu}from"path";var Vu,Ku;var sa=N(()=>{ct();Ge();ra();$t();$e();Dt();Vu={command:"archive [branch]",describe:"Archive worktree changes and optionally remove",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name or worktree path"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}).option("keep",{type:"boolean",describe:"Archive without removing the worktree"}).option("list",{type:"boolean",describe:"List all archives"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON (with --list)"}),handler:async(t)=>{let e=t.branch,o=!!t.yes,n=!!t.keep,r=!!t.list,i=!!t.json;try{if(r){let u=await na();if(i)console.log(JSON.stringify(u,null,2));else if(u.length===0)console.log("No archives found.");else{console.log(`Archives:
151
- `);for(let d of u){let g=new Date(d.archivedAt).toLocaleString();console.log(` ${d.repo}/${d.branch}`),console.log(` Date: ${g}`),console.log(` Commit: ${d.commitHash.slice(0,8)} ${d.message}`),console.log(` Patch: ${d.patchPath}`),console.log()}}process.exit(0)}if(!e)console.error("Error: branch name is required (or use --list to view archives)"),process.exit(1);let s=await at(),c=await M.list(s),f=Kt(c,e);if(f.isMain)console.error("Error: cannot archive the main worktree"),process.exit(1);let a=n?"Archive":"Archive and remove";if(!o){if(!await Te(`${a} worktree '${f.branch??Uu(f.path)}'? [y/N] `))console.log("Cancelled."),process.exit(0)}let h=await oa(f.path,s);console.log(`Archived: ${h.patchPath}`);try{qt(s,{timestamp:new Date().toISOString(),event:"archive",branch:h.branch,path:h.patchPath})}catch{}if(!n){let u=Y(),d=Lt(u,s);if(d.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(d.postRemove,{cwd:f.path,env:{OMW_BRANCH:f.branch??"",OMW_WORKTREE_PATH:f.path,OMW_REPO_PATH:s},onOutput:(g)=>console.log(` ${g}`)}).catch((g)=>console.warn(`Warning: postRemove hook failed: ${g.message}`));await M.remove(f.path,{force:!1},s),Mt(),console.log(`Removed worktree: ${f.path}`)}process.exit(0)}catch(s){wt(s)}}},Ku=Vu});var ca={};xt(ca,{default:()=>Yu});import{dirname as qu,basename as Xu,join as Zu}from"path";var Qu,Yu;var aa=N(()=>{ct();Ge();Dt();Qu={command:"rename <old> <new>",describe:"Rename worktree branch",builder:(t)=>t.positional("old",{type:"string",demandOption:!0,describe:"Current branch name"}).positional("new",{type:"string",demandOption:!0,describe:"New branch name"}).option("move-path",{type:"boolean",describe:"Also rename the worktree directory path"}),handler:async(t)=>{let{old:e,new:o}=t,n=!!t["move-path"];try{let r=await at(),i=await M.list(r),s=Kt(i,e);if(s.isMain)console.error("Error: cannot rename the main worktree branch"),process.exit(1);if(i.find((f)=>f.branch===o))console.error(`Error: branch '${o}' already exists`),process.exit(1);if(await M.exec(["branch","-m",e,o],r),Mt(),n){let f=o.replace(/\//g,"-"),a=qu(s.path),h=Xu(s.path),u=e.replace(/\//g,"-"),d=h.replace(u,f),g=Zu(a,d);if(g!==s.path)await M.move(s.path,g,r),Mt(),console.log(`Moved worktree: ${s.path} \u2192 ${g}`)}console.log(`Renamed branch: ${e} \u2192 ${o}`);try{qt(r,{timestamp:new Date().toISOString(),event:"rename",branch:o,details:{oldBranch:e}})}catch{}process.exit(0)}catch(r){wt(r)}}},Yu=Qu});var fa={};xt(fa,{default:()=>np});import{basename as tp,resolve as ep}from"path";var op,np;var la=N(()=>{ct();Zt();$t();$e();op={command:"clone <url> [path]",describe:"Clone a repository and initialize omw config",builder:(t)=>t.positional("url",{type:"string",describe:"Repository URL to clone",demandOption:!0}).positional("path",{type:"string",describe:"Target directory path"}).option("template",{type:"string",alias:"t",describe:"Apply a named template after cloning"}).option("init-config",{type:"boolean",describe:"Initialize omw config after cloning",default:!0}),handler:async(t)=>{let{url:e,template:o}=t,n=t["init-config"],r=t.path;if(!r)try{let i=new URL(e);r=tp(i.pathname).replace(/\.git$/,"")}catch{r=(e.split("/").pop()??e.split(":").pop()??e).replace(/\.git$/,"")}if(!r)console.error("Error: could not determine target directory from URL"),process.exit(1);console.log(`Cloning ${e}...`);try{await M.exec(["clone",e,r])}catch(i){if(i instanceof Gt)console.error(`Error: ${i.stderr||i.message}`);else console.error(`Error: ${i.message}`);process.exit(1)}if(n)try{let i=fe();console.log(` \u2713 Config initialized: ${i}`)}catch(i){console.warn(` \u26A0 Could not initialize config: ${i.message}`)}if(o)try{let i=Y(),s=Cn(i,o);if(!s){let h=Object.keys(i.templates??{});if(console.error(`Error: template '${o}' not found.`),h.length>0)console.error(`Available templates: ${h.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}console.log(` Using template '${o}'`);let c=ep(r),f=Lt(i,c),a=$n(f,s);if(a.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(a.postCreate,{cwd:c,env:{OMW_REPO_PATH:c},onOutput:(h)=>console.log(` ${h}`)}),console.log(" \u2713 Hooks completed");console.log(` \u2713 Template '${o}' applied`)}catch(i){if(i instanceof Co)console.error(`Error: hook timed out: ${i.command}`);else if(i instanceof bo){if(console.error(`Error: hook failed (exit ${i.exitCode}): ${i.command}`),i.stderr)console.error(i.stderr)}else console.error(`Error applying template: ${i.message}`);process.exit(1)}console.log(`
152
- Cloned: ${e} \u2192 ${r}`),process.exit(0)}},np=op});import{existsSync as ha,readFileSync as ua,statSync as Fn}from"fs";import{basename as rp,join as Bn,resolve as Ro}from"path";async function Br(t,e){return M.exec(t,e)}function ip(t){let e=Bn(t,"HEAD");if(!ha(e))return null;let n=ua(e,"utf-8").trim().match(/^ref:\s+refs\/heads\/(.+)$/);return n?n[1]:null}function pa(t){let e=Ro(t),o=Bn(e,".git");if(!Fn(o,{throwIfNoEntry:!1}))throw Error(`Missing .git at ${o}`);return Go(e)}function Lr(t){let e=Ro(t),o=Fn(e,{throwIfNoEntry:!1});if(!o)return{valid:!1,reason:`Path does not exist: ${e}`};if(!o.isDirectory())return{valid:!1,reason:`Path is not a directory: ${e}`};let n=Bn(e,".git"),r=Fn(n,{throwIfNoEntry:!1});if(!r)return{valid:!1,reason:`Target is missing .git: ${e}`};if(r.isDirectory())return{valid:!1,reason:`Target is not a linked git worktree (.git is a directory): ${e}`};if(!r.isFile())return{valid:!1,reason:`Target has invalid .git entry: ${e}`};let i="";try{i=pa(e)}catch{return{valid:!1,reason:`Cannot resolve gitdir from .git file: ${e}`}}if(!Fn(i,{throwIfNoEntry:!1})?.isDirectory())return{valid:!1,reason:`Resolved gitdir does not exist: ${i}`};let c=ip(i);if(!c)return{valid:!1,reason:`Cannot resolve branch name from HEAD: ${e}`};return{valid:!0,branch:c}}async function da(t,e){let o=Ro(t),n=Lr(o);if(!n.valid)throw new _o(`Cannot import worktree: ${n.reason??"invalid target"}`,o,n.reason??"invalid target");let[r,i,s]=await Promise.all([Br(["rev-parse","HEAD"],o),Br(["status","--porcelain"],o),Br(["rev-parse","--git-common-dir"],o)]),c=Ro(o,s),f=c.endsWith("/.git")||c.endsWith("\\.git")?c.slice(0,-5):c,a=rp(f),h=Ro(o)===Ro(f),u=pa(o),d=Bn(u,"locked"),g=ha(d),x=g?ua(d,"utf-8").trim()||void 0:void 0;if(e?.focus&&e.focus.length>0)ho(o,e.focus);if(e?.pin)try{(await Promise.resolve().then(() => (Eo(),zs))).writePin(o)}catch(m){console.warn(`Warning: failed to pin worktree: ${m.message}`)}return{path:o,branch:n.branch??null,head:r,isMain:h,isDirty:i.length>0,isLocked:g,lockReason:x,repoName:a,repoPath:f}}var ma=N(()=>{ct();xe();Zt();We()});var xa={};xt(xa,{default:()=>ap});import{resolve as sp}from"path";var cp,ap;var ga=N(()=>{ma();ct();Ge();Zt();Dt();cp={command:"import <path>",describe:"Adopt a worktree with omw metadata",builder:(t)=>t.positional("path",{type:"string",describe:"Existing worktree directory path",demandOption:!0}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("pin",{type:"boolean",describe:"Pin the worktree"}),handler:async(t)=>{let e=sp(t.path),o=Lr(e);if(!o.valid)console.error(`Error: ${o.reason??"invalid import target"}`),process.exit(1);let r=t.focus?.flatMap((s)=>s.split(/[,\s]+/)).map((s)=>s.trim()).filter(Boolean)??[],i=!!t.pin;try{let s=await da(e,{focus:r,pin:i});Mt();let c=s.branch??o.branch??"unknown",f=s.repoPath??await at();console.log(`Imported worktree: ${c} at ${s.path}`);try{qt(f,{timestamp:new Date().toISOString(),event:"import",branch:s.branch??o.branch??"unknown",path:s.path})}catch{}if(r.length>0)console.log(` Focus: ${r.join(", ")}`);if(i)console.log(" Pinned");process.exit(0)}catch(s){if(s instanceof _o)console.error(`Error: ${s.reason}`);else console.error(`Error: ${s.message}`);process.exit(1)}}},ap=cp});var wa={};xt(wa,{default:()=>up});import{basename as Ln}from"path";async function lp(t,e,o){let[n,r]=await Promise.all([br(e),M.list(t)]);if(o){let i=n.map((s)=>{let c=r.find((a)=>{let h=a.branch??Ln(a.path);return De(h,e)===s.name}),f=c?Vt(c.path):null;return{...s,branch:c?.branch??null,worktreePath:c?.path??null,layout:f?.layout??null}});console.log(JSON.stringify(i,null,2));return}if(n.length===0){console.log("No active omw sessions.");return}console.log(`Active sessions (${n.length}):
153
- `);for(let i of n){let s=r.find((u)=>{let d=u.branch??Ln(u.path);return De(d,e)===i.name}),c=s?Vt(s.path):null,f=i.attached?" (attached)":"",a=c?.layout?` [${c.layout}]`:"",h=s?.branch?` ${s.branch}`:"";console.log(` ${i.name}${h} ${i.windows} windows${a}${f}`)}}async function hp(t,e){let[o,n]=await Promise.all([br(e),M.list(t)]);if(o.length===0){console.log("No active omw sessions.");return}let r=0;for(let i of o){let s=n.find((c)=>{let f=Vt(c.path),a=c.branch??Ln(c.path);return f?.name===i.name||De(a,e)===i.name});if(await wr(i.name),s)xr(s.path);r++,console.log(` \u2713 Killed ${i.name}`)}console.log(`
154
- Killed ${r} session${r!==1?"s":""}.`)}var fp,up;var ba=N(()=>{ct();$t();Fe();Dt();fp={command:"session [branch-or-path]",aliases:["ss"],describe:"Manage tmux sessions for worktrees",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path to open session for"}).option("list",{type:"boolean",alias:"l",describe:"List active omw tmux sessions"}).option("kill",{type:"boolean",alias:"k",describe:"Kill the session for the specified worktree"}).option("kill-all",{type:"boolean",describe:"Kill all omw tmux sessions"}).option("layout",{type:"string",describe:"Use a named layout from config"}).option("json",{type:"boolean",alias:"j",describe:"Output in JSON format"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.list,n=!!t.kill,r=!!t["kill-all"],i=t.layout,s=!!t.json;if(!await po())console.error("Error: tmux is not installed or not in PATH."),console.error("Install tmux to use session management."),process.exit(1);try{let c=await at(),f=Y(),a=Ae(f);if(o)await lp(c,a.prefix,s),process.exit(0);if(r)await hp(c,a.prefix),process.exit(0);if(!e)console.error("Error: specify a branch or worktree path, or use --list."),process.exit(1);let h=await M.list(c),u=Kt(h,e),d=u.branch??Ln(u.path);if(n){if(await xn(d,u.path,a.prefix))console.log(`Killed session for '${d}'`);else console.log(`No active session for '${d}'`);process.exit(0)}let g=Sn(f,i),x=await mn(d,u.path,{layout:g,prefix:a.prefix,attach:!0,layoutName:i??a.defaultLayout});console.log(`Session: ${x}`),process.exit(0)}catch(c){wt(c)}}};up=fp});import{existsSync as Ar,mkdirSync as Ca,writeFileSync as $a}from"fs";import{dirname as Sa,join as Mo}from"path";function pp(t){let e=process.env.HOME||process.env.USERPROFILE||"~";switch(t){case"claude-code":return Mo(e,".claude","skills","omw");case"codex":return Mo(e,".agents","skills","omw");case"opencode":return Mo(e,".config","opencode","skill","omw")}}function dp(t){return Mo(pp(t),"SKILL.md")}function gp(t){return["| Flag | Type | Alias | Description |","|------|------|-------|-------------|",...t.length>0?t.map((o)=>`| ${o.flag} | ${o.type} | ${o.alias} | ${o.description} |`):["| - | - | - | No options |"]].join(`
155
- `)}function wp(){let t=xp.map((o)=>`| \`${o.command}\` | ${o.aliases} | ${o.description} |`),e=Pa.map((o)=>`- [\`omw ${o.command}\`](references/${o.command}.md)`);return["---","name: omw",`description: ${mp}`,"metadata:"," author: getsolaris",' version: "1.0.0"',"---","","# oh-my-worktree (omw)","","## Quick Start","","### Create a feature worktree","","```bash","omw add feature/my-feature --base main","```","","### List and check status","","```bash","omw list","omw status","```","","### Clean up merged worktrees","","```bash","omw clean --dry-run","omw clean --yes","```","","### Run commands across worktrees","","```bash",'omw exec "bun test" --parallel',"```","","### Review a GitHub PR","","```bash","omw add pr-review --pr 42","omw open pr-review","```","","### Use templates","","```bash","# Create worktree with predefined template (hooks, base branch, settings)","omw add feature/new --template frontend","```","","### Tmux session management","","```bash","# Create worktree with tmux session","omw add feature/api --session --layout dev","","# List active sessions","omw session --list","","# Attach to existing session","omw session feature/api","```","","### Shell integration setup","","```bash","# Add to ~/.zshrc or ~/.bashrc",'eval "$(omw shell-init)"',"","# Then switch worktrees with cd","omw switch feature/auth","```","","## Command Overview","","| Command | Aliases | Description |","|---------|---------|-------------|",...t,"","## Monorepo Workflows","","Use focus paths to target packages and trigger matching monorepo hooks.","","```bash","omw add feature/web-auth --focus apps/web,apps/api","omw import /path/to/worktree --focus packages/core --pin","omw list --json","```","","Focus accepts comma-separated values, space-separated values, or repeated --focus flags.","","## Configuration","","- Config path: `~/.config/oh-my-worktree/config.json`","- Use `--json` output flags for scripting and automation","- Environment variables in `omw exec`: `OMW_BRANCH`, `OMW_WORKTREE_PATH`, `OMW_REPO_PATH`","","## Command Reference","","For detailed options and examples for each command:","",...e,"- [`Configuration Schema`](references/config-schema.md)",""].join(`
156
- `)}function bp(){let t=new Map;for(let o of Pa){let n=[`# omw ${o.command}`,"",o.summary,"","## Synopsis","","```",o.synopsis,"```","","## Options","",gp(o.options),"","## Examples","","```bash",`# ${o.examples[0][0]}`,o.examples[0][1],"",`# ${o.examples[1][0]}`,o.examples[1][1],"```","","## Notes","",...o.notes.map((r)=>`- ${r}`),"",...o.configKeys.length>0?["## Configuration","","Related config keys in `~/.config/oh-my-worktree/config.json`:","",...o.configKeys.map((r)=>`- ${r}`),""]:[]];t.set(`${o.command}.md`,n.join(`
157
- `))}let e=Cp();return t.set("config-schema.md",e),t}function Cp(){return["# Configuration Schema","","Config file path: `~/.config/oh-my-worktree/config.json`","","## Minimal Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env", ".env.local"],',' "linkFiles": ["node_modules"],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true'," }","}","```","","## Full Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env"],',' "linkFiles": [],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true,',' "sharedDeps": {',' "strategy": "symlink",',' "paths": ["node_modules"]'," }"," },",' "repos": ['," {",' "path": "/path/to/repo",',' "copyFiles": [".env", ".env.local"],',' "monorepo": {',' "autoDetect": true,',' "hooks": ['," {",' "glob": "apps/*",',' "postCreate": ["bun install"]'," }"," ]"," }"," }"," ],",' "templates": {',' "frontend": {',' "base": "main",',' "copyFiles": [".env"],',' "postCreate": ["bun install", "bun run build"]'," },",' "review": {',' "base": "main",',' "postCreate": ["bun install"]'," }"," },",' "sessions": {',' "enabled": true,',' "autoCreate": false,',' "autoKill": true,',' "prefix": "omw",',' "defaultLayout": "dev",',' "layouts": {',' "dev": {',' "windows": [',' { "name": "editor", "command": "nvim ." },',' { "name": "server", "command": "bun run dev" },',' { "name": "shell" }'," ]"," }"," }"," },",' "lifecycle": {',' "autoCleanMerged": false,',' "staleAfterDays": 30,',' "maxWorktrees": 10'," },",' "theme": "default"',"}","```","","## Key Reference","","### defaults","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `worktreeDir` | string | `~/.omw/worktrees/{repo}-{branch}` | Directory pattern. Supports `{repo}` and `{branch}` variables |","| `copyFiles` | string[] | `[]` | Files to copy from main worktree on creation |","| `linkFiles` | string[] | `[]` | Files to symlink from main worktree on creation |","| `postCreate` | string[] | `[]` | Shell commands to run after worktree creation |","| `postRemove` | string[] | `[]` | Shell commands to run before worktree removal |","| `autoUpstream` | boolean | `false` | Automatically set upstream tracking branch |","| `sharedDeps.strategy` | string | `symlink` | Strategy for sharing deps: `symlink`, `hardlink`, or `copy` |","| `sharedDeps.paths` | string[] | `[]` | Paths to share between worktrees |","","### repos[]","","Per-repository overrides. Same keys as `defaults` plus:","","| Key | Type | Description |","|-----|------|-------------|","| `path` | string | **Required.** Absolute path to the repository |","| `monorepo.autoDetect` | boolean | Auto-detect monorepo tools (pnpm, turbo, nx, lerna) |","| `monorepo.extraPatterns` | string[] | Additional glob patterns for package discovery |","| `monorepo.hooks[]` | object[] | Per-package hooks matched by glob pattern |","| `monorepo.hooks[].glob` | string | Glob to match against focus paths |","| `monorepo.hooks[].copyFiles` | string[] | Package-level files to copy |","| `monorepo.hooks[].linkFiles` | string[] | Package-level files to symlink |","| `monorepo.hooks[].postCreate` | string[] | Package-level post-create hooks |","| `monorepo.hooks[].postRemove` | string[] | Package-level post-remove hooks |","","### templates","","Named presets applied via `omw add --template <name>` or `omw clone --template <name>`.","","| Key | Type | Description |","|-----|------|-------------|","| `base` | string | Default base branch for new worktrees |","| `worktreeDir` | string | Override directory pattern |","| `copyFiles` | string[] | Override files to copy |","| `linkFiles` | string[] | Override files to symlink |","| `postCreate` | string[] | Override post-create hooks |","| `postRemove` | string[] | Override post-remove hooks |","| `autoUpstream` | boolean | Override upstream tracking |","","### sessions","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `enabled` | boolean | `false` | Enable tmux session integration |","| `autoCreate` | boolean | `false` | Auto-create session on `omw add` |","| `autoKill` | boolean | `false` | Auto-kill session on `omw remove` |","| `prefix` | string | `omw` | Prefix for tmux session names |","| `defaultLayout` | string | - | Default layout name |","| `layouts.<name>.windows[]` | object[] | - | Window definitions |","| `layouts.<name>.windows[].name` | string | **Required.** | Window name |","| `layouts.<name>.windows[].command` | string | - | Command to run in window |","","### lifecycle","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `autoCleanMerged` | boolean | `false` | Auto-clean merged worktrees |","| `staleAfterDays` | number | `30` | Days until a worktree is considered stale |","| `maxWorktrees` | number | `10` | Maximum number of worktrees |",""].join(`
158
- `)}function ya(t){let e=dp(t),o=Mo(Sa(e),"references"),n=wp(),r=bp(),i=Sa(e);if(!Ar(i))Ca(i,{recursive:!0});if(!Ar(o))Ca(o,{recursive:!0});let s=Ar(e);$a(e,n,"utf-8");for(let[c,f]of r.entries())$a(Mo(o,c),f,"utf-8");return{filePath:e,referenceDir:o,referenceCount:r.size,platform:t,action:s?"updated":"created"}}var Ir,mp="Git worktree manager. Use when working with git worktrees \u2014 creating, switching, removing, listing, or managing worktrees across repositories. Also use for monorepo focus, tmux sessions, and worktree health checks.",xp,Pa;var Ea=N(()=>{Ir=["claude-code","codex","opencode"];xp=[{command:"add",aliases:"-",description:"Create a new worktree from a branch, template, or PR."},{command:"remove",aliases:"rm",description:"Remove a worktree by branch or path."},{command:"list",aliases:"ls",description:"List worktrees with branch, path, status, and focus."},{command:"switch",aliases:"sw",description:"Print shell cd command for a target worktree."},{command:"status",aliases:"st",description:"Show status summary for worktrees."},{command:"clean",aliases:"-",description:"Clean merged worktrees and optionally report stale ones."},{command:"doctor",aliases:"-",description:"Run worktree health checks and optional auto-fixes."},{command:"exec",aliases:"-",description:"Run commands across non-main worktrees."},{command:"diff",aliases:"-",description:"Compare two refs or worktree branches."},{command:"pin",aliases:"unpin",description:"Pin or unpin worktrees and inspect pin metadata."},{command:"log",aliases:"logs",description:"Read or clear the activity log."},{command:"archive",aliases:"-",description:"Archive worktree changes as patch files."},{command:"rename",aliases:"-",description:"Rename a worktree branch and optionally move its path."},{command:"clone",aliases:"-",description:"Clone a repository and initialize omw setup."},{command:"import",aliases:"-",description:"Import an existing worktree into omw metadata."},{command:"session",aliases:"ss",description:"Manage tmux sessions for worktrees."},{command:"config",aliases:"-",description:"Initialize, inspect, validate, and manage config profiles."},{command:"open",aliases:"-",description:"Open a worktree path in your preferred editor."},{command:"shell-init",aliases:"-",description:"Generate shell integration and completions."},{command:"init",aliases:"-",description:"Initialize config or install/update omw AI agent skill files."}],Pa=[{command:"add",summary:"Create a new worktree from a branch, template, or GitHub PR.",synopsis:"omw add [branch] [path]",options:[{flag:"--create",type:"boolean",alias:"-c",description:"Optional compatibility flag; missing branches are created automatically"},{flag:"--base",type:"string",alias:"-b",description:"Base branch/commit for new branch"},{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--template",type:"string",alias:"-t",description:"Use a named template from config"},{flag:"--pr",type:"number",alias:"-",description:"Create worktree from a GitHub PR number"},{flag:"--session",type:"boolean",alias:"-s",description:"Create a tmux session for this worktree"},{flag:"--layout",type:"string",alias:"-",description:"Session layout name from config"}],examples:[["Create a feature branch worktree","omw add feature/auth --base main"],["Create from PR with session layout","omw add feature/review --pr 123 --session --layout dev"]],notes:["Creates the branch automatically when it does not already exist.","Existing branches are reused as-is; --base only applies when a new branch is created.","Runs copyFiles, linkFiles, sharedDeps, postCreate hooks, monorepo hooks after creation.","Rolls back on hook failure.","Requires gh CLI for --pr.","Supports comma/space separated focus paths."],configKeys:["`defaults.worktreeDir` \u2014 Directory pattern for new worktrees","`defaults.copyFiles` \u2014 Files to copy from main worktree","`defaults.linkFiles` \u2014 Files to symlink from main worktree","`defaults.sharedDeps` \u2014 Shared dependency strategy and paths","`defaults.postCreate` \u2014 Hooks to run after worktree creation","`defaults.autoUpstream` \u2014 Auto-set upstream tracking branch","`templates.*` \u2014 Named template overrides","`sessions.autoCreate` \u2014 Auto-create tmux session on add","`sessions.layouts` \u2014 Tmux session layout definitions"]},{command:"remove",summary:"Remove a worktree by branch name or path.",synopsis:"omw remove <branch-or-path>",options:[{flag:"--force",type:"boolean",alias:"-f",description:"Force removal even with uncommitted changes"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"}],examples:[["Remove a branch worktree","omw remove feature/auth"],["Force remove without prompt","omw remove feature/auth --force --yes"]],notes:["Runs postRemove hooks and monorepo postRemove hooks before removal.","Cannot remove main worktree.","Cannot remove locked worktrees.","Auto-kills tmux session if sessions.autoKill is enabled."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal","`sessions.autoKill` \u2014 Auto-kill tmux session on remove"]},{command:"list",summary:"List worktrees with branch, path, status, and focus details.",synopsis:"omw list",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--porcelain",type:"boolean",alias:"-p",description:"Machine-readable output"},{flag:"--all",type:"boolean",alias:"-a",description:"List worktrees from all configured repos"}],examples:[["Show all worktrees","omw list"],["Get machine-readable output","omw list --porcelain"]],notes:["Shows branch, path, status (clean/dirty/locked), focus paths.","Focus column truncated to 40 chars."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"switch",summary:"Switch shell context to a worktree by branch or path.",synopsis:"omw switch <branch-or-path>",options:[],examples:[["Switch using branch name","omw switch feature/auth"],["Switch using path","omw switch ~/.omw/worktrees/repo-feature-auth"]],notes:["Outputs cd command for shell eval.","Requires shell integration (omw shell-init).","Auto-switches tmux session if sessions.enabled and inside tmux.","Logs switch activity."],configKeys:["`sessions.enabled` \u2014 Enable tmux session switching","`sessions.prefix` \u2014 Tmux session name prefix"]},{command:"status",summary:"Show branch health, sync state, commit info, and focus.",synopsis:"omw status",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--all",type:"boolean",alias:"-a",description:"Show worktrees from all configured repos"}],examples:[["Print status table","omw status"],["Parse status in scripts","omw status --json"]],notes:["Shows branch, dirty count, sync status (ahead/behind), last commit info, focus paths.","Marks current worktree with *."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"clean",summary:"Remove merged worktrees and optionally inspect stale candidates.",synopsis:"omw clean",options:[{flag:"--dry-run",type:"boolean",alias:"-n",description:"Show what would be removed"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation"},{flag:"--stale",type:"boolean",alias:"-",description:"Also show stale worktrees based on lifecycle config"}],examples:[["Preview merged cleanup","omw clean --dry-run"],["Run cleanup without prompts","omw clean --yes"]],notes:["Only removes merged worktrees.","Skips pinned and dirty worktrees.","Runs git worktree prune after cleanup.","--stale uses lifecycle config (staleAfterDays, maxWorktrees)."],configKeys:["`lifecycle.staleAfterDays` \u2014 Days until a worktree is considered stale","`lifecycle.maxWorktrees` \u2014 Maximum allowed worktrees","`lifecycle.autoCleanMerged` \u2014 Auto-clean merged worktrees"]},{command:"doctor",summary:"Run health checks for worktree state and configuration.",synopsis:"omw doctor",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--fix",type:"boolean",alias:"-",description:"Auto-fix issues"}],examples:[["Run health checks","omw doctor"],["Auto-fix detectable issues","omw doctor --fix"]],notes:["Checks: git version (>=2.17), config validity, stale worktrees, orphaned directories, lock status, dirty worktrees.","Auto-fix: prune stale, remove orphans, unlock stale locks.","Exit code 0 if healthy, 1 if warnings/errors."],configKeys:[]},{command:"exec",summary:"Run a shell command across filtered non-main worktrees.",synopsis:"omw exec <command>",options:[{flag:"--all",type:"boolean",alias:"-a",description:"Run across all configured repos"},{flag:"--dirty",type:"boolean",alias:"-",description:"Only run in dirty worktrees"},{flag:"--clean",type:"boolean",alias:"-",description:"Only run in clean worktrees"},{flag:"--behind",type:"boolean",alias:"-",description:"Only run in worktrees behind upstream"},{flag:"--parallel",type:"boolean",alias:"-p",description:"Run commands in parallel"},{flag:"--json",type:"boolean",alias:"-j",description:"Output results as JSON"}],examples:[["Run tests in parallel",'omw exec "bun test" --parallel'],["Pull only behind worktrees",'omw exec "git pull" --behind']],notes:["Runs in non-main worktrees only.","Sets env vars: OMW_BRANCH, OMW_WORKTREE_PATH, OMW_REPO_PATH.","Exit code 1 if any command fails."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"diff",summary:"Diff two refs or worktree branches.",synopsis:"omw diff <ref1> [ref2]",options:[{flag:"--stat",type:"boolean",alias:"-s",description:"Show diffstat summary only"},{flag:"--name-only",type:"boolean",alias:"-n",description:"Show only names of changed files"}],examples:[["Show diffstat only","omw diff feature/a feature/b --stat"],["List changed file names","omw diff feature/a --name-only"]],notes:["ref2 defaults to HEAD.","Resolves worktree branch names to refs automatically."],configKeys:[]},{command:"pin",summary:"Pin or unpin worktrees and inspect pin metadata.",synopsis:"omw pin [branch]",options:[{flag:"--reason",type:"string",alias:"-",description:"Reason for pinning"},{flag:"--list",type:"boolean",alias:"-",description:"List pinned worktrees"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--unpin",type:"boolean",alias:"-",description:"Unpin instead of pinning"}],examples:[["Pin with a reason",'omw pin feature/auth --reason "active sprint"'],["Unpin a branch","omw pin feature/auth --unpin"]],notes:["Pinned worktrees are excluded from omw clean.","Also invokable as omw unpin <branch>.","Pin metadata stored in git internals."],configKeys:[]},{command:"log",summary:"View or clear activity log events.",synopsis:"omw log",options:[{flag:"--limit",type:"number",alias:"-",description:"default 20, Show the last N entries"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--clear",type:"boolean",alias:"-",description:"Clear the activity log"}],examples:[["Show recent entries","omw log --limit 50"],["Clear the log","omw log --clear"]],notes:["Events: create (green), delete (red), switch (blue), rename (yellow), archive (magenta), import (cyan).","Color-coded in terminal."],configKeys:[]},{command:"archive",summary:"Archive worktree changes as patch files before optional removal.",synopsis:"omw archive [branch]",options:[{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"},{flag:"--keep",type:"boolean",alias:"-",description:"Archive without removing the worktree"},{flag:"--list",type:"boolean",alias:"-",description:"List all archives"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON with --list"}],examples:[["Archive and remove","omw archive feature/done --yes"],["List archive records","omw archive --list --json"]],notes:["Archives stored as patch files in ~/.omw/archives/.","Cannot archive main worktree.","Runs postRemove hooks before removal unless --keep."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal"]},{command:"rename",summary:"Rename a worktree branch and optionally move its directory path.",synopsis:"omw rename <old> <new>",options:[{flag:"--move-path",type:"boolean",alias:"-",description:"Also rename the worktree directory path"}],examples:[["Rename a worktree branch","omw rename feature/old feature/new"],["Rename branch and directory","omw rename feature/old feature/new --move-path"]],notes:["Cannot rename main worktree.","Checks for branch name conflicts.","Logs rename activity.","--move-path replaces old branch slug with new one in directory name."],configKeys:[]},{command:"clone",summary:"Clone a repository and optionally apply omw template setup.",synopsis:"omw clone <url> [path]",options:[{flag:"--template",type:"string",alias:"-t",description:"Apply a named template after cloning"},{flag:"--init-config",type:"boolean",alias:"-",description:"default true, Initialize omw config after cloning"}],examples:[["Clone and initialize","omw clone https://github.com/user/repo.git"],["Clone with template and no config init","omw clone https://github.com/user/repo.git --template review --no-init-config"]],notes:["Auto-detects target path from URL.","Runs template postCreate hooks if template specified.","Use --no-init-config to skip config initialization."],configKeys:["`templates.*` \u2014 Named template overrides"]},{command:"import",summary:"Import an existing git worktree into omw metadata.",synopsis:"omw import <path>",options:[{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--pin",type:"boolean",alias:"-",description:"Pin the worktree"}],examples:[["Import a worktree path","omw import /path/to/worktree"],["Import with focus and pin","omw import /path/to/worktree --focus apps/web,apps/api --pin"]],notes:["Validates that path is a valid git worktree.","Logs import activity.","Supports comma/space separated focus paths."],configKeys:[]},{command:"session",summary:"Manage tmux sessions for worktrees.",synopsis:"omw session [branch-or-path]",options:[{flag:"--list",type:"boolean",alias:"-l",description:"List active omw tmux sessions"},{flag:"--kill",type:"boolean",alias:"-k",description:"Kill the session for the specified worktree"},{flag:"--kill-all",type:"boolean",alias:"-",description:"Kill all omw tmux sessions"},{flag:"--layout",type:"string",alias:"-",description:"Use a named layout from config"},{flag:"--json",type:"boolean",alias:"-j",description:"Output in JSON format"}],examples:[["Attach or create a session","omw session feature/auth"],["List sessions as JSON","omw session --list --json"]],notes:["Requires tmux.","Session naming: branch feat/auth-token \u2192 tmux session omw_feat-auth-token.","Supports layout templates with multiple windows."],configKeys:["`sessions.enabled` \u2014 Enable tmux session integration","`sessions.autoCreate` \u2014 Auto-create session on worktree add","`sessions.autoKill` \u2014 Auto-kill session on worktree remove","`sessions.prefix` \u2014 Tmux session name prefix","`sessions.defaultLayout` \u2014 Default layout name","`sessions.layouts` \u2014 Layout definitions with windows"]},{command:"config",summary:"Initialize, inspect, edit, validate, and manage profiles.",synopsis:"omw config",options:[{flag:"--init",type:"boolean",alias:"-",description:"Create default config file"},{flag:"--show",type:"boolean",alias:"-s",description:"Print current config as JSON"},{flag:"--edit",type:"boolean",alias:"-e",description:"Open config in $EDITOR"},{flag:"--path",type:"boolean",alias:"-",description:"Print config file path"},{flag:"--validate",type:"boolean",alias:"-",description:"Validate config against schema"},{flag:"--profiles",type:"boolean",alias:"-",description:"List config profiles"},{flag:"--profile",type:"string",alias:"-",description:"Profile name for activation/deletion"},{flag:"--activate",type:"boolean",alias:"-",description:"Activate the specified profile"},{flag:"--delete",type:"boolean",alias:"-",description:"Delete the specified profile"}],examples:[["Initialize config","omw config --init"],["Activate a profile","omw config --profile work --activate"]],notes:["Config path: ~/.config/oh-my-worktree/config.json.","XDG-compliant."],configKeys:[]},{command:"open",summary:"Open the target or current worktree in an editor.",synopsis:"omw open [branch-or-path]",options:[{flag:"--editor",type:"string",alias:"-e",description:"Editor command to use"},{flag:"--list-editors",type:"boolean",alias:"-",description:"List detected editors"}],examples:[["Open current worktree","omw open"],["Open with specific editor","omw open feature/auth --editor nvim"]],notes:["Auto-detects editors: code, cursor, vim, nvim, emacs, nano, subl, zed, idea, webstorm.","Uses $VISUAL or $EDITOR env vars.","Defaults to current worktree if no branch specified."],configKeys:[]},{command:"shell-init",summary:"Generate shell integration wrappers and completions.",synopsis:"omw shell-init [shell]",options:[{flag:"--completions",type:"string",alias:"-",description:"Generate shell completions: bash, zsh, fish"}],examples:[["Generate shell wrapper","omw shell-init zsh"],["Generate completion script","omw shell-init --completions fish"]],notes:["Shell arg is auto-detected if omitted.","Generates wrapper function for omw switch to work with shell cd.","Supports bash, zsh, fish."],configKeys:[]},{command:"init",summary:"Initialize omw config or install AI agent skill files.",synopsis:"omw init",options:[{flag:"--skill",type:"string",alias:"-s",description:"Install AI agent skill: claude-code, codex, opencode"}],examples:[["Initialize config","omw init"],["Install Claude Code skill","omw init --skill claude-code"],["Install Codex skill","omw init --skill codex"]],notes:["Without --skill, reuses config initialization and creates only config.json.","With --skill, installs or updates SKILL.md + references/ directory.","Idempotent \u2014 running again updates existing files without breaking existing setup."],configKeys:[]}]});var Ra={};xt(Ra,{default:()=>Pp});import{dirname as $p}from"path";var Sp,Pp;var Ma=N(()=>{$t();Ea();Sp={command:"init",describe:"Initialize config or install omw integrations",builder:(t)=>t.option("skill",{type:"string",alias:"s",describe:`Install AI agent skill (${Ir.join(", ")})`,choices:Ir}),handler:async(t)=>{let e=t.skill;try{if(!e){let r=fe();console.log(`\u2713 Initialized config \u2192 ${r}`),process.exit(0)}let o=ya(e),n=o.action==="created"?"Installed":"Updated";console.log(`\u2713 ${n} \u2192 ${$p(o.filePath)}/`),console.log(" SKILL.md"),console.log(` references/ (${o.referenceCount} commands)`),process.exit(0)}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}},Pp=Sp});import"@opentui/solid/preload";import{notStrictEqual as Qa,strictEqual as Ya}from"assert";var Fa={right:Aa,center:Ia};class _r{constructor(t){var e;this.width=t.width,this.wrap=(e=t.wrap)!==null&&e!==void 0?e:!0,this.rows=[]}span(...t){let e=this.div(...t);e.span=!0}resetOutput(){this.rows=[]}div(...t){if(t.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...t)&&typeof t[0]==="string")return this.applyLayoutDSL(t[0]);let e=t.map((o)=>{if(typeof o==="string")return this.colFromString(o);return o});return this.rows.push(e),e}shouldApplyLayoutDSL(...t){return t.length===1&&typeof t[0]==="string"&&/[\t\n]/.test(t[0])}applyLayoutDSL(t){let e=t.split(`
159
- `).map((n)=>n.split("\t")),o=0;return e.forEach((n)=>{if(n.length>1&&It.stringWidth(n[0])>o)o=Math.min(Math.floor(this.width*0.5),It.stringWidth(n[0]))}),e.forEach((n)=>{this.div(...n.map((r,i)=>{return{text:r.trim(),padding:this.measurePadding(r),width:i===0&&n.length>1?o:void 0}}))}),this.rows[this.rows.length-1]}colFromString(t){return{text:t,padding:this.measurePadding(t)}}measurePadding(t){let e=It.stripAnsi(t);return[0,e.match(/\s*$/)[0].length,0,e.match(/^\s*/)[0].length]}toString(){let t=[];return this.rows.forEach((e)=>{this.rowToString(e,t)}),t.filter((e)=>!e.hidden).map((e)=>e.text).join(`
160
- `)}rowToString(t,e){return this.rasterize(t).forEach((o,n)=>{let r="";o.forEach((i,s)=>{let{width:c}=t[s],f=this.negatePadding(t[s]),a=i;if(f>It.stringWidth(i))a+=" ".repeat(f-It.stringWidth(i));if(t[s].align&&t[s].align!=="left"&&this.wrap){let u=Fa[t[s].align];if(a=u(a,f),It.stringWidth(a)<f)a+=" ".repeat((c||0)-It.stringWidth(a)-1)}let h=t[s].padding||[0,0,0,0];if(h[3])r+=" ".repeat(h[3]);if(r+=jr(t[s],a,"| "),r+=a,r+=jr(t[s],a," |"),h[1])r+=" ".repeat(h[1]);if(n===0&&e.length>0)r=this.renderInline(r,e[e.length-1])}),e.push({text:r.replace(/ +$/,""),span:t.span})}),e}renderInline(t,e){let o=t.match(/^ */),n=o?o[0].length:0,r=e.text,i=It.stringWidth(r.trimRight());if(!e.span)return t;if(!this.wrap)return e.hidden=!0,r+t;if(n<i)return t;return e.hidden=!0,r.trimRight()+" ".repeat(n-i)+t.trimLeft()}rasterize(t){let e=[],o=this.columnWidths(t),n;return t.forEach((r,i)=>{if(r.width=o[i],this.wrap)n=It.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
148
+ `))console.log(` ${g}`);console.log()}let a=c.filter((u)=>u.exitCode===0).length,h=c.length-a;console.log(`Done: ${a} passed, ${h} failed`)}let l=c.some((a)=>a.exitCode!==0);process.exit(l?1:0)}catch(r){wt(r)}}},Uu=zu});var qc={};xt(qc,{default:()=>Ku});var Vu,Ku;var Zc=H(()=>{st();Dt();Vu={command:"diff <ref1> [ref2]",describe:"Show diff between two worktrees or branches",builder:(t)=>t.positional("ref1",{type:"string",describe:"First worktree branch or ref",demandOption:!0}).positional("ref2",{type:"string",describe:"Second worktree branch or ref (default: current HEAD)"}).option("stat",{type:"boolean",alias:"s",describe:"Show diffstat summary only"}).option("name-only",{type:"boolean",alias:"n",describe:"Show only names of changed files"}),handler:async(t)=>{let e=t.ref1,o=t.ref2??"HEAD",n=!!t.stat,r=!!t["name-only"];try{let i=await ct(),s=await M.list(i),c=(u)=>{return s.find((g)=>g.branch===u)?.branch??u},l=c(e),a=c(o),h=await M.diffBetween(l,a,{stat:n,nameOnly:r},i);if(!h)console.log(`No differences between ${e} and ${o==="HEAD"?"current HEAD":o}`);else console.log(h);process.exit(0)}catch(i){wt(i)}}},Ku=Vu});var Qc={};xt(Qc,{default:()=>qu});var Xu,qu;var Yc=H(()=>{st();Oo();Dt();Xu={command:"pin [branch]",aliases:["unpin"],describe:"Pin or unpin a worktree",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name"}).option("reason",{type:"string",describe:"Reason for pinning"}).option("list",{type:"boolean",describe:"List pinned worktrees"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("unpin",{type:"boolean",describe:"Unpin instead of pinning"}),handler:async(t)=>{try{let e=t,o=await M.list();if(t.list){let c=Fr(o).map((d)=>({...d,pin:qo(d.path)}));if(t.json)console.log(JSON.stringify(c,null,2)),process.exit(0);if(c.length===0)console.log("No pinned worktrees found."),process.exit(0);let l=Math.max(6,...c.map((d)=>(d.branch??"(detached)").length)),a=Math.max(4,...c.map((d)=>d.path.length)),h=Math.max(6,...c.map((d)=>(d.pin?.reason??"\u2014").length)),u=Math.max(9,...c.map((d)=>(d.pin?.pinnedAt??"\u2014").length));console.log(`${"Branch".padEnd(l)} ${"Path".padEnd(a)} ${"Reason".padEnd(h)} ${"Pinned At".padEnd(u)}`),console.log(`${"-".repeat(l)} ${"-".repeat(a)} ${"-".repeat(h)} ${"-".repeat(u)}`);for(let d of c)console.log(`${(d.branch??"(detached)").padEnd(l)} ${d.path.padEnd(a)} ${(d.pin?.reason??"\u2014").padEnd(h)} ${(d.pin?.pinnedAt??"\u2014").padEnd(u)}`);process.exit(0)}let n=t._[0]==="unpin"||!!t.unpin,r=typeof e.branch==="string"?e.branch:typeof t._[1]==="string"?t._[1]:void 0;if(!r)console.error("Error: branch is required"),process.exit(1);let i=o.find((c)=>c.branch===r);if(!i)console.error(`Error: no worktree found for '${r}'`),process.exit(1);if(n){if(!qo(i.path))console.warn(`Warning: worktree is not pinned: ${i.path}`),process.exit(0);Dr(i.path),console.log(`Unpinned worktree: ${i.path}`),process.exit(0)}if(qo(i.path))console.warn(`Warning: worktree is already pinned: ${i.path}`),process.exit(0);let s=typeof e.reason==="string"?e.reason:void 0;Wr(i.path,s),console.log(`Pinned worktree: ${i.path}`),process.exit(0)}catch(e){wt(e)}}},qu=Xu});var ta={};xt(ta,{default:()=>Yu});function Zu(t){let e={create:"\x1B[32m",delete:"\x1B[31m",switch:"\x1B[34m",rename:"\x1B[33m",archive:"\x1B[35m",import:"\x1B[36m",reset:"\x1B[0m"};return`${e[t]??e.reset}${t}${e.reset}`}var Qu,Yu;var ea=H(()=>{He();Dt();Qu={command:"log",aliases:["logs"],describe:"Show worktree activity log",builder:(t)=>t.option("limit",{type:"number",default:20,describe:"Show the last N entries"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON"}).option("clear",{type:"boolean",describe:"Clear the activity log"}),handler:async(t)=>{try{let e=await ct();if(t.clear){if(!await ve("Clear activity log? [y/N] "))console.log("Cancelled."),process.exit(0);uc(e),console.log("Activity log cleared."),process.exit(0)}let o=typeof t.limit==="number"?t.limit:20,n=hc(e,{limit:o});if(t.json)console.log(JSON.stringify(n,null,2)),process.exit(0);for(let r of n){let i=Zu(r.event),s=r.branch??"(unknown)",c=r.details?Object.entries(r.details).map(([l,a])=>`${l}=${a}`).join(" "):"";console.log(`[${r.timestamp}] ${i} ${s}${c?` (${c})`:""}`)}process.exit(0)}catch(e){wt(e)}}},Yu=Qu});import{existsSync as ra,mkdirSync as tp,readFileSync as ia,writeFileSync as oa}from"fs";import{homedir as ep}from"os";import{basename as op,join as Ln}from"path";function np(t){let e=ko(t),o=Ln(e,"HEAD");if(!ra(o))return null;let r=ia(o,"utf-8").trim().match(/^ref:\s+(.+)$/);if(!r)return null;return r[1]?.replace(/^refs\/heads\//,"")??null}async function na(t,e){return M.exec(t,e)}function sa(){let t=Bun.env.HOME??ep();return Ln(t,".omw","archives")}async function ca(t,e){let o=op(e),n=await M.getBranchForWorktree(t)??np(t)??"detached-head",r=n.replaceAll("/","-"),i=new Date().toISOString(),s=i.replaceAll(":","-"),c=Ln(sa(),o);tp(c,{recursive:!0});let l=Ln(c,`${r}-${s}`),a=`${l}.patch`,h=`${l}.json`;try{let[u,d,g]=await Promise.all([na(["diff"],t),na(["format-patch","-5","HEAD","--stdout"],t),M.getLastCommit(t)]),x=["# OMW archive",`# repo: ${o}`,`# branch: ${n}`,`# archivedAt: ${i}`,"","# Uncommitted diff",u||"# (no uncommitted changes)","","# Recent commits (git format-patch -5 HEAD --stdout)",d||"# (no recent commits)"].join(`
149
+ `);oa(a,x,"utf-8");let m={branch:n,repo:o,archivedAt:i,patchPath:a,commitHash:g?.hash??"",message:g?.message??""};return oa(h,JSON.stringify(m,null,2),"utf-8"),m}catch(u){let d=u instanceof Error?u.message:"Unknown archive error";throw new mr(`Failed to archive worktree: ${d}`,n,"archive_failed")}}async function aa(t){let e=sa();if(!ra(e))return[];let o=t?`${t}/*.json`:"**/*.json",n=new Bun.Glob(o),r=[];for await(let i of n.scan({cwd:e,absolute:!0}))try{let s=ia(i,"utf-8");r.push(JSON.parse(s))}catch{}return r.sort((i,s)=>{let c=Date.parse(i.archivedAt);return Date.parse(s.archivedAt)-c})}var la=H(()=>{st();Qt();Fe()});var fa={};xt(fa,{default:()=>sp});import{basename as rp}from"path";var ip,sp;var ha=H(()=>{st();He();la();St();$e();Dt();ip={command:"archive [branch]",describe:"Archive worktree changes and optionally remove",builder:(t)=>t.positional("branch",{type:"string",describe:"Branch name or worktree path"}).option("yes",{type:"boolean",alias:"y",describe:"Skip confirmation prompt"}).option("keep",{type:"boolean",describe:"Archive without removing the worktree"}).option("list",{type:"boolean",describe:"List all archives"}).option("json",{type:"boolean",alias:"j",describe:"Output as JSON (with --list)"}),handler:async(t)=>{let e=t.branch,o=!!t.yes,n=!!t.keep,r=!!t.list,i=!!t.json;try{if(r){let u=await aa();if(i)console.log(JSON.stringify(u,null,2));else if(u.length===0)console.log("No archives found.");else{console.log(`Archives:
150
+ `);for(let d of u){let g=new Date(d.archivedAt).toLocaleString();console.log(` ${d.repo}/${d.branch}`),console.log(` Date: ${g}`),console.log(` Commit: ${d.commitHash.slice(0,8)} ${d.message}`),console.log(` Patch: ${d.patchPath}`),console.log()}}process.exit(0)}if(!e)console.error("Error: branch name is required (or use --list to view archives)"),process.exit(1);let s=await ct(),c=await M.list(s),l=Xt(c,e);if(l.isMain)console.error("Error: cannot archive the main worktree"),process.exit(1);let a=n?"Archive":"Archive and remove";if(!o){if(!await ve(`${a} worktree '${l.branch??rp(l.path)}'? [y/N] `))console.log("Cancelled."),process.exit(0)}let h=await ca(l.path,s);console.log(`Archived: ${h.patchPath}`);try{qt(s,{timestamp:new Date().toISOString(),event:"archive",branch:h.branch,path:h.patchPath})}catch{}if(!n){let u=Q(),d=Lt(u,s);if(d.postRemove.length>0)console.log("Running postRemove hooks..."),await Wt(d.postRemove,{cwd:l.path,env:{OMW_BRANCH:l.branch??"",OMW_WORKTREE_PATH:l.path,OMW_REPO_PATH:s},onOutput:(g)=>console.log(` ${g}`)}).catch((g)=>console.warn(`Warning: postRemove hook failed: ${g.message}`));await M.remove(l.path,{force:!1},s),Mt(),console.log(`Removed worktree: ${l.path}`)}process.exit(0)}catch(s){wt(s)}}},sp=ip});var ua={};xt(ua,{default:()=>hp});import{dirname as cp,basename as ap,join as lp}from"path";var fp,hp;var pa=H(()=>{st();He();Dt();fp={command:"rename <old> <new>",describe:"Rename worktree branch",builder:(t)=>t.positional("old",{type:"string",demandOption:!0,describe:"Current branch name"}).positional("new",{type:"string",demandOption:!0,describe:"New branch name"}).option("move-path",{type:"boolean",describe:"Also rename the worktree directory path"}),handler:async(t)=>{let{old:e,new:o}=t,n=!!t["move-path"];try{let r=await ct(),i=await M.list(r),s=Xt(i,e);if(s.isMain)console.error("Error: cannot rename the main worktree branch"),process.exit(1);if(i.find((l)=>l.branch===o))console.error(`Error: branch '${o}' already exists`),process.exit(1);if(await M.exec(["branch","-m",e,o],r),Mt(),n){let l=o.replace(/\//g,"-"),a=cp(s.path),h=ap(s.path),u=e.replace(/\//g,"-"),d=h.replace(u,l),g=lp(a,d);if(g!==s.path)await M.move(s.path,g,r),Mt(),console.log(`Moved worktree: ${s.path} \u2192 ${g}`)}console.log(`Renamed branch: ${e} \u2192 ${o}`);try{qt(r,{timestamp:new Date().toISOString(),event:"rename",branch:o,details:{oldBranch:e}})}catch{}process.exit(0)}catch(r){wt(r)}}},hp=fp});var da={};xt(da,{default:()=>mp});import{basename as up,resolve as pp}from"path";var dp,mp;var ma=H(()=>{st();Qt();St();$e();dp={command:"clone <url> [path]",describe:"Clone a repository and initialize omw config",builder:(t)=>t.positional("url",{type:"string",describe:"Repository URL to clone",demandOption:!0}).positional("path",{type:"string",describe:"Target directory path"}).option("template",{type:"string",alias:"t",describe:"Apply a named template after cloning"}).option("init-config",{type:"boolean",describe:"Initialize omw config after cloning",default:!0}),handler:async(t)=>{let{url:e,template:o}=t,n=t["init-config"],r=t.path;if(!r)try{let i=new URL(e);r=up(i.pathname).replace(/\.git$/,"")}catch{r=(e.split("/").pop()??e.split(":").pop()??e).replace(/\.git$/,"")}if(!r)console.error("Error: could not determine target directory from URL"),process.exit(1);console.log(`Cloning ${e}...`);try{await M.exec(["clone",e,r])}catch(i){if(i instanceof Ht)console.error(`Error: ${i.stderr||i.message}`);else console.error(`Error: ${i.message}`);process.exit(1)}if(n)try{let i=ue();console.log(` \u2713 Config initialized: ${i}`)}catch(i){console.warn(` \u26A0 Could not initialize config: ${i.message}`)}if(o)try{let i=Q(),s=En(i,o);if(!s){let h=Object.keys(i.templates??{});if(console.error(`Error: template '${o}' not found.`),h.length>0)console.error(`Available templates: ${h.join(", ")}`);else console.error("No templates configured. Add templates to your config file.");process.exit(1)}console.log(` Using template '${o}'`);let c=pp(r),l=Lt(i,c),a=Rn(l,s);if(a.postCreate.length>0)console.log(" Running postCreate hooks..."),await Wt(a.postCreate,{cwd:c,env:{OMW_REPO_PATH:c},onOutput:(h)=>console.log(` ${h}`)}),console.log(" \u2713 Hooks completed");console.log(` \u2713 Template '${o}' applied`)}catch(i){if(i instanceof Po)console.error(`Error: hook timed out: ${i.command}`);else if(i instanceof $o){if(console.error(`Error: hook failed (exit ${i.exitCode}): ${i.command}`),i.stderr)console.error(i.stderr)}else console.error(`Error applying template: ${i.message}`);process.exit(1)}console.log(`
151
+ Cloned: ${e} \u2192 ${r}`),process.exit(0)}},mp=dp});import{existsSync as xa,readFileSync as ga,statSync as In}from"fs";import{basename as xp,join as An,resolve as Wo}from"path";async function Ar(t,e){return M.exec(t,e)}function gp(t){let e=An(t,"HEAD");if(!xa(e))return null;let n=ga(e,"utf-8").trim().match(/^ref:\s+refs\/heads\/(.+)$/);return n?n[1]:null}function wa(t){let e=Wo(t),o=An(e,".git");if(!In(o,{throwIfNoEntry:!1}))throw Error(`Missing .git at ${o}`);return ko(e)}function jr(t){let e=Wo(t),o=In(e,{throwIfNoEntry:!1});if(!o)return{valid:!1,reason:`Path does not exist: ${e}`};if(!o.isDirectory())return{valid:!1,reason:`Path is not a directory: ${e}`};let n=An(e,".git"),r=In(n,{throwIfNoEntry:!1});if(!r)return{valid:!1,reason:`Target is missing .git: ${e}`};if(r.isDirectory())return{valid:!1,reason:`Target is not a linked git worktree (.git is a directory): ${e}`};if(!r.isFile())return{valid:!1,reason:`Target has invalid .git entry: ${e}`};let i="";try{i=wa(e)}catch{return{valid:!1,reason:`Cannot resolve gitdir from .git file: ${e}`}}if(!In(i,{throwIfNoEntry:!1})?.isDirectory())return{valid:!1,reason:`Resolved gitdir does not exist: ${i}`};let c=gp(i);if(!c)return{valid:!1,reason:`Cannot resolve branch name from HEAD: ${e}`};return{valid:!0,branch:c}}async function ba(t,e){let o=Wo(t),n=jr(o);if(!n.valid)throw new vo(`Cannot import worktree: ${n.reason??"invalid target"}`,o,n.reason??"invalid target");let[r,i,s]=await Promise.all([Ar(["rev-parse","HEAD"],o),Ar(["status","--porcelain"],o),Ar(["rev-parse","--git-common-dir"],o)]),c=Wo(o,s),l=c.endsWith("/.git")||c.endsWith("\\.git")?c.slice(0,-5):c,a=xp(l),h=Wo(o)===Wo(l),u=wa(o),d=An(u,"locked"),g=xa(d),x=g?ga(d,"utf-8").trim()||void 0:void 0;if(e?.focus&&e.focus.length>0)uo(o,e.focus);if(e?.pin)try{(await Promise.resolve().then(() => (Oo(),Xs))).writePin(o)}catch(m){console.warn(`Warning: failed to pin worktree: ${m.message}`)}return{path:o,branch:n.branch??null,head:r,isMain:h,isDirty:i.length>0,isLocked:g,lockReason:x,repoName:a,repoPath:l}}var Ca=H(()=>{st();ge();Qt();Fe()});var Sa={};xt(Sa,{default:()=>Cp});import{resolve as wp}from"path";var bp,Cp;var $a=H(()=>{Ca();st();He();Qt();Dt();bp={command:"import <path>",describe:"Adopt a worktree with omw metadata",builder:(t)=>t.positional("path",{type:"string",describe:"Existing worktree directory path",demandOption:!0}).option("focus",{type:"array",alias:"f",describe:"Focus packages for monorepo (comma or space separated paths)",string:!0}).option("pin",{type:"boolean",describe:"Pin the worktree"}),handler:async(t)=>{let e=wp(t.path),o=jr(e);if(!o.valid)console.error(`Error: ${o.reason??"invalid import target"}`),process.exit(1);let r=t.focus?.flatMap((s)=>s.split(/[,\s]+/)).map((s)=>s.trim()).filter(Boolean)??[],i=!!t.pin;try{let s=await ba(e,{focus:r,pin:i});Mt();let c=s.branch??o.branch??"unknown",l=s.repoPath??await ct();console.log(`Imported worktree: ${c} at ${s.path}`);try{qt(l,{timestamp:new Date().toISOString(),event:"import",branch:s.branch??o.branch??"unknown",path:s.path})}catch{}if(r.length>0)console.log(` Focus: ${r.join(", ")}`);if(i)console.log(" Pinned");process.exit(0)}catch(s){if(s instanceof vo)console.error(`Error: ${s.reason}`);else console.error(`Error: ${s.message}`);process.exit(1)}}},Cp=bp});var Pa={};xt(Pa,{default:()=>yp});import{basename as jn}from"path";async function $p(t,e,o){let[n,r]=await Promise.all([$r(e),M.list(t)]);if(o){let i=n.map((s)=>{let c=r.find((a)=>{let h=a.branch??jn(a.path);return Be(h,e)===s.name}),l=c?Kt(c.path):null;return{...s,branch:c?.branch??null,worktreePath:c?.path??null,layout:l?.layout??null}});console.log(JSON.stringify(i,null,2));return}if(n.length===0){console.log("No active omw sessions.");return}console.log(`Active sessions (${n.length}):
152
+ `);for(let i of n){let s=r.find((u)=>{let d=u.branch??jn(u.path);return Be(d,e)===i.name}),c=s?Kt(s.path):null,l=i.attached?" (attached)":"",a=c?.layout?` [${c.layout}]`:"",h=s?.branch?` ${s.branch}`:"";console.log(` ${i.name}${h} ${i.windows} windows${a}${l}`)}}async function Pp(t,e){let[o,n]=await Promise.all([$r(e),M.list(t)]);if(o.length===0){console.log("No active omw sessions.");return}let r=0;for(let i of o){let s=n.find((c)=>{let l=Kt(c.path),a=c.branch??jn(c.path);return l?.name===i.name||Be(a,e)===i.name});if(await Sr(i.name),s)br(s.path);r++,console.log(` \u2713 Killed ${i.name}`)}console.log(`
153
+ Killed ${r} session${r!==1?"s":""}.`)}var Sp,yp;var ya=H(()=>{st();St();Le();Dt();Sp={command:"session [branch-or-path]",aliases:["ss"],describe:"Manage tmux sessions for worktrees",builder:(t)=>t.positional("branch-or-path",{type:"string",describe:"Branch name or worktree path to open session for"}).option("list",{type:"boolean",alias:"l",describe:"List active omw tmux sessions"}).option("kill",{type:"boolean",alias:"k",describe:"Kill the session for the specified worktree"}).option("kill-all",{type:"boolean",describe:"Kill all omw tmux sessions"}).option("layout",{type:"string",describe:"Use a named layout from config"}).option("json",{type:"boolean",alias:"j",describe:"Output in JSON format"}),handler:async(t)=>{let e=t["branch-or-path"],o=!!t.list,n=!!t.kill,r=!!t["kill-all"],i=t.layout,s=!!t.json;if(!await mo())console.error("Error: tmux is not installed or not in PATH."),console.error("Install tmux to use session management."),process.exit(1);try{let c=await ct(),l=Q(),a=je(l);if(o)await $p(c,a.prefix,s),process.exit(0);if(r)await Pp(c,a.prefix),process.exit(0);if(!e)console.error("Error: specify a branch or worktree path, or use --list."),process.exit(1);let h=await M.list(c),u=Xt(h,e),d=u.branch??jn(u.path);if(n){if(await Cn(d,u.path,a.prefix))console.log(`Killed session for '${d}'`);else console.log(`No active session for '${d}'`);process.exit(0)}let g=Mn(l,i),x=await bn(d,u.path,{layout:g,prefix:a.prefix,attach:!0,layoutName:i??a.defaultLayout});console.log(`Session: ${x}`),process.exit(0)}catch(c){wt(c)}}};yp=Sp});import{existsSync as _r,mkdirSync as Ea,writeFileSync as Ra}from"fs";import{dirname as Ma,join as Do}from"path";function Ep(t){let e=process.env.HOME||process.env.USERPROFILE||"~";switch(t){case"claude-code":return Do(e,".claude","skills","omw");case"codex":return Do(e,".agents","skills","omw");case"opencode":return Do(e,".config","opencode","skill","omw")}}function Rp(t){return Do(Ep(t),"SKILL.md")}function Wp(t){return["| Flag | Type | Alias | Description |","|------|------|-------|-------------|",...t.length>0?t.map((o)=>`| ${o.flag} | ${o.type} | ${o.alias} | ${o.description} |`):["| - | - | - | No options |"]].join(`
154
+ `)}function Dp(){let t=Op.map((o)=>`| \`${o.command}\` | ${o.aliases} | ${o.description} |`),e=Oa.map((o)=>`- [\`omw ${o.command}\`](references/${o.command}.md)`);return["---","name: omw",`description: ${Mp}`,"metadata:"," author: getsolaris",' version: "1.0.0"',"---","","# oh-my-worktree (omw)","","## Quick Start","","### Create a feature worktree","","```bash","omw add feature/my-feature --base main","```","","### List and check status","","```bash","omw list","omw status","```","","### Clean up merged worktrees","","```bash","omw clean --dry-run","omw clean --yes","```","","### Run commands across worktrees","","```bash",'omw exec "bun test" --parallel',"```","","### Review a GitHub PR","","```bash","omw add pr-review --pr 42","omw open pr-review","```","","### Use templates","","```bash","# Create worktree with predefined template (hooks, base branch, settings)","omw add feature/new --template frontend","```","","### Tmux session management","","```bash","# Create worktree with tmux session","omw add feature/api --session --layout dev","","# List active sessions","omw session --list","","# Attach to existing session","omw session feature/api","```","","### Shell integration setup","","```bash","# Add to ~/.zshrc or ~/.bashrc",'eval "$(omw shell-init)"',"","# Then switch worktrees with cd","omw switch feature/auth","```","","## Command Overview","","| Command | Aliases | Description |","|---------|---------|-------------|",...t,"","## Monorepo Workflows","","Use focus paths to target packages and trigger matching monorepo hooks.","","```bash","omw add feature/web-auth --focus apps/web,apps/api","omw import /path/to/worktree --focus packages/core --pin","omw list --json","```","","Focus accepts comma-separated values, space-separated values, or repeated --focus flags.","","## Configuration","","- Config path: `~/.config/oh-my-worktree/config.json`","- Use `--json` output flags for scripting and automation","- Environment variables in `omw exec`: `OMW_BRANCH`, `OMW_WORKTREE_PATH`, `OMW_REPO_PATH`","","## Command Reference","","For detailed options and examples for each command:","",...e,"- [`Configuration Schema`](references/config-schema.md)",""].join(`
155
+ `)}function Fp(){let t=new Map;for(let o of Oa){let n=[`# omw ${o.command}`,"",o.summary,"","## Synopsis","","```",o.synopsis,"```","","## Options","",Wp(o.options),"","## Examples","","```bash",`# ${o.examples[0][0]}`,o.examples[0][1],"",`# ${o.examples[1][0]}`,o.examples[1][1],"```","","## Notes","",...o.notes.map((r)=>`- ${r}`),"",...o.configKeys.length>0?["## Configuration","","Related config keys in `~/.config/oh-my-worktree/config.json`:","",...o.configKeys.map((r)=>`- ${r}`),""]:[]];t.set(`${o.command}.md`,n.join(`
156
+ `))}let e=Bp();return t.set("config-schema.md",e),t}function Bp(){return["# Configuration Schema","","Config file path: `~/.config/oh-my-worktree/config.json`","","## Minimal Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env", ".env.local"],',' "linkFiles": ["node_modules"],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true'," }","}","```","","## Full Example","","```json","{",' "version": 1,',' "defaults": {',' "worktreeDir": "~/.omw/worktrees/{repo}-{branch}",',' "copyFiles": [".env"],',' "linkFiles": [],',' "postCreate": ["bun install"],',' "postRemove": [],',' "autoUpstream": true,',' "sharedDeps": {',' "strategy": "symlink",',' "paths": ["node_modules"]'," }"," },",' "repos": ['," {",' "path": "/path/to/repo",',' "copyFiles": [".env", ".env.local"],',' "monorepo": {',' "autoDetect": true,',' "hooks": ['," {",' "glob": "apps/*",',' "postCreate": ["bun install"]'," }"," ]"," }"," }"," ],",' "templates": {',' "frontend": {',' "base": "main",',' "copyFiles": [".env"],',' "postCreate": ["bun install", "bun run build"]'," },",' "review": {',' "base": "main",',' "postCreate": ["bun install"]'," }"," },",' "sessions": {',' "enabled": true,',' "autoCreate": false,',' "autoKill": true,',' "prefix": "omw",',' "defaultLayout": "dev",',' "layouts": {',' "dev": {',' "windows": [',' { "name": "editor", "command": "nvim ." },',' { "name": "server", "command": "bun run dev" },',' { "name": "shell" }'," ]"," }"," }"," },",' "lifecycle": {',' "autoCleanMerged": false,',' "staleAfterDays": 30,',' "maxWorktrees": 10'," },",' "theme": "default"',"}","```","","## Key Reference","","### defaults","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `worktreeDir` | string | `~/.omw/worktrees/{repo}-{branch}` | Directory pattern. Supports `{repo}` and `{branch}` variables |","| `copyFiles` | string[] | `[]` | Files to copy from main worktree on creation |","| `linkFiles` | string[] | `[]` | Files to symlink from main worktree on creation |","| `postCreate` | string[] | `[]` | Shell commands to run after worktree creation |","| `postRemove` | string[] | `[]` | Shell commands to run before worktree removal |","| `autoUpstream` | boolean | `false` | Automatically set upstream tracking branch |","| `sharedDeps.strategy` | string | `symlink` | Strategy for sharing deps: `symlink`, `hardlink`, or `copy` |","| `sharedDeps.paths` | string[] | `[]` | Paths to share between worktrees |","","### repos[]","","Per-repository overrides. Same keys as `defaults` plus:","","| Key | Type | Description |","|-----|------|-------------|","| `path` | string | **Required.** Absolute path to the repository |","| `monorepo.autoDetect` | boolean | Auto-detect monorepo tools (pnpm, turbo, nx, lerna) |","| `monorepo.extraPatterns` | string[] | Additional glob patterns for package discovery |","| `monorepo.hooks[]` | object[] | Per-package hooks matched by glob pattern |","| `monorepo.hooks[].glob` | string | Glob to match against focus paths |","| `monorepo.hooks[].copyFiles` | string[] | Package-level files to copy |","| `monorepo.hooks[].linkFiles` | string[] | Package-level files to symlink |","| `monorepo.hooks[].postCreate` | string[] | Package-level post-create hooks |","| `monorepo.hooks[].postRemove` | string[] | Package-level post-remove hooks |","","### templates","","Named presets applied via `omw add --template <name>` or `omw clone --template <name>`.","","| Key | Type | Description |","|-----|------|-------------|","| `base` | string | Default base branch for new worktrees |","| `worktreeDir` | string | Override directory pattern |","| `copyFiles` | string[] | Override files to copy |","| `linkFiles` | string[] | Override files to symlink |","| `postCreate` | string[] | Override post-create hooks |","| `postRemove` | string[] | Override post-remove hooks |","| `autoUpstream` | boolean | Override upstream tracking |","","### sessions","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `enabled` | boolean | `false` | Enable tmux session integration |","| `autoCreate` | boolean | `false` | Auto-create session on `omw add` |","| `autoKill` | boolean | `false` | Auto-kill session on `omw remove` |","| `prefix` | string | `omw` | Prefix for tmux session names |","| `defaultLayout` | string | - | Default layout name |","| `layouts.<name>.windows[]` | object[] | - | Window definitions |","| `layouts.<name>.windows[].name` | string | **Required.** | Window name |","| `layouts.<name>.windows[].command` | string | - | Command to run in window |","","### lifecycle","","| Key | Type | Default | Description |","|-----|------|---------|-------------|","| `autoCleanMerged` | boolean | `false` | Auto-clean merged worktrees |","| `staleAfterDays` | number | `30` | Days until a worktree is considered stale |","| `maxWorktrees` | number | `10` | Maximum number of worktrees |",""].join(`
157
+ `)}function Wa(t){let e=Rp(t),o=Do(Ma(e),"references"),n=Dp(),r=Fp(),i=Ma(e);if(!_r(i))Ea(i,{recursive:!0});if(!_r(o))Ea(o,{recursive:!0});let s=_r(e);Ra(e,n,"utf-8");for(let[c,l]of r.entries())Ra(Do(o,c),l,"utf-8");return{filePath:e,referenceDir:o,referenceCount:r.size,platform:t,action:s?"updated":"created"}}var Tr,Mp="Git worktree manager. Use when working with git worktrees \u2014 creating, switching, removing, listing, or managing worktrees across repositories. Also use for monorepo focus, tmux sessions, and worktree health checks.",Op,Oa;var Da=H(()=>{Tr=["claude-code","codex","opencode"];Op=[{command:"add",aliases:"-",description:"Create a new worktree from a branch, template, or PR."},{command:"remove",aliases:"rm",description:"Remove a worktree by branch or path."},{command:"list",aliases:"ls",description:"List worktrees with branch, path, status, and focus."},{command:"switch",aliases:"sw",description:"Print shell cd command for a target worktree."},{command:"status",aliases:"st",description:"Show status summary for worktrees."},{command:"clean",aliases:"-",description:"Clean merged worktrees and optionally report stale ones."},{command:"doctor",aliases:"-",description:"Run worktree health checks and optional auto-fixes."},{command:"exec",aliases:"-",description:"Run commands across non-main worktrees."},{command:"diff",aliases:"-",description:"Compare two refs or worktree branches."},{command:"pin",aliases:"unpin",description:"Pin or unpin worktrees and inspect pin metadata."},{command:"log",aliases:"logs",description:"Read or clear the activity log."},{command:"archive",aliases:"-",description:"Archive worktree changes as patch files."},{command:"rename",aliases:"-",description:"Rename a worktree branch and optionally move its path."},{command:"clone",aliases:"-",description:"Clone a repository and initialize omw setup."},{command:"import",aliases:"-",description:"Import an existing worktree into omw metadata."},{command:"session",aliases:"ss",description:"Manage tmux sessions for worktrees."},{command:"config",aliases:"-",description:"Initialize, inspect, validate, and manage config profiles."},{command:"open",aliases:"-",description:"Open a worktree path in your preferred editor."},{command:"shell-init",aliases:"-",description:"Generate shell integration and completions."},{command:"init",aliases:"-",description:"Initialize config or install/update omw AI agent skill files."}],Oa=[{command:"add",summary:"Create a new worktree from a branch, template, or GitHub PR.",synopsis:"omw add [branch] [path]",options:[{flag:"--create",type:"boolean",alias:"-c",description:"Optional compatibility flag; missing branches are created automatically"},{flag:"--base",type:"string",alias:"-b",description:"Base branch/commit for new branch"},{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--template",type:"string",alias:"-t",description:"Use a named template from config"},{flag:"--pr",type:"number",alias:"-",description:"Create worktree from a GitHub PR number"},{flag:"--session",type:"boolean",alias:"-s",description:"Create a tmux session for this worktree"},{flag:"--layout",type:"string",alias:"-",description:"Session layout name from config"}],examples:[["Create a feature branch worktree","omw add feature/auth --base main"],["Create from PR with session layout","omw add feature/review --pr 123 --session --layout dev"]],notes:["Creates the branch automatically when it does not already exist.","Existing branches are reused as-is; --base only applies when a new branch is created.","Runs copyFiles, linkFiles, sharedDeps, postCreate hooks, monorepo hooks after creation.","Rolls back on hook failure.","Requires gh CLI for --pr.","Supports comma/space separated focus paths."],configKeys:["`defaults.worktreeDir` \u2014 Directory pattern for new worktrees","`defaults.copyFiles` \u2014 Files to copy from main worktree","`defaults.linkFiles` \u2014 Files to symlink from main worktree","`defaults.sharedDeps` \u2014 Shared dependency strategy and paths","`defaults.postCreate` \u2014 Hooks to run after worktree creation","`defaults.autoUpstream` \u2014 Auto-set upstream tracking branch","`templates.*` \u2014 Named template overrides","`sessions.autoCreate` \u2014 Auto-create tmux session on add","`sessions.layouts` \u2014 Tmux session layout definitions"]},{command:"remove",summary:"Remove a worktree by branch name or path.",synopsis:"omw remove <branch-or-path>",options:[{flag:"--force",type:"boolean",alias:"-f",description:"Force removal even with uncommitted changes"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"}],examples:[["Remove a branch worktree","omw remove feature/auth"],["Force remove without prompt","omw remove feature/auth --force --yes"]],notes:["Runs postRemove hooks and monorepo postRemove hooks before removal.","Cannot remove main worktree.","Cannot remove locked worktrees.","Auto-kills tmux session if sessions.autoKill is enabled."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal","`sessions.autoKill` \u2014 Auto-kill tmux session on remove"]},{command:"list",summary:"List worktrees with branch, path, status, and focus details.",synopsis:"omw list",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--porcelain",type:"boolean",alias:"-p",description:"Machine-readable output"},{flag:"--all",type:"boolean",alias:"-a",description:"List worktrees from all configured repos"}],examples:[["Show all worktrees","omw list"],["Get machine-readable output","omw list --porcelain"]],notes:["Shows branch, path, status (clean/dirty/locked), focus paths.","Focus column truncated to 40 chars."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"switch",summary:"Switch shell context to a worktree by branch or path.",synopsis:"omw switch <branch-or-path>",options:[],examples:[["Switch using branch name","omw switch feature/auth"],["Switch using path","omw switch ~/.omw/worktrees/repo-feature-auth"]],notes:["Outputs cd command for shell eval.","Requires shell integration (omw shell-init).","Auto-switches tmux session if sessions.enabled and inside tmux.","Logs switch activity."],configKeys:["`sessions.enabled` \u2014 Enable tmux session switching","`sessions.prefix` \u2014 Tmux session name prefix"]},{command:"status",summary:"Show branch health, sync state, commit info, and focus.",synopsis:"omw status",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--all",type:"boolean",alias:"-a",description:"Show worktrees from all configured repos"}],examples:[["Print status table","omw status"],["Parse status in scripts","omw status --json"]],notes:["Shows branch, dirty count, sync status (ahead/behind), last commit info, focus paths.","Marks current worktree with *."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"clean",summary:"Remove merged worktrees and optionally inspect stale candidates.",synopsis:"omw clean",options:[{flag:"--dry-run",type:"boolean",alias:"-n",description:"Show what would be removed"},{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation"},{flag:"--stale",type:"boolean",alias:"-",description:"Also show stale worktrees based on lifecycle config"}],examples:[["Preview merged cleanup","omw clean --dry-run"],["Run cleanup without prompts","omw clean --yes"]],notes:["Only removes merged worktrees.","Skips pinned and dirty worktrees.","Runs git worktree prune after cleanup.","--stale uses lifecycle config (staleAfterDays, maxWorktrees)."],configKeys:["`lifecycle.staleAfterDays` \u2014 Days until a worktree is considered stale","`lifecycle.maxWorktrees` \u2014 Maximum allowed worktrees","`lifecycle.autoCleanMerged` \u2014 Auto-clean merged worktrees"]},{command:"doctor",summary:"Run health checks for worktree state and configuration.",synopsis:"omw doctor",options:[{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--fix",type:"boolean",alias:"-",description:"Auto-fix issues"}],examples:[["Run health checks","omw doctor"],["Auto-fix detectable issues","omw doctor --fix"]],notes:["Checks: git version (>=2.17), config validity, stale worktrees, orphaned directories, lock status, dirty worktrees.","Auto-fix: prune stale, remove orphans, unlock stale locks.","Exit code 0 if healthy, 1 if warnings/errors."],configKeys:[]},{command:"exec",summary:"Run a shell command across filtered non-main worktrees.",synopsis:"omw exec <command>",options:[{flag:"--all",type:"boolean",alias:"-a",description:"Run across all configured repos"},{flag:"--dirty",type:"boolean",alias:"-",description:"Only run in dirty worktrees"},{flag:"--clean",type:"boolean",alias:"-",description:"Only run in clean worktrees"},{flag:"--behind",type:"boolean",alias:"-",description:"Only run in worktrees behind upstream"},{flag:"--parallel",type:"boolean",alias:"-p",description:"Run commands in parallel"},{flag:"--json",type:"boolean",alias:"-j",description:"Output results as JSON"}],examples:[["Run tests in parallel",'omw exec "bun test" --parallel'],["Pull only behind worktrees",'omw exec "git pull" --behind']],notes:["Runs in non-main worktrees only.","Sets env vars: OMW_BRANCH, OMW_WORKTREE_PATH, OMW_REPO_PATH.","Exit code 1 if any command fails."],configKeys:["`repos[].path` \u2014 Repository paths for --all flag"]},{command:"diff",summary:"Diff two refs or worktree branches.",synopsis:"omw diff <ref1> [ref2]",options:[{flag:"--stat",type:"boolean",alias:"-s",description:"Show diffstat summary only"},{flag:"--name-only",type:"boolean",alias:"-n",description:"Show only names of changed files"}],examples:[["Show diffstat only","omw diff feature/a feature/b --stat"],["List changed file names","omw diff feature/a --name-only"]],notes:["ref2 defaults to HEAD.","Resolves worktree branch names to refs automatically."],configKeys:[]},{command:"pin",summary:"Pin or unpin worktrees and inspect pin metadata.",synopsis:"omw pin [branch]",options:[{flag:"--reason",type:"string",alias:"-",description:"Reason for pinning"},{flag:"--list",type:"boolean",alias:"-",description:"List pinned worktrees"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--unpin",type:"boolean",alias:"-",description:"Unpin instead of pinning"}],examples:[["Pin with a reason",'omw pin feature/auth --reason "active sprint"'],["Unpin a branch","omw pin feature/auth --unpin"]],notes:["Pinned worktrees are excluded from omw clean.","Also invokable as omw unpin <branch>.","Pin metadata stored in git internals."],configKeys:[]},{command:"log",summary:"View or clear activity log events.",synopsis:"omw log",options:[{flag:"--limit",type:"number",alias:"-",description:"default 20, Show the last N entries"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON"},{flag:"--clear",type:"boolean",alias:"-",description:"Clear the activity log"}],examples:[["Show recent entries","omw log --limit 50"],["Clear the log","omw log --clear"]],notes:["Events: create (green), delete (red), switch (blue), rename (yellow), archive (magenta), import (cyan).","Color-coded in terminal."],configKeys:[]},{command:"archive",summary:"Archive worktree changes as patch files before optional removal.",synopsis:"omw archive [branch]",options:[{flag:"--yes",type:"boolean",alias:"-y",description:"Skip confirmation prompt"},{flag:"--keep",type:"boolean",alias:"-",description:"Archive without removing the worktree"},{flag:"--list",type:"boolean",alias:"-",description:"List all archives"},{flag:"--json",type:"boolean",alias:"-j",description:"Output as JSON with --list"}],examples:[["Archive and remove","omw archive feature/done --yes"],["List archive records","omw archive --list --json"]],notes:["Archives stored as patch files in ~/.omw/archives/.","Cannot archive main worktree.","Runs postRemove hooks before removal unless --keep."],configKeys:["`defaults.postRemove` \u2014 Hooks to run before worktree removal"]},{command:"rename",summary:"Rename a worktree branch and optionally move its directory path.",synopsis:"omw rename <old> <new>",options:[{flag:"--move-path",type:"boolean",alias:"-",description:"Also rename the worktree directory path"}],examples:[["Rename a worktree branch","omw rename feature/old feature/new"],["Rename branch and directory","omw rename feature/old feature/new --move-path"]],notes:["Cannot rename main worktree.","Checks for branch name conflicts.","Logs rename activity.","--move-path replaces old branch slug with new one in directory name."],configKeys:[]},{command:"clone",summary:"Clone a repository and optionally apply omw template setup.",synopsis:"omw clone <url> [path]",options:[{flag:"--template",type:"string",alias:"-t",description:"Apply a named template after cloning"},{flag:"--init-config",type:"boolean",alias:"-",description:"default true, Initialize omw config after cloning"}],examples:[["Clone and initialize","omw clone https://github.com/user/repo.git"],["Clone with template and no config init","omw clone https://github.com/user/repo.git --template review --no-init-config"]],notes:["Auto-detects target path from URL.","Runs template postCreate hooks if template specified.","Use --no-init-config to skip config initialization."],configKeys:["`templates.*` \u2014 Named template overrides"]},{command:"import",summary:"Import an existing git worktree into omw metadata.",synopsis:"omw import <path>",options:[{flag:"--focus",type:"array",alias:"-f",description:"Focus packages for monorepo"},{flag:"--pin",type:"boolean",alias:"-",description:"Pin the worktree"}],examples:[["Import a worktree path","omw import /path/to/worktree"],["Import with focus and pin","omw import /path/to/worktree --focus apps/web,apps/api --pin"]],notes:["Validates that path is a valid git worktree.","Logs import activity.","Supports comma/space separated focus paths."],configKeys:[]},{command:"session",summary:"Manage tmux sessions for worktrees.",synopsis:"omw session [branch-or-path]",options:[{flag:"--list",type:"boolean",alias:"-l",description:"List active omw tmux sessions"},{flag:"--kill",type:"boolean",alias:"-k",description:"Kill the session for the specified worktree"},{flag:"--kill-all",type:"boolean",alias:"-",description:"Kill all omw tmux sessions"},{flag:"--layout",type:"string",alias:"-",description:"Use a named layout from config"},{flag:"--json",type:"boolean",alias:"-j",description:"Output in JSON format"}],examples:[["Attach or create a session","omw session feature/auth"],["List sessions as JSON","omw session --list --json"]],notes:["Requires tmux.","Session naming: branch feat/auth-token \u2192 tmux session omw_feat-auth-token.","Supports layout templates with multiple windows."],configKeys:["`sessions.enabled` \u2014 Enable tmux session integration","`sessions.autoCreate` \u2014 Auto-create session on worktree add","`sessions.autoKill` \u2014 Auto-kill session on worktree remove","`sessions.prefix` \u2014 Tmux session name prefix","`sessions.defaultLayout` \u2014 Default layout name","`sessions.layouts` \u2014 Layout definitions with windows"]},{command:"config",summary:"Initialize, inspect, edit, validate, and manage profiles.",synopsis:"omw config",options:[{flag:"--init",type:"boolean",alias:"-",description:"Create default config file"},{flag:"--show",type:"boolean",alias:"-s",description:"Print current config as JSON"},{flag:"--edit",type:"boolean",alias:"-e",description:"Open config in $EDITOR"},{flag:"--path",type:"boolean",alias:"-",description:"Print config file path"},{flag:"--validate",type:"boolean",alias:"-",description:"Validate config against schema"},{flag:"--profiles",type:"boolean",alias:"-",description:"List config profiles"},{flag:"--profile",type:"string",alias:"-",description:"Profile name for activation/deletion"},{flag:"--activate",type:"boolean",alias:"-",description:"Activate the specified profile"},{flag:"--delete",type:"boolean",alias:"-",description:"Delete the specified profile"}],examples:[["Initialize config","omw config --init"],["Activate a profile","omw config --profile work --activate"]],notes:["Config path: ~/.config/oh-my-worktree/config.json.","XDG-compliant."],configKeys:[]},{command:"open",summary:"Open the target or current worktree in an editor.",synopsis:"omw open [branch-or-path]",options:[{flag:"--editor",type:"string",alias:"-e",description:"Editor command to use"},{flag:"--list-editors",type:"boolean",alias:"-",description:"List detected editors"}],examples:[["Open current worktree","omw open"],["Open with specific editor","omw open feature/auth --editor nvim"]],notes:["Auto-detects editors: code, cursor, vim, nvim, emacs, nano, subl, zed, idea, webstorm.","Uses $VISUAL or $EDITOR env vars.","Defaults to current worktree if no branch specified."],configKeys:[]},{command:"shell-init",summary:"Generate shell integration wrappers and completions.",synopsis:"omw shell-init [shell]",options:[{flag:"--completions",type:"string",alias:"-",description:"Generate shell completions: bash, zsh, fish"}],examples:[["Generate shell wrapper","omw shell-init zsh"],["Generate completion script","omw shell-init --completions fish"]],notes:["Shell arg is auto-detected if omitted.","Generates wrapper function for omw switch to work with shell cd.","Supports bash, zsh, fish."],configKeys:[]},{command:"init",summary:"Initialize omw config or install AI agent skill files.",synopsis:"omw init",options:[{flag:"--skill",type:"string",alias:"-s",description:"Install AI agent skill: claude-code, codex, opencode"}],examples:[["Initialize config","omw init"],["Install Claude Code skill","omw init --skill claude-code"],["Install Codex skill","omw init --skill codex"]],notes:["Without --skill, reuses config initialization and creates only config.json.","With --skill, installs or updates SKILL.md + references/ directory.","Idempotent \u2014 running again updates existing files without breaking existing setup."],configKeys:[]}]});var Fa={};xt(Fa,{default:()=>Ap});import{dirname as Lp}from"path";var Ip,Ap;var Ba=H(()=>{St();Da();Ip={command:"init",describe:"Initialize config or install omw integrations",builder:(t)=>t.option("skill",{type:"string",alias:"s",describe:`Install AI agent skill (${Tr.join(", ")})`,choices:Tr}),handler:async(t)=>{let e=t.skill;try{if(!e){let r=ue();console.log(`\u2713 Initialized config \u2192 ${r}`),process.exit(0)}let o=Wa(e),n=o.action==="created"?"Installed":"Updated";console.log(`\u2713 ${n} \u2192 ${Lp(o.filePath)}/`),console.log(" SKILL.md"),console.log(` references/ (${o.referenceCount} commands)`),process.exit(0)}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}},Ap=Ip});import"@opentui/solid/preload";import{notStrictEqual as rl,strictEqual as il}from"assert";var _a={right:va,center:Ha};class Hr{constructor(t){var e;this.width=t.width,this.wrap=(e=t.wrap)!==null&&e!==void 0?e:!0,this.rows=[]}span(...t){let e=this.div(...t);e.span=!0}resetOutput(){this.rows=[]}div(...t){if(t.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...t)&&typeof t[0]==="string")return this.applyLayoutDSL(t[0]);let e=t.map((o)=>{if(typeof o==="string")return this.colFromString(o);return o});return this.rows.push(e),e}shouldApplyLayoutDSL(...t){return t.length===1&&typeof t[0]==="string"&&/[\t\n]/.test(t[0])}applyLayoutDSL(t){let e=t.split(`
158
+ `).map((n)=>n.split("\t")),o=0;return e.forEach((n)=>{if(n.length>1&&_t.stringWidth(n[0])>o)o=Math.min(Math.floor(this.width*0.5),_t.stringWidth(n[0]))}),e.forEach((n)=>{this.div(...n.map((r,i)=>{return{text:r.trim(),padding:this.measurePadding(r),width:i===0&&n.length>1?o:void 0}}))}),this.rows[this.rows.length-1]}colFromString(t){return{text:t,padding:this.measurePadding(t)}}measurePadding(t){let e=_t.stripAnsi(t);return[0,e.match(/\s*$/)[0].length,0,e.match(/^\s*/)[0].length]}toString(){let t=[];return this.rows.forEach((e)=>{this.rowToString(e,t)}),t.filter((e)=>!e.hidden).map((e)=>e.text).join(`
159
+ `)}rowToString(t,e){return this.rasterize(t).forEach((o,n)=>{let r="";o.forEach((i,s)=>{let{width:c}=t[s],l=this.negatePadding(t[s]),a=i;if(l>_t.stringWidth(i))a+=" ".repeat(l-_t.stringWidth(i));if(t[s].align&&t[s].align!=="left"&&this.wrap){let u=_a[t[s].align];if(a=u(a,l),_t.stringWidth(a)<l)a+=" ".repeat((c||0)-_t.stringWidth(a)-1)}let h=t[s].padding||[0,0,0,0];if(h[3])r+=" ".repeat(h[3]);if(r+=vr(t[s],a,"| "),r+=a,r+=vr(t[s],a," |"),h[1])r+=" ".repeat(h[1]);if(n===0&&e.length>0)r=this.renderInline(r,e[e.length-1])}),e.push({text:r.replace(/ +$/,""),span:t.span})}),e}renderInline(t,e){let o=t.match(/^ */),n=o?o[0].length:0,r=e.text,i=_t.stringWidth(r.trimRight());if(!e.span)return t;if(!this.wrap)return e.hidden=!0,r+t;if(n<i)return t;return e.hidden=!0,r.trimRight()+" ".repeat(n-i)+t.trimLeft()}rasterize(t){let e=[],o=this.columnWidths(t),n;return t.forEach((r,i)=>{if(r.width=o[i],this.wrap)n=_t.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
161
160
  `);else n=r.text.split(`
162
- `);if(r.border)n.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),n.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)n.unshift(...Array(r.padding[0]||0).fill("")),n.push(...Array(r.padding[2]||0).fill(""));n.forEach((s,c)=>{if(!e[c])e.push([]);let f=e[c];for(let a=0;a<i;a++)if(f[a]===void 0)f.push("");f.push(s)})}),e}negatePadding(t){let e=t.width||0;if(t.padding)e-=(t.padding[3]||0)+(t.padding[1]||0);if(t.border)e-=4;return e}columnWidths(t){if(!this.wrap)return t.map((i)=>{return i.width||It.stringWidth(i.text)});let e=t.length,o=this.width,n=t.map((i)=>{if(i.width)return e--,o-=i.width,i.width;return}),r=e?Math.floor(o/e):0;return n.map((i,s)=>{if(i===void 0)return Math.max(r,Ba(t[s]));return i})}}function jr(t,e,o){if(t.border){if(/[.']-+[.']/.test(e))return"";if(e.trim().length!==0)return o;return" "}return""}function Ba(t){let e=t.padding||[],o=1+(e[3]||0)+(e[1]||0);if(t.border)return o+4;return o}function La(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Aa(t,e){t=t.trim();let o=It.stringWidth(t);if(o<e)return" ".repeat(e-o)+t;return t}function Ia(t,e){t=t.trim();let o=It.stringWidth(t);if(o>=e)return t;return" ".repeat(e-o>>1)+t}var It;function Tr(t,e){return It=e,new _r({width:(t===null||t===void 0?void 0:t.width)||La(),wrap:t===null||t===void 0?void 0:t.wrap})}var Gr=new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");function An(t){return t.replace(Gr,"")}function Hr(t,e){let[o,n]=t.match(Gr)||["",""];t=An(t);let r="";for(let i=0;i<t.length;i++){if(i!==0&&i%e===0)r+=`
163
- `;r+=t.charAt(i)}if(o&&n)r=`${o}${r}${n}`;return r}function In(t){return Tr(t,{stringWidth:(e)=>{return[...e].length},stripAnsi:An,wrap:Hr})}import{dirname as Nr,resolve as Jr}from"path";import{readdirSync as ja,statSync as _a}from"fs";function jn(t,e){let o=Jr(".",t),n;if(!_a(o).isDirectory())o=Nr(o);while(!0){if(n=e(o,ja(o)),n)return Jr(o,n);if(o=Nr(n=o),n===o)break}}import{inspect as tf}from"util";import{readFileSync as ef}from"fs";import{fileURLToPath as of}from"url";import{format as Ha}from"util";import{normalize as Na,resolve as Ja}from"path";function He(t){if(!(t!==t.toLowerCase()&&t!==t.toUpperCase()))t=t.toLowerCase();if(t.indexOf("-")===-1&&t.indexOf("_")===-1)return t;else{let o="",n=!1,r=t.match(/^-+/);for(let i=r?r[0].length:0;i<t.length;i++){let s=t.charAt(i);if(n)n=!1,s=s.toUpperCase();if(i!==0&&(s==="-"||s==="_"))n=!0;else if(s!=="-"&&s!=="_")o+=s}return o}}function Ko(t,e){let o=t.toLowerCase();e=e||"-";let n="";for(let r=0;r<t.length;r++){let i=o.charAt(r),s=t.charAt(r);if(i!==s&&r>0)n+=`${e}${o.charAt(r)}`;else n+=s}return n}function qo(t){if(t===null||t===void 0)return!1;if(typeof t==="number")return!0;if(/^0x[0-9a-f]+$/i.test(t))return!0;if(/^0[^.]/.test(t))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(t)}function kr(t){if(Array.isArray(t))return t.map((s)=>typeof s!=="string"?s+"":s);t=t.trim();let e=0,o=null,n=null,r=null,i=[];for(let s=0;s<t.length;s++){if(o=n,n=t.charAt(s),n===" "&&!r){if(o!==" ")e++;continue}if(n===r)r=null;else if((n==="'"||n==='"')&&!r)r=n;if(!i[e])i[e]="";i[e]+=n}return i}var Jt;(function(t){t.BOOLEAN="boolean",t.STRING="string",t.NUMBER="number",t.ARRAY="array"})(Jt||(Jt={}));var ue;class Tn{constructor(t){ue=t}parse(t,e){let o=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},e),n=kr(t),r=typeof t==="string",i=Ta(Object.assign(Object.create(null),o.alias)),s=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},o.configuration),c=Object.assign(Object.create(null),o.default),f=o.configObjects||[],a=o.envPrefix,h=s["populate--"],u=h?"--":"_",d=Object.create(null),g=Object.create(null),x=o.__||ue.format,m={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},b=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,S=new RegExp("^--"+s["negation-prefix"]+"(.+)");if([].concat(o.array||[]).filter(Boolean).forEach(function(w){let $=typeof w==="object"?w.key:w,W=Object.keys(w).map(function(P){return{boolean:"bools",string:"strings",number:"numbers"}[P]}).filter(Boolean).pop();if(W)m[W][$]=!0;m.arrays[$]=!0,m.keys.push($)}),[].concat(o.boolean||[]).filter(Boolean).forEach(function(w){m.bools[w]=!0,m.keys.push(w)}),[].concat(o.string||[]).filter(Boolean).forEach(function(w){m.strings[w]=!0,m.keys.push(w)}),[].concat(o.number||[]).filter(Boolean).forEach(function(w){m.numbers[w]=!0,m.keys.push(w)}),[].concat(o.count||[]).filter(Boolean).forEach(function(w){m.counts[w]=!0,m.keys.push(w)}),[].concat(o.normalize||[]).filter(Boolean).forEach(function(w){m.normalize[w]=!0,m.keys.push(w)}),typeof o.narg==="object")Object.entries(o.narg).forEach(([w,$])=>{if(typeof $==="number")m.nargs[w]=$,m.keys.push(w)});if(typeof o.coerce==="object")Object.entries(o.coerce).forEach(([w,$])=>{if(typeof $==="function")m.coercions[w]=$,m.keys.push(w)});if(typeof o.config<"u"){if(Array.isArray(o.config)||typeof o.config==="string")[].concat(o.config).filter(Boolean).forEach(function(w){m.configs[w]=!0});else if(typeof o.config==="object")Object.entries(o.config).forEach(([w,$])=>{if(typeof $==="boolean"||typeof $==="function")m.configs[w]=$})}dt(o.key,i,o.default,m.arrays),Object.keys(c).forEach(function(w){(m.aliases[w]||[]).forEach(function($){c[$]=c[w]})});let E=null;io();let y=[],R=Object.assign(Object.create(null),{_:[]}),it={};for(let w=0;w<n.length;w++){let $=n[w],W=$.replace(/^-{3,}/,"---"),P,C,H,B,z,Pt;if($!=="--"&&/^-/.test($)&&nt($))st($);else if(W.match(/^---+(=|$)/)){st($);continue}else if($.match(/^--.+=/)||!s["short-option-groups"]&&$.match(/^-.+=/)){if(B=$.match(/^--?([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)if(A(B[1],m.arrays))w=ot(w,B[1],n,B[2]);else if(A(B[1],m.nargs)!==!1)w=G(w,B[1],n,B[2]);else et(B[1],B[2],!0)}else if($.match(S)&&s["boolean-negation"]){if(B=$.match(S),B!==null&&Array.isArray(B)&&B.length>=2)C=B[1],et(C,A(C,m.arrays)?[!1]:!1)}else if($.match(/^--.+/)||!s["short-option-groups"]&&$.match(/^-[^-]+/)){if(B=$.match(/^--?(.+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],A(C,m.arrays))w=ot(w,C,n);else if(A(C,m.nargs)!==!1)w=G(w,C,n);else if(z=n[w+1],z!==void 0&&(!z.match(/^-/)||z.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,z),w++;else if(/^(true|false)$/.test(z))et(C,z),w++;else et(C,U(C))}else if($.match(/^-.\..+=/)){if(B=$.match(/^-([^=]+)=([\s\S]*)$/),B!==null&&Array.isArray(B)&&B.length>=3)et(B[1],B[2])}else if($.match(/^-.\..+/)&&!$.match(b)){if(z=n[w+1],B=$.match(/^-(.\..+)/),B!==null&&Array.isArray(B)&&B.length>=2)if(C=B[1],z!==void 0&&!z.match(/^-/)&&!A(C,m.bools)&&!A(C,m.counts))et(C,z),w++;else et(C,U(C))}else if($.match(/^-[^-]+/)&&!$.match(b)){H=$.slice(1,-1).split(""),P=!1;for(let Ft=0;Ft<H.length;Ft++){if(z=$.slice(Ft+2),H[Ft+1]&&H[Ft+1]==="="){if(Pt=$.slice(Ft+3),C=H[Ft],A(C,m.arrays))w=ot(w,C,n,Pt);else if(A(C,m.nargs)!==!1)w=G(w,C,n,Pt);else et(C,Pt);P=!0;break}if(z==="-"){et(H[Ft],z);continue}if(/[A-Za-z]/.test(H[Ft])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(z)&&A(z,m.bools)===!1){et(H[Ft],z),P=!0;break}if(H[Ft+1]&&H[Ft+1].match(/\W/)){et(H[Ft],z),P=!0;break}else et(H[Ft],U(H[Ft]))}if(C=$.slice(-1)[0],!P&&C!=="-")if(A(C,m.arrays))w=ot(w,C,n);else if(A(C,m.nargs)!==!1)w=G(w,C,n);else if(z=n[w+1],z!==void 0&&(!/^(-|--)[^-]/.test(z)||z.match(b))&&!A(C,m.bools)&&!A(C,m.counts))et(C,z),w++;else if(/^(true|false)$/.test(z))et(C,z),w++;else et(C,U(C))}else if($.match(/^-[0-9]$/)&&$.match(b)&&A($.slice(1),m.bools))C=$.slice(1),et(C,U(C));else if($==="--"){y=n.slice(w+1);break}else if(s["halt-at-non-option"]){y=n.slice(w);break}else st($)}if(mt(R,!0),mt(R,!1),L(R),tt(),k(R,m.aliases,c,!0),q(R),s["set-placeholder-key"])ut(R);if(Object.keys(m.counts).forEach(function(w){if(!T(R,w.split(".")))et(w,0)}),h&&y.length)R[u]=[];if(y.forEach(function(w){R[u].push(w)}),s["camel-case-expansion"]&&s["strip-dashed"])Object.keys(R).filter((w)=>w!=="--"&&w.includes("-")).forEach((w)=>{delete R[w]});if(s["strip-aliased"])[].concat(...Object.keys(i).map((w)=>i[w])).forEach((w)=>{if(s["camel-case-expansion"]&&w.includes("-"))delete R[w.split(".").map(($)=>He($)).join(".")];delete R[w]});function st(w){let $=D("_",w);if(typeof $==="string"||typeof $==="number")R._.push($)}function G(w,$,W,P){let C,H=A($,m.nargs);if(H=typeof H!=="number"||isNaN(H)?1:H,H===0){if(!rt(P))E=Error(x("Argument unexpected for: %s",$));return et($,U($)),w}let B=rt(P)?0:1;if(s["nargs-eats-options"]){if(W.length-(w+1)+B<H)E=Error(x("Not enough arguments following: %s",$));B=H}else{for(C=w+1;C<W.length;C++)if(!W[C].match(/^-[^0-9]/)||W[C].match(b)||nt(W[C]))B++;else break;if(B<H)E=Error(x("Not enough arguments following: %s",$))}let z=Math.min(B,H);if(!rt(P)&&z>0)et($,P),z--;for(C=w+1;C<z+w+1;C++)et($,W[C]);return w+z}function ot(w,$,W,P){let C=[],H=P||W[w+1],B=A($,m.nargs);if(A($,m.bools)&&!/^(true|false)$/.test(H))C.push(!0);else if(rt(H)||rt(P)&&/^-/.test(H)&&!b.test(H)&&!nt(H)){if(c[$]!==void 0){let z=c[$];C=Array.isArray(z)?z:[z]}}else{if(!rt(P))C.push(_($,P,!0));for(let z=w+1;z<W.length;z++){if(!s["greedy-arrays"]&&C.length>0||B&&typeof B==="number"&&C.length>=B)break;if(H=W[z],/^-/.test(H)&&!b.test(H)&&!nt(H))break;w=z,C.push(_($,H,r))}}if(typeof B==="number"&&(B&&C.length<B||isNaN(B)&&C.length===0))E=Error(x("Not enough arguments following: %s",$));return et($,C),w}function et(w,$,W=r){if(/-/.test(w)&&s["camel-case-expansion"]){let H=w.split(".").map(function(B){return He(B)}).join(".");le(w,H)}let P=_(w,$,W),C=w.split(".");if(Z(R,C,P),m.aliases[w])m.aliases[w].forEach(function(H){let B=H.split(".");Z(R,B,P)});if(C.length>1&&s["dot-notation"])(m.aliases[C[0]]||[]).forEach(function(H){let B=H.split("."),z=[].concat(C);if(z.shift(),B=B.concat(z),!(m.aliases[w]||[]).includes(B.join(".")))Z(R,B,P)});if(A(w,m.normalize)&&!A(w,m.arrays))[w].concat(m.aliases[w]||[]).forEach(function(B){Object.defineProperty(it,B,{enumerable:!0,get(){return $},set(z){$=typeof z==="string"?ue.normalize(z):z}})})}function le(w,$){if(!(m.aliases[w]&&m.aliases[w].length))m.aliases[w]=[$],d[$]=!0;if(!(m.aliases[$]&&m.aliases[$].length))le($,w)}function _(w,$,W){if(W)$=Ga($);if(A(w,m.bools)||A(w,m.counts)){if(typeof $==="string")$=$==="true"}let P=Array.isArray($)?$.map(function(C){return D(w,C)}):D(w,$);if(A(w,m.counts)&&(rt(P)||typeof P==="boolean"))P=_n();if(A(w,m.normalize)&&A(w,m.arrays))if(Array.isArray($))P=$.map((C)=>{return ue.normalize(C)});else P=ue.normalize($);return P}function D(w,$){if(!s["parse-positional-numbers"]&&w==="_")return $;if(!A(w,m.strings)&&!A(w,m.bools)&&!Array.isArray($)){if(qo($)&&s["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${$}`)))||!rt($)&&A(w,m.numbers))$=Number($)}return $}function L(w){let $=Object.create(null);k($,m.aliases,c),Object.keys(m.configs).forEach(function(W){let P=w[W]||$[W];if(P)try{let C=null,H=ue.resolve(ue.cwd(),P),B=m.configs[W];if(typeof B==="function"){try{C=B(H)}catch(z){C=z}if(C instanceof Error){E=C;return}}else C=ue.require(H);V(C)}catch(C){if(C.name==="PermissionDenied")E=C;else if(w[W])E=Error(x("Invalid JSON config file: %s",P))}})}function V(w,$){Object.keys(w).forEach(function(W){let P=w[W],C=$?$+"."+W:W;if(typeof P==="object"&&P!==null&&!Array.isArray(P)&&s["dot-notation"])V(P,C);else if(!T(R,C.split("."))||A(C,m.arrays)&&s["combine-arrays"])et(C,P)})}function tt(){if(typeof f<"u")f.forEach(function(w){V(w)})}function mt(w,$){if(typeof a>"u")return;let W=typeof a==="string"?a:"",P=ue.env();Object.keys(P).forEach(function(C){if(W===""||C.lastIndexOf(W,0)===0){let H=C.split("__").map(function(B,z){if(z===0)B=B.substring(W.length);return He(B)});if(($&&m.configs[H.join(".")]||!$)&&!T(w,H))et(H.join("."),P[C])}})}function q(w){let $,W=new Set;Object.keys(w).forEach(function(P){if(!W.has(P)){if($=A(P,m.coercions),typeof $==="function")try{let C=D(P,$(w[P]));[].concat(m.aliases[P]||[],P).forEach((H)=>{W.add(H),w[H]=C})}catch(C){E=C}}})}function ut(w){return m.keys.forEach(($)=>{if(~$.indexOf("."))return;if(typeof w[$]>"u")w[$]=void 0}),w}function k(w,$,W,P=!1){Object.keys(W).forEach(function(C){if(!T(w,C.split("."))){if(Z(w,C.split("."),W[C]),P)g[C]=!0;($[C]||[]).forEach(function(H){if(T(w,H.split(".")))return;Z(w,H.split("."),W[C])})}})}function T(w,$){let W=w;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(C){W=W[C]||{}});let P=$[$.length-1];if(typeof W!=="object")return!1;else return P in W}function Z(w,$,W){let P=w;if(!s["dot-notation"])$=[$.join(".")];$.slice(0,-1).forEach(function(Pt){if(Pt=zr(Pt),typeof P==="object"&&P[Pt]===void 0)P[Pt]={};if(typeof P[Pt]!=="object"||Array.isArray(P[Pt])){if(Array.isArray(P[Pt]))P[Pt].push({});else P[Pt]=[P[Pt],{}];P=P[Pt][P[Pt].length-1]}else P=P[Pt]});let C=zr($[$.length-1]),H=A($.join("."),m.arrays),B=Array.isArray(W),z=s["duplicate-arguments-array"];if(!z&&A(C,m.nargs)){if(z=!0,!rt(P[C])&&m.nargs[C]===1||Array.isArray(P[C])&&P[C].length===m.nargs[C])P[C]=void 0}if(W===_n())P[C]=_n(P[C]);else if(Array.isArray(P[C]))if(z&&H&&B)P[C]=s["flatten-duplicate-arrays"]?P[C].concat(W):(Array.isArray(P[C][0])?P[C]:[P[C]]).concat([W]);else if(!z&&Boolean(H)===Boolean(B))P[C]=W;else P[C]=P[C].concat([W]);else if(P[C]===void 0&&H)P[C]=B?W:[W];else if(z&&!(P[C]===void 0||A(C,m.counts)||A(C,m.bools)))P[C]=[P[C],W];else P[C]=W}function dt(...w){w.forEach(function($){Object.keys($||{}).forEach(function(W){if(m.aliases[W])return;m.aliases[W]=[].concat(i[W]||[]),m.aliases[W].concat(W).forEach(function(P){if(/-/.test(P)&&s["camel-case-expansion"]){let C=He(P);if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].concat(W).forEach(function(P){if(P.length>1&&/[A-Z]/.test(P)&&s["camel-case-expansion"]){let C=Ko(P,"-");if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].forEach(function(P){m.aliases[P]=[W].concat(m.aliases[W].filter(function(C){return P!==C}))})})})}function A(w,$){let W=[].concat(m.aliases[w]||[],w),P=Object.keys($),C=W.find((H)=>P.includes(H));return C?$[C]:!1}function ee(w){let $=Object.keys(m);return[].concat($.map((P)=>m[P])).some(function(P){return Array.isArray(P)?P.includes(w):P[w]})}function Se(w,...$){return[].concat(...$).some(function(P){let C=w.match(P);return C&&ee(C[1])})}function F(w){if(w.match(b)||!w.match(/^-[^-]+/))return!1;let $=!0,W,P=w.slice(1).split("");for(let C=0;C<P.length;C++){if(W=w.slice(C+2),!ee(P[C])){$=!1;break}if(P[C+1]&&P[C+1]==="="||W==="-"||/[A-Za-z]/.test(P[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(W)||P[C+1]&&P[C+1].match(/\W/))break}return $}function nt(w){return s["unknown-options-as-args"]&&pt(w)}function pt(w){if(w=w.replace(/^-{3,}/,"--"),w.match(b))return!1;if(F(w))return!1;return!Se(w,/^-+([^=]+?)=[\s\S]*$/,S,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function U(w){if(!A(w,m.bools)&&!A(w,m.counts)&&`${w}`in c)return c[w];else return Q(ft(w))}function Q(w){return{[Jt.BOOLEAN]:!0,[Jt.STRING]:"",[Jt.NUMBER]:void 0,[Jt.ARRAY]:[]}[w]}function ft(w){let $=Jt.BOOLEAN;if(A(w,m.strings))$=Jt.STRING;else if(A(w,m.numbers))$=Jt.NUMBER;else if(A(w,m.bools))$=Jt.BOOLEAN;else if(A(w,m.arrays))$=Jt.ARRAY;return $}function rt(w){return w===void 0}function io(){Object.keys(m.counts).find((w)=>{if(A(w,m.arrays))return E=Error(x("Invalid configuration: %s, opts.count excludes opts.array.",w)),!0;else if(A(w,m.nargs))return E=Error(x("Invalid configuration: %s, opts.count excludes opts.narg.",w)),!0;return!1})}return{aliases:Object.assign({},m.aliases),argv:Object.assign(it,R),configuration:s,defaulted:Object.assign({},g),error:E,newAliases:Object.assign({},d)}}}function Ta(t){let e=[],o=Object.create(null),n=!0;Object.keys(t).forEach(function(r){e.push([].concat(t[r],r))});while(n){n=!1;for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)if(e[r].filter(function(c){return e[i].indexOf(c)!==-1}).length){e[r]=e[r].concat(e[i]),e.splice(i,1),n=!0;break}}return e.forEach(function(r){r=r.filter(function(s,c,f){return f.indexOf(s)===c});let i=r.pop();if(i!==void 0&&typeof i==="string")o[i]=r}),o}function _n(t){return t!==void 0?t+1:1}function zr(t){if(t==="__proto__")return"___proto___";return t}function Ga(t){return typeof t==="string"&&(t[0]==="'"||t[0]==='"')&&t[t.length-1]===t[0]?t.substring(1,t.length-1):t}var Gn,Hn,Nn,vr=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,Ur=(Hn=(Gn=process===null||process===void 0?void 0:process.versions)===null||Gn===void 0?void 0:Gn.node)!==null&&Hn!==void 0?Hn:(Nn=process===null||process===void 0?void 0:process.version)===null||Nn===void 0?void 0:Nn.slice(1);if(Ur){if(Number(Ur.match(/^([^.]+)/)[1])<vr)throw Error(`yargs parser supports a minimum Node.js version of ${vr}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var ka=process?process.env:{},Vr=new Tn({cwd:process.cwd,env:()=>{return ka},format:Ha,normalize:Na,resolve:Ja,require:(t)=>{return he(t)}}),Oo=function(e,o){return Vr.parse(e.slice(),o).argv};Oo.detailed=function(t,e){return Vr.parse(t.slice(),e)};Oo.camelCase=He;Oo.decamelize=Ko;Oo.looksLikeNumber=qo;var Jn=Oo;import{basename as nf,dirname as rf,extname as sf,relative as cf,resolve as ti}from"path";function Kr(){if(za())return 0;return 1}function za(){return va()&&!process.defaultApp}function va(){return!!process.versions.electron}function kn(t){return t.slice(Kr()+1)}function qr(){return process.argv[Kr()]}class lt extends Error{constructor(t){super(t||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,lt)}}import{readFileSync as Ua,statSync as Va,writeFile as Ka}from"fs";import{format as qa}from"util";import{resolve as Xa}from"path";var Xr={fs:{readFileSync:Ua,writeFile:Ka},format:qa,resolve:Xa,exists:(t)=>{try{return Va(t).isFile()}catch(e){return!1}}};var Xt;class Zr{constructor(t){t=t||{},this.directory=t.directory||"./locales",this.updateFiles=typeof t.updateFiles==="boolean"?t.updateFiles:!0,this.locale=t.locale||"en",this.fallbackToLanguage=typeof t.fallbackToLanguage==="boolean"?t.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...t){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let e=t.shift(),o=function(){};if(typeof t[t.length-1]==="function")o=t.pop();if(o=o||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]=e,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();return Xt.format.apply(Xt.format,[this.cache[this.locale][e]||e].concat(t))}__n(){let t=Array.prototype.slice.call(arguments),e=t.shift(),o=t.shift(),n=t.shift(),r=function(){};if(typeof t[t.length-1]==="function")r=t.pop();if(!this.cache[this.locale])this._readLocaleFile();let i=n===1?e:o;if(this.cache[this.locale][e])i=this.cache[this.locale][e][n===1?"one":"other"];if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]={one:e,other:o},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let s=[i];if(~i.indexOf("%d"))s.push(n);return Xt.format.apply(Xt.format,s.concat(t))}setLocale(t){this.locale=t}getLocale(){return this.locale}updateLocale(t){if(!this.cache[this.locale])this._readLocaleFile();for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))this.cache[this.locale][e]=t[e]}_taggedLiteral(t,...e){let o="";return t.forEach(function(n,r){let i=e[r+1];if(o+=n,typeof i<"u")o+="%s"}),this.__.apply(this,[o].concat([].slice.call(e,1)))}_enqueueWrite(t){if(this.writeQueue.push(t),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let t=this,e=this.writeQueue[0],o=e.directory,n=e.locale,r=e.cb,i=this._resolveLocaleFile(o,n),s=JSON.stringify(this.cache[n],null,2);Xt.fs.writeFile(i,s,"utf-8",function(c){if(t.writeQueue.shift(),t.writeQueue.length>0)t._processWriteQueue();r(c)})}_readLocaleFile(){let t={},e=this._resolveLocaleFile(this.directory,this.locale);try{if(Xt.fs.readFileSync)t=JSON.parse(Xt.fs.readFileSync(e,"utf-8"))}catch(o){if(o instanceof SyntaxError)o.message="syntax error in "+e;if(o.code==="ENOENT")t={};else throw o}this.cache[this.locale]=t}_resolveLocaleFile(t,e){let o=Xt.resolve(t,"./",e+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(o)&&~e.lastIndexOf("_")){let n=Xt.resolve(t,"./",e.split("_")[0]+".json");if(this._fileExistsSync(n))o=n}return o}_fileExistsSync(t){return Xt.exists(t)}}function Qr(t,e){Xt=e;let o=new Zr(t);return{__:o.__.bind(o),__n:o.__n.bind(o),setLocale:o.setLocale.bind(o),getLocale:o.getLocale.bind(o),updateLocale:o.updateLocale.bind(o),locale:o.locale}}var Za=(t)=>{return Qr(t,Xr)},Yr=Za;var af="require is not supported by ESM",ei="loading a directory of commands is not supported yet for ESM",Wo;try{Wo=of(import.meta.url)}catch(t){Wo=process.cwd()}var ff=Wo.substring(0,Wo.lastIndexOf("node_modules")),zn={assert:{notStrictEqual:Qa,strictEqual:Ya},cliui:In,findUp:jn,getEnv:(t)=>{return process.env[t]},inspect:tf,getCallerFile:()=>{throw new lt(ei)},getProcessArgvBin:qr,mainFilename:ff||process.cwd(),Parser:Jn,path:{basename:nf,dirname:rf,extname:sf,relative:cf,resolve:ti},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:ef,require:()=>{throw new lt(af)},requireDirectory:()=>{throw new lt(ei)},stringWidth:(t)=>{return[...t].length},y18n:Yr({directory:ti(Wo,"../../../locales"),updateFiles:!1})};function Bt(t,e,o,n){o.assert.notStrictEqual(t,e,n)}function vn(t,e){e.assert.strictEqual(typeof t,"string")}function so(t){return Object.keys(t)}function ht(t){return!!t&&!!t.then&&typeof t.then==="function"}function Pe(t){let o=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=o.shift();if(!r)throw Error(`No command found in: ${t}`);let i={cmd:r.replace(n,""),demanded:[],optional:[]};return o.forEach((s,c)=>{let f=!1;if(s=s.replace(/\s/g,""),/\.+[\]>]/.test(s)&&c===o.length-1)f=!0;if(/^\[/.test(s))i.optional.push({cmd:s.replace(n,"").split("|"),variadic:f});else i.demanded.push({cmd:s.replace(n,"").split("|"),variadic:f})}),i}var lf=["first","second","third","fourth","fifth","sixth"];function I(t,e,o){function n(){return typeof t==="object"?[{demanded:[],optional:[]},t,e]:[Pe(`cmd ${t}`),e,o]}try{let r=0,[i,s,c]=n(),f=[].slice.call(s);while(f.length&&f[f.length-1]===void 0)f.pop();let a=c||f.length;if(a<i.demanded.length)throw new lt(`Not enough arguments provided. Expected ${i.demanded.length} but received ${f.length}.`);let h=i.demanded.length+i.optional.length;if(a>h)throw new lt(`Too many arguments provided. Expected max ${h} but received ${a}.`);i.demanded.forEach((u)=>{let d=f.shift(),g=oi(d);if(u.cmd.filter((m)=>m===g||m==="*").length===0)ni(g,u.cmd,r);r+=1}),i.optional.forEach((u)=>{if(f.length===0)return;let d=f.shift(),g=oi(d);if(u.cmd.filter((m)=>m===g||m==="*").length===0)ni(g,u.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function oi(t){if(Array.isArray(t))return"array";else if(t===null)return"null";return typeof t}function ni(t,e,o){throw new lt(`Invalid ${lf[o]||"manyith"} argument. Expected ${e.join(" or ")} but received ${t}.`)}class Un{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,o=!0,n=!1){if(I("<array|function> [boolean] [boolean] [boolean]",[t,e,o],arguments.length),Array.isArray(t)){for(let r=0;r<t.length;r++){if(typeof t[r]!=="function")throw Error("middleware must be a function");let i=t[r];i.applyBeforeValidation=e,i.global=o}Array.prototype.push.apply(this.globalMiddleware,t)}else if(typeof t==="function"){let r=t;r.applyBeforeValidation=e,r.global=o,r.mutates=n,this.globalMiddleware.push(t)}return this.yargs}addCoerceMiddleware(t,e){let o=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((n)=>{let r=[...o[e]||[],e];if(!n.option)return!0;else return!r.includes(n.option)}),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let t=this.frozens.pop();if(t!==void 0)this.globalMiddleware=t}reset(){this.globalMiddleware=this.globalMiddleware.filter((t)=>t.global)}}function ri(t){if(!t)return[];return t.map((e)=>{return e.applyBeforeValidation=!1,e})}function Ne(t,e,o,n){return o.reduce((r,i)=>{if(i.applyBeforeValidation!==n)return r;if(i.mutates){if(i.applied)return r;i.applied=!0}if(ht(r))return r.then((s)=>Promise.all([s,i(s,e)])).then(([s,c])=>Object.assign(s,c));else{let s=i(r,e);return ht(s)?s.then((c)=>Object.assign(r,c)):Object.assign(r,s)}},t)}function Je(t,e,o=(n)=>{throw n}){try{let n=hf(t)?t():t;return ht(n)?n.then((r)=>e(r)):e(n)}catch(n){return o(n)}}function hf(t){return typeof t==="function"}function Vn(t){for(let e=0,o=Object.keys(he.cache),n;e<o.length;e++)if(n=he.cache[o[e]],n.exports===t)return n;return null}var co=/(^\*)|(^\$0)/;class si{constructor(t,e,o,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=t,this.globalMiddleware=o,this.validation=e}addDirectory(t,e,o,n){if(n=n||{},typeof n.recurse!=="boolean")n.recurse=!1;if(!Array.isArray(n.extensions))n.extensions=["js"];let r=typeof n.visit==="function"?n.visit:(i)=>i;n.visit=(i,s,c)=>{let f=r(i,s,c);if(f){if(this.requireCache.has(s))return f;else this.requireCache.add(s);this.addHandler(f)}return f},this.shim.requireDirectory({require:e,filename:o},t,n)}addHandler(t,e,o,n,r,i){let s=[],c=ri(r);if(n=n||(()=>{}),Array.isArray(t))if(uf(t))[t,...s]=t;else for(let f of t)this.addHandler(f);else if(df(t)){let f=Array.isArray(t.command)||typeof t.command==="string"?t.command:this.moduleName(t);if(t.aliases)f=[].concat(f).concat(t.aliases);this.addHandler(f,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated);return}else if(ii(o)){this.addHandler([t].concat(s),e,o.builder,o.handler,o.middlewares,o.deprecated);return}if(typeof t==="string"){let f=Pe(t);s=s.map((u)=>Pe(u).cmd);let a=!1,h=[f.cmd].concat(s).filter((u)=>{if(co.test(u))return a=!0,!1;return!0});if(h.length===0&&a)h.push("$0");if(a)f.cmd=h[0],s=h.slice(1),t=t.replace(co,f.cmd);if(s.forEach((u)=>{this.aliasMap[u]=f.cmd}),e!==!1)this.usage.command(t,e,a,s,i);if(this.handlers[f.cmd]={original:t,description:e,handler:n,builder:o||{},middlewares:c,deprecated:i,demanded:f.demanded,optional:f.optional},a)this.defaultCommand=this.handlers[f.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,o,n,r,i){let s=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,c=e.getInternalMethods().getContext(),f=c.commands.slice(),a=!t;if(t)c.commands.push(t),c.fullCommands.push(s.original);let h=this.applyBuilderUpdateUsageAndParse(a,s,e,o.aliases,f,n,r,i);return ht(h)?h.then((u)=>this.applyMiddlewareAndGetResult(a,s,u.innerArgv,c,r,u.aliases,e)):this.applyMiddlewareAndGetResult(a,s,h.innerArgv,c,r,h.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,o,n,r,i,s,c){let f=e.builder,a=o;if(Xo(f)){o.getInternalMethods().getUsageInstance().freeze();let h=f(o.getInternalMethods().reset(n),c);if(ht(h))return h.then((u)=>{return a=ai(u)?u:o,this.parseAndUpdateUsage(t,e,a,r,i,s)})}else if(pf(f))o.getInternalMethods().getUsageInstance().freeze(),a=o.getInternalMethods().reset(n),Object.keys(e.builder).forEach((h)=>{a.option(h,f[h])});return this.parseAndUpdateUsage(t,e,a,r,i,s)}parseAndUpdateUsage(t,e,o,n,r,i){if(t)o.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(o))o.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,e),e.description);let s=o.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,i);return ht(s)?s.then((c)=>({aliases:o.parsed.aliases,innerArgv:c})):{aliases:o.parsed.aliases,innerArgv:s}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&t.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(t,e){let o=co.test(e.original)?e.original.replace(co,"").trim():e.original,n=t.filter((r)=>{return!co.test(r)});return n.push(o),`$0 ${n.join(" ")}`}handleValidationAndGetResult(t,e,o,n,r,i,s,c){if(!i.getInternalMethods().getHasOutput()){let f=i.getInternalMethods().runValidation(r,c,i.parsed.error,t);o=Je(o,(a)=>{return f(a),a})}if(e.handler&&!i.getInternalMethods().getHasOutput()){i.getInternalMethods().setHasOutput();let f=!!i.getOptions().configuration["populate--"];if(i.getInternalMethods().postProcess(o,f,!1,!1),o=Ne(o,i,s,!1),o=Je(o,(a)=>{let h=e.handler(a);return ht(h)?h.then(()=>a):a}),!t)i.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ht(o)&&!i.getInternalMethods().hasParseCallback())o.catch((a)=>{try{i.getInternalMethods().getUsageInstance().fail(null,a)}catch(h){}})}if(!t)n.commands.pop(),n.fullCommands.pop();return o}applyMiddlewareAndGetResult(t,e,o,n,r,i,s){let c={};if(r)return o;if(!s.getInternalMethods().getHasOutput())c=this.populatePositionals(e,o,n,s);let f=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),a=Ne(o,s,f,!0);return ht(a)?a.then((h)=>this.handleValidationAndGetResult(t,e,h,n,i,s,f,c)):this.handleValidationAndGetResult(t,e,a,n,i,s,f,c)}populatePositionals(t,e,o,n){e._=e._.slice(o.commands.length);let r=t.demanded.slice(0),i=t.optional.slice(0),s={};this.validation.positionalCount(r.length,e._.length);while(r.length){let c=r.shift();this.populatePositional(c,e,s)}while(i.length){let c=i.shift();this.populatePositional(c,e,s)}return e._=o.commands.concat(e._.map((c)=>""+c)),this.postProcessPositionals(e,s,this.cmdToParseOptions(t.original),n),s}populatePositional(t,e,o){let n=t.cmd[0];if(t.variadic)o[n]=e._.splice(0).map(String);else if(e._.length)o[n]=[String(e._.shift())]}cmdToParseOptions(t){let e={array:[],default:{},alias:{},demand:{}},o=Pe(t);return o.demanded.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i,e.demand[r]=!0}),o.optional.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i}),e}postProcessPositionals(t,e,o,n){let r=Object.assign({},n.getOptions());r.default=Object.assign(o.default,r.default);for(let f of Object.keys(o.alias))r.alias[f]=(r.alias[f]||[]).concat(o.alias[f]);r.array=r.array.concat(o.array),r.config={};let i=[];if(Object.keys(e).forEach((f)=>{e[f].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[f]=!0;i.push(`--${f}`),i.push(a)})}),!i.length)return;let s=Object.assign({},r.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(i,Object.assign({},r,{configuration:s}));if(c.error)n.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let f=Object.keys(e);Object.keys(e).forEach((a)=>{f.push(...c.aliases[a])}),Object.keys(c.argv).forEach((a)=>{if(f.includes(a)){if(!e[a])e[a]=c.argv[a];if(!this.isInConfigs(n,a)&&!this.isDefaulted(n,a)&&Object.prototype.hasOwnProperty.call(t,a)&&Object.prototype.hasOwnProperty.call(c.argv,a)&&(Array.isArray(t[a])||Array.isArray(c.argv[a])))t[a]=[].concat(t[a],c.argv[a]);else t[a]=c.argv[a]}})}}isDefaulted(t,e){let{default:o}=t.getOptions();return Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(e))}isInConfigs(t,e){let{configObjects:o}=t.getOptions();return o.some((n)=>Object.prototype.hasOwnProperty.call(n,e))||o.some((n)=>Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(e)))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){let o=co.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(o,this.defaultCommand.description)}let e=this.defaultCommand.builder;if(Xo(e))return e(t,!0);else if(!ii(e))Object.keys(e).forEach((o)=>{t.option(o,e[o])});return}moduleName(t){let e=Vn(t);if(!e)throw Error(`No command name given for module: ${this.shim.inspect(t)}`);return this.commandFromFilename(e.filename)}commandFromFilename(t){return this.shim.path.basename(t,this.shim.path.extname(t))}extractDesc({describe:t,description:e,desc:o}){for(let n of[t,e,o]){if(typeof n==="string"||n===!1)return n;Bt(n,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let t=this.frozens.pop();Bt(t,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=t}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function ci(t,e,o,n){return new si(t,e,o,n)}function ii(t){return typeof t==="object"&&!!t.builder&&typeof t.handler==="function"}function uf(t){return t.every((e)=>typeof e==="string")}function Xo(t){return typeof t==="function"}function pf(t){return typeof t==="object"}function df(t){return typeof t==="object"&&!Array.isArray(t)}function ye(t={},e=()=>!0){let o={};return so(t).forEach((n)=>{if(e(n,t[n]))o[n]=t[n]}),o}function Ee(t){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((e)=>{let o=e;if(o._handle&&o.isTTY&&typeof o._handle.setBlocking==="function")o._handle.setBlocking(t)})}function mf(t){return typeof t==="boolean"}function li(t,e){let o=e.y18n.__,n={},r=[];n.failFn=function(D){r.push(D)};let i=null,s=null,c=!0;n.showHelpOnFail=function(D=!0,L){let[V,tt]=typeof D==="string"?[!0,D]:[D,L];if(t.getInternalMethods().isGlobalContext())s=tt;return i=tt,c=V,n};let f=!1;n.fail=function(D,L){let V=t.getInternalMethods().getLoggerInstance();if(r.length)for(let tt=r.length-1;tt>=0;--tt){let mt=r[tt];if(mf(mt)){if(L)throw L;else if(D)throw Error(D)}else mt(D,L,n)}else{if(t.getExitProcess())Ee(!0);if(!f){if(f=!0,c)t.showHelp("error"),V.error();if(D||L)V.error(D||L);let tt=i||s;if(tt){if(D||L)V.error("");V.error(tt)}}if(L=L||new lt(D),t.getExitProcess())return t.exit(1);else if(t.getInternalMethods().hasParseCallback())return t.exit(1,L);else throw L}};let a=[],h=!1;n.usage=(_,D)=>{if(_===null)return h=!0,a=[],n;return h=!1,a.push([_,D||""]),n},n.getUsage=()=>{return a},n.getUsageDisabled=()=>{return h},n.getPositionalGroupName=()=>{return o("Positionals:")};let u=[];n.example=(_,D)=>{u.push([_,D||""])};let d=[];n.command=function(D,L,V,tt,mt=!1){if(V)d=d.map((q)=>{return q[2]=!1,q});d.push([D,L||"",V,tt,mt])},n.getCommands=()=>d;let g={};n.describe=function(D,L){if(Array.isArray(D))D.forEach((V)=>{n.describe(V,L)});else if(typeof D==="object")Object.keys(D).forEach((V)=>{n.describe(V,D[V])});else g[D]=L},n.getDescriptions=()=>g;let x=[];n.epilog=(_)=>{x.push(_)};let m=!1,b;n.wrap=(_)=>{m=!0,b=_},n.getWrap=()=>{if(e.getEnv("YARGS_DISABLE_WRAP"))return null;if(!m)b=ot(),m=!0;return b};let S="__yargsString__:";n.deferY18nLookup=(_)=>S+_,n.help=function(){if(R)return R;y();let D=t.customScriptName?t.$0:e.path.basename(t.$0),L=t.getDemandedOptions(),V=t.getDemandedCommands(),tt=t.getDeprecatedOptions(),mt=t.getGroups(),q=t.getOptions(),ut=[];ut=ut.concat(Object.keys(g)),ut=ut.concat(Object.keys(L)),ut=ut.concat(Object.keys(V)),ut=ut.concat(Object.keys(q.default)),ut=ut.filter(st),ut=Object.keys(ut.reduce((F,nt)=>{if(nt!=="_")F[nt]=!0;return F},{}));let k=n.getWrap(),T=e.cliui({width:k,wrap:!!k});if(!h){if(a.length)a.forEach((F)=>{if(T.div({text:`${F[0].replace(/\$0/g,D)}`}),F[1])T.div({text:`${F[1]}`,padding:[1,0,0,0]})}),T.div();else if(d.length){let F=null;if(V._)F=`${D} <${o("command")}>
164
- `;else F=`${D} [${o("command")}]
165
- `;T.div(`${F}`)}}if(d.length>1||d.length===1&&!d[0][2]){T.div(o("Commands:"));let F=t.getInternalMethods().getContext(),nt=F.commands.length?`${F.commands.join(" ")} `:"";if(t.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)d=d.sort((U,Q)=>U[0].localeCompare(Q[0]));let pt=D?`${D} `:"";d.forEach((U)=>{let Q=`${pt}${nt}${U[0].replace(/^\$0 ?/,"")}`;T.span({text:Q,padding:[0,2,0,2],width:E(d,k,`${D}${nt}`)+4},{text:U[1]});let ft=[];if(U[2])ft.push(`[${o("default")}]`);if(U[3]&&U[3].length)ft.push(`[${o("aliases:")} ${U[3].join(", ")}]`);if(U[4])if(typeof U[4]==="string")ft.push(`[${o("deprecated: %s",U[4])}]`);else ft.push(`[${o("deprecated")}]`);if(ft.length)T.div({text:ft.join(" "),padding:[0,0,0,2],align:"right"});else T.div()}),T.div()}let Z=(Object.keys(q.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);ut=ut.filter((F)=>!t.parsed.newAliases[F]&&Z.every((nt)=>(q.alias[nt]||[]).indexOf(F)===-1));let dt=o("Options:");if(!mt[dt])mt[dt]=[];it(ut,q.alias,mt,dt);let A=(F)=>/^--/.test(Zo(F)),ee=Object.keys(mt).filter((F)=>mt[F].length>0).map((F)=>{let nt=mt[F].filter(st).map((pt)=>{if(Z.includes(pt))return pt;for(let U=0,Q;(Q=Z[U])!==void 0;U++)if((q.alias[Q]||[]).includes(pt))return Q;return pt});return{groupName:F,normalizedKeys:nt}}).filter(({normalizedKeys:F})=>F.length>0).map(({groupName:F,normalizedKeys:nt})=>{let pt=nt.reduce((U,Q)=>{return U[Q]=[Q].concat(q.alias[Q]||[]).map((ft)=>{if(F===n.getPositionalGroupName())return ft;else return(/^[0-9]$/.test(ft)?q.boolean.includes(Q)?"-":"--":ft.length>1?"--":"-")+ft}).sort((ft,rt)=>A(ft)===A(rt)?0:A(ft)?1:-1).join(", "),U},{});return{groupName:F,normalizedKeys:nt,switches:pt}});if(ee.filter(({groupName:F})=>F!==n.getPositionalGroupName()).some(({normalizedKeys:F,switches:nt})=>!F.every((pt)=>A(nt[pt]))))ee.filter(({groupName:F})=>F!==n.getPositionalGroupName()).forEach(({normalizedKeys:F,switches:nt})=>{F.forEach((pt)=>{if(A(nt[pt]))nt[pt]=xf(nt[pt],4)})});if(ee.forEach(({groupName:F,normalizedKeys:nt,switches:pt})=>{T.div(F),nt.forEach((U)=>{let Q=pt[U],ft=g[U]||"",rt=null;if(ft.includes(S))ft=o(ft.substring(S.length));if(q.boolean.includes(U))rt=`[${o("boolean")}]`;if(q.count.includes(U))rt=`[${o("count")}]`;if(q.string.includes(U))rt=`[${o("string")}]`;if(q.normalize.includes(U))rt=`[${o("string")}]`;if(q.array.includes(U))rt=`[${o("array")}]`;if(q.number.includes(U))rt=`[${o("number")}]`;let io=(W)=>typeof W==="string"?`[${o("deprecated: %s",W)}]`:`[${o("deprecated")}]`,w=[U in tt?io(tt[U]):null,rt,U in L?`[${o("required")}]`:null,q.choices&&q.choices[U]?`[${o("choices:")} ${n.stringifiedValues(q.choices[U])}]`:null,G(q.default[U],q.defaultDescription[U])].filter(Boolean).join(" ");T.span({text:Zo(Q),padding:[0,2,0,2+fi(Q)],width:E(pt,k)+4},ft);let $=t.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(w&&!$)T.div({text:w,padding:[0,0,0,2],align:"right"});else T.div()}),T.div()}),u.length)T.div(o("Examples:")),u.forEach((F)=>{F[0]=F[0].replace(/\$0/g,D)}),u.forEach((F)=>{if(F[1]==="")T.div({text:F[0],padding:[0,2,0,2]});else T.div({text:F[0],padding:[0,2,0,2],width:E(u,k)+4},{text:F[1]})}),T.div();if(x.length>0){let F=x.map((nt)=>nt.replace(/\$0/g,D)).join(`
166
- `);T.div(`${F}
167
- `)}return T.toString().replace(/\s*$/,"")};function E(_,D,L){let V=0;if(!Array.isArray(_))_=Object.values(_).map((tt)=>[tt]);if(_.forEach((tt)=>{V=Math.max(e.stringWidth(L?`${L} ${Zo(tt[0])}`:Zo(tt[0]))+fi(tt[0]),V)}),D)V=Math.min(V,parseInt((D*0.5).toString(),10));return V}function y(){let _=t.getDemandedOptions(),D=t.getOptions();(Object.keys(D.alias)||[]).forEach((L)=>{D.alias[L].forEach((V)=>{if(g[V])n.describe(L,g[V]);if(V in _)t.demandOption(L,_[V]);if(D.boolean.includes(V))t.boolean(L);if(D.count.includes(V))t.count(L);if(D.string.includes(V))t.string(L);if(D.normalize.includes(V))t.normalize(L);if(D.array.includes(V))t.array(L);if(D.number.includes(V))t.number(L)})})}let R;n.cacheHelpMessage=function(){R=this.help()},n.clearCachedHelpMessage=function(){R=void 0},n.hasCachedHelpMessage=function(){return!!R};function it(_,D,L,V){let tt=[],mt=null;return Object.keys(L).forEach((q)=>{tt=tt.concat(L[q])}),_.forEach((q)=>{if(mt=[q].concat(D[q]),!mt.some((ut)=>tt.indexOf(ut)!==-1))L[V].push(q)}),tt}function st(_){return t.getOptions().hiddenOptions.indexOf(_)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}n.showHelp=(_)=>{let D=t.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:D[_])(n.help())},n.functionDescription=(_)=>{return["(",_.name?e.Parser.decamelize(_.name,"-"):o("generated-value"),")"].join("")},n.stringifiedValues=function(D,L){let V="",tt=L||", ",mt=[].concat(D);if(!D||!mt.length)return V;return mt.forEach((q)=>{if(V.length)V+=tt;V+=JSON.stringify(q)}),V};function G(_,D){let L=`[${o("default:")} `;if(_===void 0&&!D)return null;if(D)L+=D;else switch(typeof _){case"string":L+=`"${_}"`;break;case"object":L+=JSON.stringify(_);break;default:L+=_}return`${L}]`}function ot(){if(e.process.stdColumns)return Math.min(80,e.process.stdColumns);else return 80}let et=null;n.version=(_)=>{et=_},n.showVersion=(_)=>{let D=t.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:D[_])(et)},n.reset=function(D){return i=null,f=!1,a=[],h=!1,x=[],u=[],d=[],g=ye(g,(L)=>!D[L]),n};let le=[];return n.freeze=function(){le.push({failMessage:i,failureOutput:f,usages:a,usageDisabled:h,epilogs:x,examples:u,commands:d,descriptions:g})},n.unfreeze=function(D=!1){let L=le.pop();if(!L)return;if(D)g={...L.descriptions,...g},d=[...L.commands,...d],a=[...L.usages,...a],u=[...L.examples,...u],x=[...L.epilogs,...x];else({failMessage:i,failureOutput:f,usages:a,usageDisabled:h,epilogs:x,examples:u,commands:d,descriptions:g}=L)},n}function Kn(t){return typeof t==="object"}function xf(t,e){return Kn(t)?{text:t.text,indentation:t.indentation+e}:{text:t,indentation:e}}function fi(t){return Kn(t)?t.indentation:0}function Zo(t){return Kn(t)?t.text:t}var hi=`###-begin-{{app_name}}-completions-###
161
+ `);if(r.border)n.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),n.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)n.unshift(...Array(r.padding[0]||0).fill("")),n.push(...Array(r.padding[2]||0).fill(""));n.forEach((s,c)=>{if(!e[c])e.push([]);let l=e[c];for(let a=0;a<i;a++)if(l[a]===void 0)l.push("");l.push(s)})}),e}negatePadding(t){let e=t.width||0;if(t.padding)e-=(t.padding[3]||0)+(t.padding[1]||0);if(t.border)e-=4;return e}columnWidths(t){if(!this.wrap)return t.map((i)=>{return i.width||_t.stringWidth(i.text)});let e=t.length,o=this.width,n=t.map((i)=>{if(i.width)return e--,o-=i.width,i.width;return}),r=e?Math.floor(o/e):0;return n.map((i,s)=>{if(i===void 0)return Math.max(r,Ta(t[s]));return i})}}function vr(t,e,o){if(t.border){if(/[.']-+[.']/.test(e))return"";if(e.trim().length!==0)return o;return" "}return""}function Ta(t){let e=t.padding||[],o=1+(e[3]||0)+(e[1]||0);if(t.border)return o+4;return o}function Ga(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function va(t,e){t=t.trim();let o=_t.stringWidth(t);if(o<e)return" ".repeat(e-o)+t;return t}function Ha(t,e){t=t.trim();let o=_t.stringWidth(t);if(o>=e)return t;return" ".repeat(e-o>>1)+t}var _t;function kr(t,e){return _t=e,new Hr({width:(t===null||t===void 0?void 0:t.width)||Ga(),wrap:t===null||t===void 0?void 0:t.wrap})}var Nr=new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)","g");function _n(t){return t.replace(Nr,"")}function Jr(t,e){let[o,n]=t.match(Nr)||["",""];t=_n(t);let r="";for(let i=0;i<t.length;i++){if(i!==0&&i%e===0)r+=`
162
+ `;r+=t.charAt(i)}if(o&&n)r=`${o}${r}${n}`;return r}function Tn(t){return kr(t,{stringWidth:(e)=>{return[...e].length},stripAnsi:_n,wrap:Jr})}import{dirname as zr,resolve as Ur}from"path";import{readdirSync as ka,statSync as Na}from"fs";function Gn(t,e){let o=Ur(".",t),n;if(!Na(o).isDirectory())o=zr(o);while(!0){if(n=e(o,ka(o)),n)return Ur(o,n);if(o=zr(n=o),n===o)break}}import{inspect as sl}from"util";import{readFileSync as cl}from"fs";import{fileURLToPath as al}from"url";import{format as Ua}from"util";import{normalize as Va,resolve as Ka}from"path";function ke(t){if(!(t!==t.toLowerCase()&&t!==t.toUpperCase()))t=t.toLowerCase();if(t.indexOf("-")===-1&&t.indexOf("_")===-1)return t;else{let o="",n=!1,r=t.match(/^-+/);for(let i=r?r[0].length:0;i<t.length;i++){let s=t.charAt(i);if(n)n=!1,s=s.toUpperCase();if(i!==0&&(s==="-"||s==="_"))n=!0;else if(s!=="-"&&s!=="_")o+=s}return o}}function Qo(t,e){let o=t.toLowerCase();e=e||"-";let n="";for(let r=0;r<t.length;r++){let i=o.charAt(r),s=t.charAt(r);if(i!==s&&r>0)n+=`${e}${o.charAt(r)}`;else n+=s}return n}function Yo(t){if(t===null||t===void 0)return!1;if(typeof t==="number")return!0;if(/^0x[0-9a-f]+$/i.test(t))return!0;if(/^0[^.]/.test(t))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(t)}function Vr(t){if(Array.isArray(t))return t.map((s)=>typeof s!=="string"?s+"":s);t=t.trim();let e=0,o=null,n=null,r=null,i=[];for(let s=0;s<t.length;s++){if(o=n,n=t.charAt(s),n===" "&&!r){if(o!==" ")e++;continue}if(n===r)r=null;else if((n==="'"||n==='"')&&!r)r=n;if(!i[e])i[e]="";i[e]+=n}return i}var Nt;(function(t){t.BOOLEAN="boolean",t.STRING="string",t.NUMBER="number",t.ARRAY="array"})(Nt||(Nt={}));var de;class Hn{constructor(t){de=t}parse(t,e){let o=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},e),n=Vr(t),r=typeof t==="string",i=Ja(Object.assign(Object.create(null),o.alias)),s=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},o.configuration),c=Object.assign(Object.create(null),o.default),l=o.configObjects||[],a=o.envPrefix,h=s["populate--"],u=h?"--":"_",d=Object.create(null),g=Object.create(null),x=o.__||de.format,m={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},b=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,$=new RegExp("^--"+s["negation-prefix"]+"(.+)");if([].concat(o.array||[]).filter(Boolean).forEach(function(w){let S=typeof w==="object"?w.key:w,W=Object.keys(w).map(function(y){return{boolean:"bools",string:"strings",number:"numbers"}[y]}).filter(Boolean).pop();if(W)m[W][S]=!0;m.arrays[S]=!0,m.keys.push(S)}),[].concat(o.boolean||[]).filter(Boolean).forEach(function(w){m.bools[w]=!0,m.keys.push(w)}),[].concat(o.string||[]).filter(Boolean).forEach(function(w){m.strings[w]=!0,m.keys.push(w)}),[].concat(o.number||[]).filter(Boolean).forEach(function(w){m.numbers[w]=!0,m.keys.push(w)}),[].concat(o.count||[]).filter(Boolean).forEach(function(w){m.counts[w]=!0,m.keys.push(w)}),[].concat(o.normalize||[]).filter(Boolean).forEach(function(w){m.normalize[w]=!0,m.keys.push(w)}),typeof o.narg==="object")Object.entries(o.narg).forEach(([w,S])=>{if(typeof S==="number")m.nargs[w]=S,m.keys.push(w)});if(typeof o.coerce==="object")Object.entries(o.coerce).forEach(([w,S])=>{if(typeof S==="function")m.coercions[w]=S,m.keys.push(w)});if(typeof o.config<"u"){if(Array.isArray(o.config)||typeof o.config==="string")[].concat(o.config).filter(Boolean).forEach(function(w){m.configs[w]=!0});else if(typeof o.config==="object")Object.entries(o.config).forEach(([w,S])=>{if(typeof S==="boolean"||typeof S==="function")m.configs[w]=S})}dt(o.key,i,o.default,m.arrays),Object.keys(c).forEach(function(w){(m.aliases[w]||[]).forEach(function(S){c[S]=c[w]})});let E=null;so();let R=[],P=Object.assign(Object.create(null),{_:[]}),rt={};for(let w=0;w<n.length;w++){let S=n[w],W=S.replace(/^-{3,}/,"---"),y,C,v,L,z,Pt;if(S!=="--"&&/^-/.test(S)&&ot(S))at(S);else if(W.match(/^---+(=|$)/)){at(S);continue}else if(S.match(/^--.+=/)||!s["short-option-groups"]&&S.match(/^-.+=/)){if(L=S.match(/^--?([^=]+)=([\s\S]*)$/),L!==null&&Array.isArray(L)&&L.length>=3)if(j(L[1],m.arrays))w=Y(w,L[1],n,L[2]);else if(j(L[1],m.nargs)!==!1)w=I(w,L[1],n,L[2]);else et(L[1],L[2],!0)}else if(S.match($)&&s["boolean-negation"]){if(L=S.match($),L!==null&&Array.isArray(L)&&L.length>=2)C=L[1],et(C,j(C,m.arrays)?[!1]:!1)}else if(S.match(/^--.+/)||!s["short-option-groups"]&&S.match(/^-[^-]+/)){if(L=S.match(/^--?(.+)/),L!==null&&Array.isArray(L)&&L.length>=2)if(C=L[1],j(C,m.arrays))w=Y(w,C,n);else if(j(C,m.nargs)!==!1)w=I(w,C,n);else if(z=n[w+1],z!==void 0&&(!z.match(/^-/)||z.match(b))&&!j(C,m.bools)&&!j(C,m.counts))et(C,z),w++;else if(/^(true|false)$/.test(z))et(C,z),w++;else et(C,U(C))}else if(S.match(/^-.\..+=/)){if(L=S.match(/^-([^=]+)=([\s\S]*)$/),L!==null&&Array.isArray(L)&&L.length>=3)et(L[1],L[2])}else if(S.match(/^-.\..+/)&&!S.match(b)){if(z=n[w+1],L=S.match(/^-(.\..+)/),L!==null&&Array.isArray(L)&&L.length>=2)if(C=L[1],z!==void 0&&!z.match(/^-/)&&!j(C,m.bools)&&!j(C,m.counts))et(C,z),w++;else et(C,U(C))}else if(S.match(/^-[^-]+/)&&!S.match(b)){v=S.slice(1,-1).split(""),y=!1;for(let Ft=0;Ft<v.length;Ft++){if(z=S.slice(Ft+2),v[Ft+1]&&v[Ft+1]==="="){if(Pt=S.slice(Ft+3),C=v[Ft],j(C,m.arrays))w=Y(w,C,n,Pt);else if(j(C,m.nargs)!==!1)w=I(w,C,n,Pt);else et(C,Pt);y=!0;break}if(z==="-"){et(v[Ft],z);continue}if(/[A-Za-z]/.test(v[Ft])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(z)&&j(z,m.bools)===!1){et(v[Ft],z),y=!0;break}if(v[Ft+1]&&v[Ft+1].match(/\W/)){et(v[Ft],z),y=!0;break}else et(v[Ft],U(v[Ft]))}if(C=S.slice(-1)[0],!y&&C!=="-")if(j(C,m.arrays))w=Y(w,C,n);else if(j(C,m.nargs)!==!1)w=I(w,C,n);else if(z=n[w+1],z!==void 0&&(!/^(-|--)[^-]/.test(z)||z.match(b))&&!j(C,m.bools)&&!j(C,m.counts))et(C,z),w++;else if(/^(true|false)$/.test(z))et(C,z),w++;else et(C,U(C))}else if(S.match(/^-[0-9]$/)&&S.match(b)&&j(S.slice(1),m.bools))C=S.slice(1),et(C,U(C));else if(S==="--"){R=n.slice(w+1);break}else if(s["halt-at-non-option"]){R=n.slice(w);break}else at(S)}if(mt(P,!0),mt(P,!1),A(P),tt(),J(P,m.aliases,c,!0),X(P),s["set-placeholder-key"])ut(P);if(Object.keys(m.counts).forEach(function(w){if(!G(P,w.split(".")))et(w,0)}),h&&R.length)P[u]=[];if(R.forEach(function(w){P[u].push(w)}),s["camel-case-expansion"]&&s["strip-dashed"])Object.keys(P).filter((w)=>w!=="--"&&w.includes("-")).forEach((w)=>{delete P[w]});if(s["strip-aliased"])[].concat(...Object.keys(i).map((w)=>i[w])).forEach((w)=>{if(s["camel-case-expansion"]&&w.includes("-"))delete P[w.split(".").map((S)=>ke(S)).join(".")];delete P[w]});function at(w){let S=D("_",w);if(typeof S==="string"||typeof S==="number")P._.push(S)}function I(w,S,W,y){let C,v=j(S,m.nargs);if(v=typeof v!=="number"||isNaN(v)?1:v,v===0){if(!nt(y))E=Error(x("Argument unexpected for: %s",S));return et(S,U(S)),w}let L=nt(y)?0:1;if(s["nargs-eats-options"]){if(W.length-(w+1)+L<v)E=Error(x("Not enough arguments following: %s",S));L=v}else{for(C=w+1;C<W.length;C++)if(!W[C].match(/^-[^0-9]/)||W[C].match(b)||ot(W[C]))L++;else break;if(L<v)E=Error(x("Not enough arguments following: %s",S))}let z=Math.min(L,v);if(!nt(y)&&z>0)et(S,y),z--;for(C=w+1;C<z+w+1;C++)et(S,W[C]);return w+z}function Y(w,S,W,y){let C=[],v=y||W[w+1],L=j(S,m.nargs);if(j(S,m.bools)&&!/^(true|false)$/.test(v))C.push(!0);else if(nt(v)||nt(y)&&/^-/.test(v)&&!b.test(v)&&!ot(v)){if(c[S]!==void 0){let z=c[S];C=Array.isArray(z)?z:[z]}}else{if(!nt(y))C.push(F(S,y,!0));for(let z=w+1;z<W.length;z++){if(!s["greedy-arrays"]&&C.length>0||L&&typeof L==="number"&&C.length>=L)break;if(v=W[z],/^-/.test(v)&&!b.test(v)&&!ot(v))break;w=z,C.push(F(S,v,r))}}if(typeof L==="number"&&(L&&C.length<L||isNaN(L)&&C.length===0))E=Error(x("Not enough arguments following: %s",S));return et(S,C),w}function et(w,S,W=r){if(/-/.test(w)&&s["camel-case-expansion"]){let v=w.split(".").map(function(L){return ke(L)}).join(".");It(w,v)}let y=F(w,S,W),C=w.split(".");if(it(P,C,y),m.aliases[w])m.aliases[w].forEach(function(v){let L=v.split(".");it(P,L,y)});if(C.length>1&&s["dot-notation"])(m.aliases[C[0]]||[]).forEach(function(v){let L=v.split("."),z=[].concat(C);if(z.shift(),L=L.concat(z),!(m.aliases[w]||[]).includes(L.join(".")))it(P,L,y)});if(j(w,m.normalize)&&!j(w,m.arrays))[w].concat(m.aliases[w]||[]).forEach(function(L){Object.defineProperty(rt,L,{enumerable:!0,get(){return S},set(z){S=typeof z==="string"?de.normalize(z):z}})})}function It(w,S){if(!(m.aliases[w]&&m.aliases[w].length))m.aliases[w]=[S],d[S]=!0;if(!(m.aliases[S]&&m.aliases[S].length))It(S,w)}function F(w,S,W){if(W)S=za(S);if(j(w,m.bools)||j(w,m.counts)){if(typeof S==="string")S=S==="true"}let y=Array.isArray(S)?S.map(function(C){return D(w,C)}):D(w,S);if(j(w,m.counts)&&(nt(y)||typeof y==="boolean"))y=vn();if(j(w,m.normalize)&&j(w,m.arrays))if(Array.isArray(S))y=S.map((C)=>{return de.normalize(C)});else y=de.normalize(S);return y}function D(w,S){if(!s["parse-positional-numbers"]&&w==="_")return S;if(!j(w,m.strings)&&!j(w,m.bools)&&!Array.isArray(S)){if(Yo(S)&&s["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))||!nt(S)&&j(w,m.numbers))S=Number(S)}return S}function A(w){let S=Object.create(null);J(S,m.aliases,c),Object.keys(m.configs).forEach(function(W){let y=w[W]||S[W];if(y)try{let C=null,v=de.resolve(de.cwd(),y),L=m.configs[W];if(typeof L==="function"){try{C=L(v)}catch(z){C=z}if(C instanceof Error){E=C;return}}else C=de.require(v);V(C)}catch(C){if(C.name==="PermissionDenied")E=C;else if(w[W])E=Error(x("Invalid JSON config file: %s",y))}})}function V(w,S){Object.keys(w).forEach(function(W){let y=w[W],C=S?S+"."+W:W;if(typeof y==="object"&&y!==null&&!Array.isArray(y)&&s["dot-notation"])V(y,C);else if(!G(P,C.split("."))||j(C,m.arrays)&&s["combine-arrays"])et(C,y)})}function tt(){if(typeof l<"u")l.forEach(function(w){V(w)})}function mt(w,S){if(typeof a>"u")return;let W=typeof a==="string"?a:"",y=de.env();Object.keys(y).forEach(function(C){if(W===""||C.lastIndexOf(W,0)===0){let v=C.split("__").map(function(L,z){if(z===0)L=L.substring(W.length);return ke(L)});if((S&&m.configs[v.join(".")]||!S)&&!G(w,v))et(v.join("."),y[C])}})}function X(w){let S,W=new Set;Object.keys(w).forEach(function(y){if(!W.has(y)){if(S=j(y,m.coercions),typeof S==="function")try{let C=D(y,S(w[y]));[].concat(m.aliases[y]||[],y).forEach((v)=>{W.add(v),w[v]=C})}catch(C){E=C}}})}function ut(w){return m.keys.forEach((S)=>{if(~S.indexOf("."))return;if(typeof w[S]>"u")w[S]=void 0}),w}function J(w,S,W,y=!1){Object.keys(W).forEach(function(C){if(!G(w,C.split("."))){if(it(w,C.split("."),W[C]),y)g[C]=!0;(S[C]||[]).forEach(function(v){if(G(w,v.split(".")))return;it(w,v.split("."),W[C])})}})}function G(w,S){let W=w;if(!s["dot-notation"])S=[S.join(".")];S.slice(0,-1).forEach(function(C){W=W[C]||{}});let y=S[S.length-1];if(typeof W!=="object")return!1;else return y in W}function it(w,S,W){let y=w;if(!s["dot-notation"])S=[S.join(".")];S.slice(0,-1).forEach(function(Pt){if(Pt=Kr(Pt),typeof y==="object"&&y[Pt]===void 0)y[Pt]={};if(typeof y[Pt]!=="object"||Array.isArray(y[Pt])){if(Array.isArray(y[Pt]))y[Pt].push({});else y[Pt]=[y[Pt],{}];y=y[Pt][y[Pt].length-1]}else y=y[Pt]});let C=Kr(S[S.length-1]),v=j(S.join("."),m.arrays),L=Array.isArray(W),z=s["duplicate-arguments-array"];if(!z&&j(C,m.nargs)){if(z=!0,!nt(y[C])&&m.nargs[C]===1||Array.isArray(y[C])&&y[C].length===m.nargs[C])y[C]=void 0}if(W===vn())y[C]=vn(y[C]);else if(Array.isArray(y[C]))if(z&&v&&L)y[C]=s["flatten-duplicate-arrays"]?y[C].concat(W):(Array.isArray(y[C][0])?y[C]:[y[C]]).concat([W]);else if(!z&&Boolean(v)===Boolean(L))y[C]=W;else y[C]=y[C].concat([W]);else if(y[C]===void 0&&v)y[C]=L?W:[W];else if(z&&!(y[C]===void 0||j(C,m.counts)||j(C,m.bools)))y[C]=[y[C],W];else y[C]=W}function dt(...w){w.forEach(function(S){Object.keys(S||{}).forEach(function(W){if(m.aliases[W])return;m.aliases[W]=[].concat(i[W]||[]),m.aliases[W].concat(W).forEach(function(y){if(/-/.test(y)&&s["camel-case-expansion"]){let C=ke(y);if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].concat(W).forEach(function(y){if(y.length>1&&/[A-Z]/.test(y)&&s["camel-case-expansion"]){let C=Qo(y,"-");if(C!==W&&m.aliases[W].indexOf(C)===-1)m.aliases[W].push(C),d[C]=!0}}),m.aliases[W].forEach(function(y){m.aliases[y]=[W].concat(m.aliases[W].filter(function(C){return y!==C}))})})})}function j(w,S){let W=[].concat(m.aliases[w]||[],w),y=Object.keys(S),C=W.find((v)=>y.includes(v));return C?S[C]:!1}function oe(w){let S=Object.keys(m);return[].concat(S.map((y)=>m[y])).some(function(y){return Array.isArray(y)?y.includes(w):y[w]})}function Pe(w,...S){return[].concat(...S).some(function(y){let C=w.match(y);return C&&oe(C[1])})}function B(w){if(w.match(b)||!w.match(/^-[^-]+/))return!1;let S=!0,W,y=w.slice(1).split("");for(let C=0;C<y.length;C++){if(W=w.slice(C+2),!oe(y[C])){S=!1;break}if(y[C+1]&&y[C+1]==="="||W==="-"||/[A-Za-z]/.test(y[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(W)||y[C+1]&&y[C+1].match(/\W/))break}return S}function ot(w){return s["unknown-options-as-args"]&&pt(w)}function pt(w){if(w=w.replace(/^-{3,}/,"--"),w.match(b))return!1;if(B(w))return!1;return!Pe(w,/^-+([^=]+?)=[\s\S]*$/,$,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function U(w){if(!j(w,m.bools)&&!j(w,m.counts)&&`${w}`in c)return c[w];else return Z(lt(w))}function Z(w){return{[Nt.BOOLEAN]:!0,[Nt.STRING]:"",[Nt.NUMBER]:void 0,[Nt.ARRAY]:[]}[w]}function lt(w){let S=Nt.BOOLEAN;if(j(w,m.strings))S=Nt.STRING;else if(j(w,m.numbers))S=Nt.NUMBER;else if(j(w,m.bools))S=Nt.BOOLEAN;else if(j(w,m.arrays))S=Nt.ARRAY;return S}function nt(w){return w===void 0}function so(){Object.keys(m.counts).find((w)=>{if(j(w,m.arrays))return E=Error(x("Invalid configuration: %s, opts.count excludes opts.array.",w)),!0;else if(j(w,m.nargs))return E=Error(x("Invalid configuration: %s, opts.count excludes opts.narg.",w)),!0;return!1})}return{aliases:Object.assign({},m.aliases),argv:Object.assign(rt,P),configuration:s,defaulted:Object.assign({},g),error:E,newAliases:Object.assign({},d)}}}function Ja(t){let e=[],o=Object.create(null),n=!0;Object.keys(t).forEach(function(r){e.push([].concat(t[r],r))});while(n){n=!1;for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)if(e[r].filter(function(c){return e[i].indexOf(c)!==-1}).length){e[r]=e[r].concat(e[i]),e.splice(i,1),n=!0;break}}return e.forEach(function(r){r=r.filter(function(s,c,l){return l.indexOf(s)===c});let i=r.pop();if(i!==void 0&&typeof i==="string")o[i]=r}),o}function vn(t){return t!==void 0?t+1:1}function Kr(t){if(t==="__proto__")return"___proto___";return t}function za(t){return typeof t==="string"&&(t[0]==="'"||t[0]==='"')&&t[t.length-1]===t[0]?t.substring(1,t.length-1):t}var kn,Nn,Jn,Xr=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12,qr=(Nn=(kn=process===null||process===void 0?void 0:process.versions)===null||kn===void 0?void 0:kn.node)!==null&&Nn!==void 0?Nn:(Jn=process===null||process===void 0?void 0:process.version)===null||Jn===void 0?void 0:Jn.slice(1);if(qr){if(Number(qr.match(/^([^.]+)/)[1])<Xr)throw Error(`yargs parser supports a minimum Node.js version of ${Xr}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Xa=process?process.env:{},Zr=new Hn({cwd:process.cwd,env:()=>{return Xa},format:Ua,normalize:Va,resolve:Ka,require:(t)=>{return pe(t)}}),Fo=function(e,o){return Zr.parse(e.slice(),o).argv};Fo.detailed=function(t,e){return Zr.parse(t.slice(),e)};Fo.camelCase=ke;Fo.decamelize=Qo;Fo.looksLikeNumber=Yo;var zn=Fo;import{basename as ll,dirname as fl,extname as hl,relative as ul,resolve as ri}from"path";function Qr(){if(qa())return 0;return 1}function qa(){return Za()&&!process.defaultApp}function Za(){return!!process.versions.electron}function Un(t){return t.slice(Qr()+1)}function Yr(){return process.argv[Qr()]}class ft extends Error{constructor(t){super(t||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,ft)}}import{readFileSync as Qa,statSync as Ya,writeFile as tl}from"fs";import{format as el}from"util";import{resolve as ol}from"path";var ti={fs:{readFileSync:Qa,writeFile:tl},format:el,resolve:ol,exists:(t)=>{try{return Ya(t).isFile()}catch(e){return!1}}};var Zt;class ei{constructor(t){t=t||{},this.directory=t.directory||"./locales",this.updateFiles=typeof t.updateFiles==="boolean"?t.updateFiles:!0,this.locale=t.locale||"en",this.fallbackToLanguage=typeof t.fallbackToLanguage==="boolean"?t.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...t){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let e=t.shift(),o=function(){};if(typeof t[t.length-1]==="function")o=t.pop();if(o=o||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]=e,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();return Zt.format.apply(Zt.format,[this.cache[this.locale][e]||e].concat(t))}__n(){let t=Array.prototype.slice.call(arguments),e=t.shift(),o=t.shift(),n=t.shift(),r=function(){};if(typeof t[t.length-1]==="function")r=t.pop();if(!this.cache[this.locale])this._readLocaleFile();let i=n===1?e:o;if(this.cache[this.locale][e])i=this.cache[this.locale][e][n===1?"one":"other"];if(!this.cache[this.locale][e]&&this.updateFiles)this.cache[this.locale][e]={one:e,other:o},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let s=[i];if(~i.indexOf("%d"))s.push(n);return Zt.format.apply(Zt.format,s.concat(t))}setLocale(t){this.locale=t}getLocale(){return this.locale}updateLocale(t){if(!this.cache[this.locale])this._readLocaleFile();for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))this.cache[this.locale][e]=t[e]}_taggedLiteral(t,...e){let o="";return t.forEach(function(n,r){let i=e[r+1];if(o+=n,typeof i<"u")o+="%s"}),this.__.apply(this,[o].concat([].slice.call(e,1)))}_enqueueWrite(t){if(this.writeQueue.push(t),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let t=this,e=this.writeQueue[0],o=e.directory,n=e.locale,r=e.cb,i=this._resolveLocaleFile(o,n),s=JSON.stringify(this.cache[n],null,2);Zt.fs.writeFile(i,s,"utf-8",function(c){if(t.writeQueue.shift(),t.writeQueue.length>0)t._processWriteQueue();r(c)})}_readLocaleFile(){let t={},e=this._resolveLocaleFile(this.directory,this.locale);try{if(Zt.fs.readFileSync)t=JSON.parse(Zt.fs.readFileSync(e,"utf-8"))}catch(o){if(o instanceof SyntaxError)o.message="syntax error in "+e;if(o.code==="ENOENT")t={};else throw o}this.cache[this.locale]=t}_resolveLocaleFile(t,e){let o=Zt.resolve(t,"./",e+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(o)&&~e.lastIndexOf("_")){let n=Zt.resolve(t,"./",e.split("_")[0]+".json");if(this._fileExistsSync(n))o=n}return o}_fileExistsSync(t){return Zt.exists(t)}}function oi(t,e){Zt=e;let o=new ei(t);return{__:o.__.bind(o),__n:o.__n.bind(o),setLocale:o.setLocale.bind(o),getLocale:o.getLocale.bind(o),updateLocale:o.updateLocale.bind(o),locale:o.locale}}var nl=(t)=>{return oi(t,ti)},ni=nl;var pl="require is not supported by ESM",ii="loading a directory of commands is not supported yet for ESM",Bo;try{Bo=al(import.meta.url)}catch(t){Bo=process.cwd()}var dl=Bo.substring(0,Bo.lastIndexOf("node_modules")),Vn={assert:{notStrictEqual:rl,strictEqual:il},cliui:Tn,findUp:Gn,getEnv:(t)=>{return process.env[t]},inspect:sl,getCallerFile:()=>{throw new ft(ii)},getProcessArgvBin:Yr,mainFilename:dl||process.cwd(),Parser:zn,path:{basename:ll,dirname:fl,extname:hl,relative:ul,resolve:ri},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:process.exit,nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:cl,require:()=>{throw new ft(pl)},requireDirectory:()=>{throw new ft(ii)},stringWidth:(t)=>{return[...t].length},y18n:ni({directory:ri(Bo,"../../../locales"),updateFiles:!1})};function Bt(t,e,o,n){o.assert.notStrictEqual(t,e,n)}function Kn(t,e){e.assert.strictEqual(typeof t,"string")}function co(t){return Object.keys(t)}function ht(t){return!!t&&!!t.then&&typeof t.then==="function"}function ye(t){let o=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),n=/\.*[\][<>]/g,r=o.shift();if(!r)throw Error(`No command found in: ${t}`);let i={cmd:r.replace(n,""),demanded:[],optional:[]};return o.forEach((s,c)=>{let l=!1;if(s=s.replace(/\s/g,""),/\.+[\]>]/.test(s)&&c===o.length-1)l=!0;if(/^\[/.test(s))i.optional.push({cmd:s.replace(n,"").split("|"),variadic:l});else i.demanded.push({cmd:s.replace(n,"").split("|"),variadic:l})}),i}var ml=["first","second","third","fourth","fifth","sixth"];function _(t,e,o){function n(){return typeof t==="object"?[{demanded:[],optional:[]},t,e]:[ye(`cmd ${t}`),e,o]}try{let r=0,[i,s,c]=n(),l=[].slice.call(s);while(l.length&&l[l.length-1]===void 0)l.pop();let a=c||l.length;if(a<i.demanded.length)throw new ft(`Not enough arguments provided. Expected ${i.demanded.length} but received ${l.length}.`);let h=i.demanded.length+i.optional.length;if(a>h)throw new ft(`Too many arguments provided. Expected max ${h} but received ${a}.`);i.demanded.forEach((u)=>{let d=l.shift(),g=si(d);if(u.cmd.filter((m)=>m===g||m==="*").length===0)ci(g,u.cmd,r);r+=1}),i.optional.forEach((u)=>{if(l.length===0)return;let d=l.shift(),g=si(d);if(u.cmd.filter((m)=>m===g||m==="*").length===0)ci(g,u.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function si(t){if(Array.isArray(t))return"array";else if(t===null)return"null";return typeof t}function ci(t,e,o){throw new ft(`Invalid ${ml[o]||"manyith"} argument. Expected ${e.join(" or ")} but received ${t}.`)}class Xn{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,o=!0,n=!1){if(_("<array|function> [boolean] [boolean] [boolean]",[t,e,o],arguments.length),Array.isArray(t)){for(let r=0;r<t.length;r++){if(typeof t[r]!=="function")throw Error("middleware must be a function");let i=t[r];i.applyBeforeValidation=e,i.global=o}Array.prototype.push.apply(this.globalMiddleware,t)}else if(typeof t==="function"){let r=t;r.applyBeforeValidation=e,r.global=o,r.mutates=n,this.globalMiddleware.push(t)}return this.yargs}addCoerceMiddleware(t,e){let o=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((n)=>{let r=[...o[e]||[],e];if(!n.option)return!0;else return!r.includes(n.option)}),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let t=this.frozens.pop();if(t!==void 0)this.globalMiddleware=t}reset(){this.globalMiddleware=this.globalMiddleware.filter((t)=>t.global)}}function ai(t){if(!t)return[];return t.map((e)=>{return e.applyBeforeValidation=!1,e})}function Ne(t,e,o,n){return o.reduce((r,i)=>{if(i.applyBeforeValidation!==n)return r;if(i.mutates){if(i.applied)return r;i.applied=!0}if(ht(r))return r.then((s)=>Promise.all([s,i(s,e)])).then(([s,c])=>Object.assign(s,c));else{let s=i(r,e);return ht(s)?s.then((c)=>Object.assign(r,c)):Object.assign(r,s)}},t)}function Je(t,e,o=(n)=>{throw n}){try{let n=xl(t)?t():t;return ht(n)?n.then((r)=>e(r)):e(n)}catch(n){return o(n)}}function xl(t){return typeof t==="function"}function qn(t){for(let e=0,o=Object.keys(pe.cache),n;e<o.length;e++)if(n=pe.cache[o[e]],n.exports===t)return n;return null}var ao=/(^\*)|(^\$0)/;class fi{constructor(t,e,o,n){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=n,this.usage=t,this.globalMiddleware=o,this.validation=e}addDirectory(t,e,o,n){if(n=n||{},typeof n.recurse!=="boolean")n.recurse=!1;if(!Array.isArray(n.extensions))n.extensions=["js"];let r=typeof n.visit==="function"?n.visit:(i)=>i;n.visit=(i,s,c)=>{let l=r(i,s,c);if(l){if(this.requireCache.has(s))return l;else this.requireCache.add(s);this.addHandler(l)}return l},this.shim.requireDirectory({require:e,filename:o},t,n)}addHandler(t,e,o,n,r,i){let s=[],c=ai(r);if(n=n||(()=>{}),Array.isArray(t))if(gl(t))[t,...s]=t;else for(let l of t)this.addHandler(l);else if(bl(t)){let l=Array.isArray(t.command)||typeof t.command==="string"?t.command:this.moduleName(t);if(t.aliases)l=[].concat(l).concat(t.aliases);this.addHandler(l,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated);return}else if(li(o)){this.addHandler([t].concat(s),e,o.builder,o.handler,o.middlewares,o.deprecated);return}if(typeof t==="string"){let l=ye(t);s=s.map((u)=>ye(u).cmd);let a=!1,h=[l.cmd].concat(s).filter((u)=>{if(ao.test(u))return a=!0,!1;return!0});if(h.length===0&&a)h.push("$0");if(a)l.cmd=h[0],s=h.slice(1),t=t.replace(ao,l.cmd);if(s.forEach((u)=>{this.aliasMap[u]=l.cmd}),e!==!1)this.usage.command(t,e,a,s,i);if(this.handlers[l.cmd]={original:t,description:e,handler:n,builder:o||{},middlewares:c,deprecated:i,demanded:l.demanded,optional:l.optional},a)this.defaultCommand=this.handlers[l.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,o,n,r,i){let s=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,c=e.getInternalMethods().getContext(),l=c.commands.slice(),a=!t;if(t)c.commands.push(t),c.fullCommands.push(s.original);let h=this.applyBuilderUpdateUsageAndParse(a,s,e,o.aliases,l,n,r,i);return ht(h)?h.then((u)=>this.applyMiddlewareAndGetResult(a,s,u.innerArgv,c,r,u.aliases,e)):this.applyMiddlewareAndGetResult(a,s,h.innerArgv,c,r,h.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,o,n,r,i,s,c){let l=e.builder,a=o;if(tn(l)){o.getInternalMethods().getUsageInstance().freeze();let h=l(o.getInternalMethods().reset(n),c);if(ht(h))return h.then((u)=>{return a=ui(u)?u:o,this.parseAndUpdateUsage(t,e,a,r,i,s)})}else if(wl(l))o.getInternalMethods().getUsageInstance().freeze(),a=o.getInternalMethods().reset(n),Object.keys(e.builder).forEach((h)=>{a.option(h,l[h])});return this.parseAndUpdateUsage(t,e,a,r,i,s)}parseAndUpdateUsage(t,e,o,n,r,i){if(t)o.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(o))o.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(n,e),e.description);let s=o.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,i);return ht(s)?s.then((c)=>({aliases:o.parsed.aliases,innerArgv:c})):{aliases:o.parsed.aliases,innerArgv:s}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&t.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(t,e){let o=ao.test(e.original)?e.original.replace(ao,"").trim():e.original,n=t.filter((r)=>{return!ao.test(r)});return n.push(o),`$0 ${n.join(" ")}`}handleValidationAndGetResult(t,e,o,n,r,i,s,c){if(!i.getInternalMethods().getHasOutput()){let l=i.getInternalMethods().runValidation(r,c,i.parsed.error,t);o=Je(o,(a)=>{return l(a),a})}if(e.handler&&!i.getInternalMethods().getHasOutput()){i.getInternalMethods().setHasOutput();let l=!!i.getOptions().configuration["populate--"];if(i.getInternalMethods().postProcess(o,l,!1,!1),o=Ne(o,i,s,!1),o=Je(o,(a)=>{let h=e.handler(a);return ht(h)?h.then(()=>a):a}),!t)i.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ht(o)&&!i.getInternalMethods().hasParseCallback())o.catch((a)=>{try{i.getInternalMethods().getUsageInstance().fail(null,a)}catch(h){}})}if(!t)n.commands.pop(),n.fullCommands.pop();return o}applyMiddlewareAndGetResult(t,e,o,n,r,i,s){let c={};if(r)return o;if(!s.getInternalMethods().getHasOutput())c=this.populatePositionals(e,o,n,s);let l=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),a=Ne(o,s,l,!0);return ht(a)?a.then((h)=>this.handleValidationAndGetResult(t,e,h,n,i,s,l,c)):this.handleValidationAndGetResult(t,e,a,n,i,s,l,c)}populatePositionals(t,e,o,n){e._=e._.slice(o.commands.length);let r=t.demanded.slice(0),i=t.optional.slice(0),s={};this.validation.positionalCount(r.length,e._.length);while(r.length){let c=r.shift();this.populatePositional(c,e,s)}while(i.length){let c=i.shift();this.populatePositional(c,e,s)}return e._=o.commands.concat(e._.map((c)=>""+c)),this.postProcessPositionals(e,s,this.cmdToParseOptions(t.original),n),s}populatePositional(t,e,o){let n=t.cmd[0];if(t.variadic)o[n]=e._.splice(0).map(String);else if(e._.length)o[n]=[String(e._.shift())]}cmdToParseOptions(t){let e={array:[],default:{},alias:{},demand:{}},o=ye(t);return o.demanded.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i,e.demand[r]=!0}),o.optional.forEach((n)=>{let[r,...i]=n.cmd;if(n.variadic)e.array.push(r),e.default[r]=[];e.alias[r]=i}),e}postProcessPositionals(t,e,o,n){let r=Object.assign({},n.getOptions());r.default=Object.assign(o.default,r.default);for(let l of Object.keys(o.alias))r.alias[l]=(r.alias[l]||[]).concat(o.alias[l]);r.array=r.array.concat(o.array),r.config={};let i=[];if(Object.keys(e).forEach((l)=>{e[l].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[l]=!0;i.push(`--${l}`),i.push(a)})}),!i.length)return;let s=Object.assign({},r.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(i,Object.assign({},r,{configuration:s}));if(c.error)n.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let l=Object.keys(e);Object.keys(e).forEach((a)=>{l.push(...c.aliases[a])}),Object.keys(c.argv).forEach((a)=>{if(l.includes(a)){if(!e[a])e[a]=c.argv[a];if(!this.isInConfigs(n,a)&&!this.isDefaulted(n,a)&&Object.prototype.hasOwnProperty.call(t,a)&&Object.prototype.hasOwnProperty.call(c.argv,a)&&(Array.isArray(t[a])||Array.isArray(c.argv[a])))t[a]=[].concat(t[a],c.argv[a]);else t[a]=c.argv[a]}})}}isDefaulted(t,e){let{default:o}=t.getOptions();return Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(e))}isInConfigs(t,e){let{configObjects:o}=t.getOptions();return o.some((n)=>Object.prototype.hasOwnProperty.call(n,e))||o.some((n)=>Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(e)))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){let o=ao.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(o,this.defaultCommand.description)}let e=this.defaultCommand.builder;if(tn(e))return e(t,!0);else if(!li(e))Object.keys(e).forEach((o)=>{t.option(o,e[o])});return}moduleName(t){let e=qn(t);if(!e)throw Error(`No command name given for module: ${this.shim.inspect(t)}`);return this.commandFromFilename(e.filename)}commandFromFilename(t){return this.shim.path.basename(t,this.shim.path.extname(t))}extractDesc({describe:t,description:e,desc:o}){for(let n of[t,e,o]){if(typeof n==="string"||n===!1)return n;Bt(n,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let t=this.frozens.pop();Bt(t,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=t}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function hi(t,e,o,n){return new fi(t,e,o,n)}function li(t){return typeof t==="object"&&!!t.builder&&typeof t.handler==="function"}function gl(t){return t.every((e)=>typeof e==="string")}function tn(t){return typeof t==="function"}function wl(t){return typeof t==="object"}function bl(t){return typeof t==="object"&&!Array.isArray(t)}function Ee(t={},e=()=>!0){let o={};return co(t).forEach((n)=>{if(e(n,t[n]))o[n]=t[n]}),o}function Re(t){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((e)=>{let o=e;if(o._handle&&o.isTTY&&typeof o._handle.setBlocking==="function")o._handle.setBlocking(t)})}function Cl(t){return typeof t==="boolean"}function di(t,e){let o=e.y18n.__,n={},r=[];n.failFn=function(D){r.push(D)};let i=null,s=null,c=!0;n.showHelpOnFail=function(D=!0,A){let[V,tt]=typeof D==="string"?[!0,D]:[D,A];if(t.getInternalMethods().isGlobalContext())s=tt;return i=tt,c=V,n};let l=!1;n.fail=function(D,A){let V=t.getInternalMethods().getLoggerInstance();if(r.length)for(let tt=r.length-1;tt>=0;--tt){let mt=r[tt];if(Cl(mt)){if(A)throw A;else if(D)throw Error(D)}else mt(D,A,n)}else{if(t.getExitProcess())Re(!0);if(!l){if(l=!0,c)t.showHelp("error"),V.error();if(D||A)V.error(D||A);let tt=i||s;if(tt){if(D||A)V.error("");V.error(tt)}}if(A=A||new ft(D),t.getExitProcess())return t.exit(1);else if(t.getInternalMethods().hasParseCallback())return t.exit(1,A);else throw A}};let a=[],h=!1;n.usage=(F,D)=>{if(F===null)return h=!0,a=[],n;return h=!1,a.push([F,D||""]),n},n.getUsage=()=>{return a},n.getUsageDisabled=()=>{return h},n.getPositionalGroupName=()=>{return o("Positionals:")};let u=[];n.example=(F,D)=>{u.push([F,D||""])};let d=[];n.command=function(D,A,V,tt,mt=!1){if(V)d=d.map((X)=>{return X[2]=!1,X});d.push([D,A||"",V,tt,mt])},n.getCommands=()=>d;let g={};n.describe=function(D,A){if(Array.isArray(D))D.forEach((V)=>{n.describe(V,A)});else if(typeof D==="object")Object.keys(D).forEach((V)=>{n.describe(V,D[V])});else g[D]=A},n.getDescriptions=()=>g;let x=[];n.epilog=(F)=>{x.push(F)};let m=!1,b;n.wrap=(F)=>{m=!0,b=F},n.getWrap=()=>{if(e.getEnv("YARGS_DISABLE_WRAP"))return null;if(!m)b=Y(),m=!0;return b};let $="__yargsString__:";n.deferY18nLookup=(F)=>$+F,n.help=function(){if(P)return P;R();let D=t.customScriptName?t.$0:e.path.basename(t.$0),A=t.getDemandedOptions(),V=t.getDemandedCommands(),tt=t.getDeprecatedOptions(),mt=t.getGroups(),X=t.getOptions(),ut=[];ut=ut.concat(Object.keys(g)),ut=ut.concat(Object.keys(A)),ut=ut.concat(Object.keys(V)),ut=ut.concat(Object.keys(X.default)),ut=ut.filter(at),ut=Object.keys(ut.reduce((B,ot)=>{if(ot!=="_")B[ot]=!0;return B},{}));let J=n.getWrap(),G=e.cliui({width:J,wrap:!!J});if(!h){if(a.length)a.forEach((B)=>{if(G.div({text:`${B[0].replace(/\$0/g,D)}`}),B[1])G.div({text:`${B[1]}`,padding:[1,0,0,0]})}),G.div();else if(d.length){let B=null;if(V._)B=`${D} <${o("command")}>
163
+ `;else B=`${D} [${o("command")}]
164
+ `;G.div(`${B}`)}}if(d.length>1||d.length===1&&!d[0][2]){G.div(o("Commands:"));let B=t.getInternalMethods().getContext(),ot=B.commands.length?`${B.commands.join(" ")} `:"";if(t.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)d=d.sort((U,Z)=>U[0].localeCompare(Z[0]));let pt=D?`${D} `:"";d.forEach((U)=>{let Z=`${pt}${ot}${U[0].replace(/^\$0 ?/,"")}`;G.span({text:Z,padding:[0,2,0,2],width:E(d,J,`${D}${ot}`)+4},{text:U[1]});let lt=[];if(U[2])lt.push(`[${o("default")}]`);if(U[3]&&U[3].length)lt.push(`[${o("aliases:")} ${U[3].join(", ")}]`);if(U[4])if(typeof U[4]==="string")lt.push(`[${o("deprecated: %s",U[4])}]`);else lt.push(`[${o("deprecated")}]`);if(lt.length)G.div({text:lt.join(" "),padding:[0,0,0,2],align:"right"});else G.div()}),G.div()}let it=(Object.keys(X.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);ut=ut.filter((B)=>!t.parsed.newAliases[B]&&it.every((ot)=>(X.alias[ot]||[]).indexOf(B)===-1));let dt=o("Options:");if(!mt[dt])mt[dt]=[];rt(ut,X.alias,mt,dt);let j=(B)=>/^--/.test(en(B)),oe=Object.keys(mt).filter((B)=>mt[B].length>0).map((B)=>{let ot=mt[B].filter(at).map((pt)=>{if(it.includes(pt))return pt;for(let U=0,Z;(Z=it[U])!==void 0;U++)if((X.alias[Z]||[]).includes(pt))return Z;return pt});return{groupName:B,normalizedKeys:ot}}).filter(({normalizedKeys:B})=>B.length>0).map(({groupName:B,normalizedKeys:ot})=>{let pt=ot.reduce((U,Z)=>{return U[Z]=[Z].concat(X.alias[Z]||[]).map((lt)=>{if(B===n.getPositionalGroupName())return lt;else return(/^[0-9]$/.test(lt)?X.boolean.includes(Z)?"-":"--":lt.length>1?"--":"-")+lt}).sort((lt,nt)=>j(lt)===j(nt)?0:j(lt)?1:-1).join(", "),U},{});return{groupName:B,normalizedKeys:ot,switches:pt}});if(oe.filter(({groupName:B})=>B!==n.getPositionalGroupName()).some(({normalizedKeys:B,switches:ot})=>!B.every((pt)=>j(ot[pt]))))oe.filter(({groupName:B})=>B!==n.getPositionalGroupName()).forEach(({normalizedKeys:B,switches:ot})=>{B.forEach((pt)=>{if(j(ot[pt]))ot[pt]=Sl(ot[pt],4)})});if(oe.forEach(({groupName:B,normalizedKeys:ot,switches:pt})=>{G.div(B),ot.forEach((U)=>{let Z=pt[U],lt=g[U]||"",nt=null;if(lt.includes($))lt=o(lt.substring($.length));if(X.boolean.includes(U))nt=`[${o("boolean")}]`;if(X.count.includes(U))nt=`[${o("count")}]`;if(X.string.includes(U))nt=`[${o("string")}]`;if(X.normalize.includes(U))nt=`[${o("string")}]`;if(X.array.includes(U))nt=`[${o("array")}]`;if(X.number.includes(U))nt=`[${o("number")}]`;let so=(W)=>typeof W==="string"?`[${o("deprecated: %s",W)}]`:`[${o("deprecated")}]`,w=[U in tt?so(tt[U]):null,nt,U in A?`[${o("required")}]`:null,X.choices&&X.choices[U]?`[${o("choices:")} ${n.stringifiedValues(X.choices[U])}]`:null,I(X.default[U],X.defaultDescription[U])].filter(Boolean).join(" ");G.span({text:en(Z),padding:[0,2,0,2+pi(Z)],width:E(pt,J)+4},lt);let S=t.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(w&&!S)G.div({text:w,padding:[0,0,0,2],align:"right"});else G.div()}),G.div()}),u.length)G.div(o("Examples:")),u.forEach((B)=>{B[0]=B[0].replace(/\$0/g,D)}),u.forEach((B)=>{if(B[1]==="")G.div({text:B[0],padding:[0,2,0,2]});else G.div({text:B[0],padding:[0,2,0,2],width:E(u,J)+4},{text:B[1]})}),G.div();if(x.length>0){let B=x.map((ot)=>ot.replace(/\$0/g,D)).join(`
165
+ `);G.div(`${B}
166
+ `)}return G.toString().replace(/\s*$/,"")};function E(F,D,A){let V=0;if(!Array.isArray(F))F=Object.values(F).map((tt)=>[tt]);if(F.forEach((tt)=>{V=Math.max(e.stringWidth(A?`${A} ${en(tt[0])}`:en(tt[0]))+pi(tt[0]),V)}),D)V=Math.min(V,parseInt((D*0.5).toString(),10));return V}function R(){let F=t.getDemandedOptions(),D=t.getOptions();(Object.keys(D.alias)||[]).forEach((A)=>{D.alias[A].forEach((V)=>{if(g[V])n.describe(A,g[V]);if(V in F)t.demandOption(A,F[V]);if(D.boolean.includes(V))t.boolean(A);if(D.count.includes(V))t.count(A);if(D.string.includes(V))t.string(A);if(D.normalize.includes(V))t.normalize(A);if(D.array.includes(V))t.array(A);if(D.number.includes(V))t.number(A)})})}let P;n.cacheHelpMessage=function(){P=this.help()},n.clearCachedHelpMessage=function(){P=void 0},n.hasCachedHelpMessage=function(){return!!P};function rt(F,D,A,V){let tt=[],mt=null;return Object.keys(A).forEach((X)=>{tt=tt.concat(A[X])}),F.forEach((X)=>{if(mt=[X].concat(D[X]),!mt.some((ut)=>tt.indexOf(ut)!==-1))A[V].push(X)}),tt}function at(F){return t.getOptions().hiddenOptions.indexOf(F)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}n.showHelp=(F)=>{let D=t.getInternalMethods().getLoggerInstance();if(!F)F="error";(typeof F==="function"?F:D[F])(n.help())},n.functionDescription=(F)=>{return["(",F.name?e.Parser.decamelize(F.name,"-"):o("generated-value"),")"].join("")},n.stringifiedValues=function(D,A){let V="",tt=A||", ",mt=[].concat(D);if(!D||!mt.length)return V;return mt.forEach((X)=>{if(V.length)V+=tt;V+=JSON.stringify(X)}),V};function I(F,D){let A=`[${o("default:")} `;if(F===void 0&&!D)return null;if(D)A+=D;else switch(typeof F){case"string":A+=`"${F}"`;break;case"object":A+=JSON.stringify(F);break;default:A+=F}return`${A}]`}function Y(){if(e.process.stdColumns)return Math.min(80,e.process.stdColumns);else return 80}let et=null;n.version=(F)=>{et=F},n.showVersion=(F)=>{let D=t.getInternalMethods().getLoggerInstance();if(!F)F="error";(typeof F==="function"?F:D[F])(et)},n.reset=function(D){return i=null,l=!1,a=[],h=!1,x=[],u=[],d=[],g=Ee(g,(A)=>!D[A]),n};let It=[];return n.freeze=function(){It.push({failMessage:i,failureOutput:l,usages:a,usageDisabled:h,epilogs:x,examples:u,commands:d,descriptions:g})},n.unfreeze=function(D=!1){let A=It.pop();if(!A)return;if(D)g={...A.descriptions,...g},d=[...A.commands,...d],a=[...A.usages,...a],u=[...A.examples,...u],x=[...A.epilogs,...x];else({failMessage:i,failureOutput:l,usages:a,usageDisabled:h,epilogs:x,examples:u,commands:d,descriptions:g}=A)},n}function Zn(t){return typeof t==="object"}function Sl(t,e){return Zn(t)?{text:t.text,indentation:t.indentation+e}:{text:t,indentation:e}}function pi(t){return Zn(t)?t.indentation:0}function en(t){return Zn(t)?t.text:t}var mi=`###-begin-{{app_name}}-completions-###
168
167
  #
169
168
  # yargs command completion script
170
169
  #
@@ -192,7 +191,7 @@ _{{app_name}}_yargs_completions()
192
191
  }
193
192
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
194
193
  ###-end-{{app_name}}-completions-###
195
- `,ui=`#compdef {{app_name}}
194
+ `,xi=`#compdef {{app_name}}
196
195
  ###-begin-{{app_name}}-completions-###
197
196
  #
198
197
  # yargs command completion script
@@ -211,11 +210,11 @@ _{{app_name}}_yargs_completions()
211
210
  }
212
211
  compdef _{{app_name}}_yargs_completions {{app_name}}
213
212
  ###-end-{{app_name}}-completions-###
214
- `;class pi{constructor(t,e,o,n){var r,i,s;this.yargs=t,this.usage=e,this.command=o,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(s=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((i=this.shim.getEnv("ZSH_NAME"))===null||i===void 0?void 0:i.includes("zsh")))!==null&&s!==void 0?s:!1}defaultCompletion(t,e,o,n){let r=this.command.getCommandHandlers();for(let s=0,c=t.length;s<c;++s)if(r[t[s]]&&r[t[s]].builder){let f=r[t[s]].builder;if(Xo(f)){this.indexAfterLastReset=s+1;let a=this.yargs.getInternalMethods().reset();return f(a,!0),a.argv}}let i=[];this.commandCompletions(i,t,o),this.optionCompletions(i,t,e,o),this.choicesFromOptionsCompletions(i,t,e,o),this.choicesFromPositionalsCompletions(i,t,e,o),n(null,i)}commandCompletions(t,e,o){let n=this.yargs.getInternalMethods().getContext().commands;if(!o.match(/^-/)&&n[n.length-1]!==o&&!this.previousArgHasChoices(e))this.usage.getCommands().forEach((r)=>{let i=Pe(r[0]).cmd;if(e.indexOf(i)===-1)if(!this.zshShell)t.push(i);else{let s=r[1]||"";t.push(i.replace(/:/g,"\\:")+":"+s)}})}optionCompletions(t,e,o,n){if((n.match(/^-/)||n===""&&t.length===0)&&!this.previousArgHasChoices(e)){let r=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((s)=>{let c=!!r.configuration["boolean-negation"]&&r.boolean.includes(s);if(!i.includes(s)&&!r.hiddenOptions.includes(s)&&!this.argsContainKey(e,s,c))this.completeOptionKey(s,t,n,c&&!!r.default[s])})}}choicesFromOptionsCompletions(t,e,o,n){if(this.previousArgHasChoices(e)){let r=this.getPreviousArgChoices(e);if(r&&r.length>0)t.push(...r.map((i)=>i.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(t,e,o,n){if(n===""&&t.length>0&&this.previousArgHasChoices(e))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],i=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),s=r[o._.length-i-1];if(!s)return;let c=this.yargs.getOptions().choices[s]||[];for(let f of c)if(f.startsWith(n))t.push(f.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],o="";if(!e.startsWith("-")&&t.length>1)o=e,e=t[t.length-2];if(!e.startsWith("-"))return;let n=e.replace(/^-+/,""),r=this.yargs.getOptions(),i=[n,...this.yargs.getAliases()[n]||[]],s;for(let c of i)if(Object.prototype.hasOwnProperty.call(r.key,c)&&Array.isArray(r.choices[c])){s=r.choices[c];break}if(s)return s.filter((c)=>!o||c.startsWith(o))}previousArgHasChoices(t){let e=this.getPreviousArgChoices(t);return e!==void 0&&e.length>0}argsContainKey(t,e,o){let n=(r)=>t.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(n(e))return!0;if(o&&n(`no-${e}`))return!0;if(this.aliases){for(let r of this.aliases[e])if(n(r))return!0}return!1}completeOptionKey(t,e,o,n){var r,i,s,c;let f=t;if(this.zshShell){let d=this.usage.getDescriptions(),g=(i=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[t])===null||i===void 0?void 0:i.find((b)=>{let S=d[b];return typeof S==="string"&&S.length>0}),x=g?d[g]:void 0,m=(c=(s=d[t])!==null&&s!==void 0?s:x)!==null&&c!==void 0?c:"";f=`${t.replace(/:/g,"\\:")}:${m.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let a=(d)=>/^--/.test(d),h=(d)=>/^[^0-9]$/.test(d),u=!a(o)&&h(t)?"-":"--";if(e.push(u+f),n)e.push(u+"no-"+f)}customCompletion(t,e,o,n){if(Bt(this.customCompletionFunction,null,this.shim),wf(this.customCompletionFunction)){let r=this.customCompletionFunction(o,e);if(ht(r))return r.then((i)=>{this.shim.process.nextTick(()=>{n(null,i)})}).catch((i)=>{this.shim.process.nextTick(()=>{n(i,void 0)})});return n(null,r)}else if(bf(this.customCompletionFunction))return this.customCompletionFunction(o,e,(r=n)=>this.defaultCompletion(t,e,o,r),(r)=>{n(null,r)});else return this.customCompletionFunction(o,e,(r)=>{n(null,r)})}getCompletion(t,e){let o=t.length?t[t.length-1]:"",n=this.yargs.parse(t,!0),r=this.customCompletionFunction?(i)=>this.customCompletion(t,i,o,e):(i)=>this.defaultCompletion(t,i,o,e);return ht(n)?n.then(r):r(n)}generateCompletionScript(t,e){let o=this.zshShell?ui:hi,n=this.shim.path.basename(t);if(t.match(/\.js$/))t=`./${t}`;return o=o.replace(/{{app_name}}/g,n),o=o.replace(/{{completion_command}}/g,e),o.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function di(t,e,o,n){return new pi(t,e,o,n)}function wf(t){return t.length<3}function bf(t){return t.length>3}function mi(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let o=[],n;for(n=0;n<=e.length;n++)o[n]=[n];let r;for(r=0;r<=t.length;r++)o[0][r]=r;for(n=1;n<=e.length;n++)for(r=1;r<=t.length;r++)if(e.charAt(n-1)===t.charAt(r-1))o[n][r]=o[n-1][r-1];else if(n>1&&r>1&&e.charAt(n-2)===t.charAt(r-1)&&e.charAt(n-1)===t.charAt(r-2))o[n][r]=o[n-2][r-2]+1;else o[n][r]=Math.min(o[n-1][r-1]+1,Math.min(o[n][r-1]+1,o[n-1][r]+1));return o[e.length][t.length]}var xi=["$0","--","_"];function gi(t,e,o){let n=o.y18n.__,r=o.y18n.__n,i={};i.nonOptionCount=function(u){let d=t.getDemandedCommands(),x=u._.length+(u["--"]?u["--"].length:0)-t.getInternalMethods().getContext().commands.length;if(d._&&(x<d._.min||x>d._.max)){if(x<d._.min)if(d._.minMsg!==void 0)e.fail(d._.minMsg?d._.minMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.min.toString()):null);else e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",x,x.toString(),d._.min.toString()));else if(x>d._.max)if(d._.maxMsg!==void 0)e.fail(d._.maxMsg?d._.maxMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.max.toString()):null);else e.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",x,x.toString(),d._.max.toString()))}},i.positionalCount=function(u,d){if(d<u)e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",d,d+"",u+""))},i.requiredArguments=function(u,d){let g=null;for(let x of Object.keys(d))if(!Object.prototype.hasOwnProperty.call(u,x)||typeof u[x]>"u")g=g||{},g[x]=d[x];if(g){let x=[];for(let b of Object.keys(g)){let S=g[b];if(S&&x.indexOf(S)<0)x.push(S)}let m=x.length?`
213
+ `;class gi{constructor(t,e,o,n){var r,i,s;this.yargs=t,this.usage=e,this.command=o,this.shim=n,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(s=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((i=this.shim.getEnv("ZSH_NAME"))===null||i===void 0?void 0:i.includes("zsh")))!==null&&s!==void 0?s:!1}defaultCompletion(t,e,o,n){let r=this.command.getCommandHandlers();for(let s=0,c=t.length;s<c;++s)if(r[t[s]]&&r[t[s]].builder){let l=r[t[s]].builder;if(tn(l)){this.indexAfterLastReset=s+1;let a=this.yargs.getInternalMethods().reset();return l(a,!0),a.argv}}let i=[];this.commandCompletions(i,t,o),this.optionCompletions(i,t,e,o),this.choicesFromOptionsCompletions(i,t,e,o),this.choicesFromPositionalsCompletions(i,t,e,o),n(null,i)}commandCompletions(t,e,o){let n=this.yargs.getInternalMethods().getContext().commands;if(!o.match(/^-/)&&n[n.length-1]!==o&&!this.previousArgHasChoices(e))this.usage.getCommands().forEach((r)=>{let i=ye(r[0]).cmd;if(e.indexOf(i)===-1)if(!this.zshShell)t.push(i);else{let s=r[1]||"";t.push(i.replace(/:/g,"\\:")+":"+s)}})}optionCompletions(t,e,o,n){if((n.match(/^-/)||n===""&&t.length===0)&&!this.previousArgHasChoices(e)){let r=this.yargs.getOptions(),i=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((s)=>{let c=!!r.configuration["boolean-negation"]&&r.boolean.includes(s);if(!i.includes(s)&&!r.hiddenOptions.includes(s)&&!this.argsContainKey(e,s,c))this.completeOptionKey(s,t,n,c&&!!r.default[s])})}}choicesFromOptionsCompletions(t,e,o,n){if(this.previousArgHasChoices(e)){let r=this.getPreviousArgChoices(e);if(r&&r.length>0)t.push(...r.map((i)=>i.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(t,e,o,n){if(n===""&&t.length>0&&this.previousArgHasChoices(e))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],i=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),s=r[o._.length-i-1];if(!s)return;let c=this.yargs.getOptions().choices[s]||[];for(let l of c)if(l.startsWith(n))t.push(l.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],o="";if(!e.startsWith("-")&&t.length>1)o=e,e=t[t.length-2];if(!e.startsWith("-"))return;let n=e.replace(/^-+/,""),r=this.yargs.getOptions(),i=[n,...this.yargs.getAliases()[n]||[]],s;for(let c of i)if(Object.prototype.hasOwnProperty.call(r.key,c)&&Array.isArray(r.choices[c])){s=r.choices[c];break}if(s)return s.filter((c)=>!o||c.startsWith(o))}previousArgHasChoices(t){let e=this.getPreviousArgChoices(t);return e!==void 0&&e.length>0}argsContainKey(t,e,o){let n=(r)=>t.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(n(e))return!0;if(o&&n(`no-${e}`))return!0;if(this.aliases){for(let r of this.aliases[e])if(n(r))return!0}return!1}completeOptionKey(t,e,o,n){var r,i,s,c;let l=t;if(this.zshShell){let d=this.usage.getDescriptions(),g=(i=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[t])===null||i===void 0?void 0:i.find((b)=>{let $=d[b];return typeof $==="string"&&$.length>0}),x=g?d[g]:void 0,m=(c=(s=d[t])!==null&&s!==void 0?s:x)!==null&&c!==void 0?c:"";l=`${t.replace(/:/g,"\\:")}:${m.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let a=(d)=>/^--/.test(d),h=(d)=>/^[^0-9]$/.test(d),u=!a(o)&&h(t)?"-":"--";if(e.push(u+l),n)e.push(u+"no-"+l)}customCompletion(t,e,o,n){if(Bt(this.customCompletionFunction,null,this.shim),Pl(this.customCompletionFunction)){let r=this.customCompletionFunction(o,e);if(ht(r))return r.then((i)=>{this.shim.process.nextTick(()=>{n(null,i)})}).catch((i)=>{this.shim.process.nextTick(()=>{n(i,void 0)})});return n(null,r)}else if(yl(this.customCompletionFunction))return this.customCompletionFunction(o,e,(r=n)=>this.defaultCompletion(t,e,o,r),(r)=>{n(null,r)});else return this.customCompletionFunction(o,e,(r)=>{n(null,r)})}getCompletion(t,e){let o=t.length?t[t.length-1]:"",n=this.yargs.parse(t,!0),r=this.customCompletionFunction?(i)=>this.customCompletion(t,i,o,e):(i)=>this.defaultCompletion(t,i,o,e);return ht(n)?n.then(r):r(n)}generateCompletionScript(t,e){let o=this.zshShell?xi:mi,n=this.shim.path.basename(t);if(t.match(/\.js$/))t=`./${t}`;return o=o.replace(/{{app_name}}/g,n),o=o.replace(/{{completion_command}}/g,e),o.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function wi(t,e,o,n){return new gi(t,e,o,n)}function Pl(t){return t.length<3}function yl(t){return t.length>3}function bi(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let o=[],n;for(n=0;n<=e.length;n++)o[n]=[n];let r;for(r=0;r<=t.length;r++)o[0][r]=r;for(n=1;n<=e.length;n++)for(r=1;r<=t.length;r++)if(e.charAt(n-1)===t.charAt(r-1))o[n][r]=o[n-1][r-1];else if(n>1&&r>1&&e.charAt(n-2)===t.charAt(r-1)&&e.charAt(n-1)===t.charAt(r-2))o[n][r]=o[n-2][r-2]+1;else o[n][r]=Math.min(o[n-1][r-1]+1,Math.min(o[n][r-1]+1,o[n-1][r]+1));return o[e.length][t.length]}var Ci=["$0","--","_"];function Si(t,e,o){let n=o.y18n.__,r=o.y18n.__n,i={};i.nonOptionCount=function(u){let d=t.getDemandedCommands(),x=u._.length+(u["--"]?u["--"].length:0)-t.getInternalMethods().getContext().commands.length;if(d._&&(x<d._.min||x>d._.max)){if(x<d._.min)if(d._.minMsg!==void 0)e.fail(d._.minMsg?d._.minMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.min.toString()):null);else e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",x,x.toString(),d._.min.toString()));else if(x>d._.max)if(d._.maxMsg!==void 0)e.fail(d._.maxMsg?d._.maxMsg.replace(/\$0/g,x.toString()).replace(/\$1/,d._.max.toString()):null);else e.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",x,x.toString(),d._.max.toString()))}},i.positionalCount=function(u,d){if(d<u)e.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",d,d+"",u+""))},i.requiredArguments=function(u,d){let g=null;for(let x of Object.keys(d))if(!Object.prototype.hasOwnProperty.call(u,x)||typeof u[x]>"u")g=g||{},g[x]=d[x];if(g){let x=[];for(let b of Object.keys(g)){let $=g[b];if($&&x.indexOf($)<0)x.push($)}let m=x.length?`
215
214
  ${x.join(`
216
- `)}`:"";e.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(g).length,Object.keys(g).join(", ")+m))}},i.unknownArguments=function(u,d,g,x,m=!0){var b;let S=t.getInternalMethods().getCommandInstance().getCommands(),E=[],y=t.getInternalMethods().getContext();if(Object.keys(u).forEach((R)=>{if(!xi.includes(R)&&!Object.prototype.hasOwnProperty.call(g,R)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),R)&&!i.isValidAndSomeAliasIsNotNew(R,d))E.push(R)}),m&&(y.commands.length>0||S.length>0||x))u._.slice(y.commands.length).forEach((R)=>{if(!S.includes(""+R))E.push(""+R)});if(m){let it=((b=t.getDemandedCommands()._)===null||b===void 0?void 0:b.max)||0,st=y.commands.length+it;if(st<u._.length)u._.slice(st).forEach((G)=>{if(G=String(G),!y.commands.includes(G)&&!E.includes(G))E.push(G)})}if(E.length)e.fail(r("Unknown argument: %s","Unknown arguments: %s",E.length,E.map((R)=>R.trim()?R:`"${R}"`).join(", ")))},i.unknownCommands=function(u){let d=t.getInternalMethods().getCommandInstance().getCommands(),g=[],x=t.getInternalMethods().getContext();if(x.commands.length>0||d.length>0)u._.slice(x.commands.length).forEach((m)=>{if(!d.includes(""+m))g.push(""+m)});if(g.length>0)return e.fail(r("Unknown command: %s","Unknown commands: %s",g.length,g.join(", "))),!0;else return!1},i.isValidAndSomeAliasIsNotNew=function(u,d){if(!Object.prototype.hasOwnProperty.call(d,u))return!1;let g=t.parsed.newAliases;return[u,...d[u]].some((x)=>!Object.prototype.hasOwnProperty.call(g,x)||!g[u])},i.limitedChoices=function(u){let d=t.getOptions(),g={};if(!Object.keys(d.choices).length)return;Object.keys(u).forEach((b)=>{if(xi.indexOf(b)===-1&&Object.prototype.hasOwnProperty.call(d.choices,b))[].concat(u[b]).forEach((S)=>{if(d.choices[b].indexOf(S)===-1&&S!==void 0)g[b]=(g[b]||[]).concat(S)})});let x=Object.keys(g);if(!x.length)return;let m=n("Invalid values:");x.forEach((b)=>{m+=`
217
- ${n("Argument: %s, Given: %s, Choices: %s",b,e.stringifiedValues(g[b]),e.stringifiedValues(d.choices[b]))}`}),e.fail(m)};let s={};i.implies=function(u,d){if(I("<string|object> [array|number|string]",[u,d],arguments.length),typeof u==="object")Object.keys(u).forEach((g)=>{i.implies(g,u[g])});else{if(t.global(u),!s[u])s[u]=[];if(Array.isArray(d))d.forEach((g)=>i.implies(u,g));else Bt(d,void 0,o),s[u].push(d)}},i.getImplied=function(){return s};function c(h,u){let d=Number(u);if(u=isNaN(d)?u:d,typeof u==="number")u=h._.length>=u;else if(u.match(/^--no-.+/))u=u.match(/^--no-(.+)/)[1],u=!Object.prototype.hasOwnProperty.call(h,u);else u=Object.prototype.hasOwnProperty.call(h,u);return u}i.implications=function(u){let d=[];if(Object.keys(s).forEach((g)=>{let x=g;(s[g]||[]).forEach((m)=>{let b=x,S=m;if(b=c(u,b),m=c(u,m),b&&!m)d.push(` ${x} -> ${S}`)})}),d.length){let g=`${n("Implications failed:")}
218
- `;d.forEach((x)=>{g+=x}),e.fail(g)}};let f={};i.conflicts=function(u,d){if(I("<string|object> [array|string]",[u,d],arguments.length),typeof u==="object")Object.keys(u).forEach((g)=>{i.conflicts(g,u[g])});else{if(t.global(u),!f[u])f[u]=[];if(Array.isArray(d))d.forEach((g)=>i.conflicts(u,g));else f[u].push(d)}},i.getConflicting=()=>f,i.conflicting=function(u){if(Object.keys(u).forEach((d)=>{if(f[d])f[d].forEach((g)=>{if(g&&u[d]!==void 0&&u[g]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})}),t.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(f).forEach((d)=>{f[d].forEach((g)=>{if(g&&u[o.Parser.camelCase(d)]!==void 0&&u[o.Parser.camelCase(g)]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})})},i.recommendCommands=function(u,d){d=d.sort((b,S)=>S.length-b.length);let x=null,m=1/0;for(let b=0,S;(S=d[b])!==void 0;b++){let E=mi(u,S);if(E<=3&&E<m)m=E,x=S}if(x)e.fail(n("Did you mean %s?",x))},i.reset=function(u){return s=ye(s,(d)=>!u[d]),f=ye(f,(d)=>!u[d]),i};let a=[];return i.freeze=function(){a.push({implied:s,conflicting:f})},i.unfreeze=function(){let u=a.pop();Bt(u,void 0,o),{implied:s,conflicting:f}=u},i}var qn=[],Do;function Fo(t,e,o,n){Do=n;let r={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if(typeof t.extends!=="string")return r;let i=/\.json|\..*rc$/.test(t.extends),s=null;if(!i)try{s=he.resolve(t.extends)}catch(c){return t}else s=$f(e,t.extends);Cf(s),qn.push(s),r=i?JSON.parse(Do.readFileSync(s,"utf8")):he(t.extends),delete t.extends,r=Fo(r,Do.path.dirname(s),o,Do)}return qn=[],o?wi(r,t):Object.assign({},r,t)}function Cf(t){if(qn.indexOf(t)>-1)throw new lt(`Circular extended configurations: '${t}'.`)}function $f(t,e){return Do.path.resolve(t,e)}function wi(t,e){let o={};function n(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(o,t);for(let r of Object.keys(e))if(n(e[r])&&n(o[r]))o[r]=wi(t[r],e[r]);else o[r]=e[r];return o}var j=function(t,e,o,n,r){if(n==="m")throw TypeError("Private method is not writable");if(n==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof e==="function"?t!==e||!r:!e.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(t,o):r?r.value=o:e.set(t,o),o},p=function(t,e,o,n){if(o==="a"&&!n)throw TypeError("Private accessor was defined without a getter");if(typeof e==="function"?t!==e||!n:!e.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?n:o==="a"?n.call(t):n?n.value:e.get(t)},bt,ke,Bo,kt,jt,Qo,Re,ze,Yo,zt,tn,vt,oe,_t,Ut,en,ao,yt,J,on,nn,Tt,ve,fo,Ue,Me,rn,K,Ve,Ke,qe,X,sn,ne,gt;function Ti(t){return(e=[],o=t.process.cwd(),n)=>{let r=new Gi(e,o,n,t);return Object.defineProperty(r,"argv",{get:()=>{return r.parse()},enumerable:!0}),r.help(),r.version(),r}}var bi=Symbol("copyDoubleDash"),Ci=Symbol("copyDoubleDash"),Xn=Symbol("deleteFromParserHintObject"),$i=Symbol("emitWarning"),Si=Symbol("freeze"),Pi=Symbol("getDollarZero"),Xe=Symbol("getParserConfiguration"),yi=Symbol("getUsageConfiguration"),Zn=Symbol("guessLocale"),Ei=Symbol("guessVersion"),Ri=Symbol("parsePositionalNumbers"),Qn=Symbol("pkgUp"),Oe=Symbol("populateParserHintArray"),lo=Symbol("populateParserHintSingleValueDictionary"),Yn=Symbol("populateParserHintArrayDictionary"),tr=Symbol("populateParserHintDictionary"),er=Symbol("sanitizeKey"),or=Symbol("setKey"),nr=Symbol("unfreeze"),Mi=Symbol("validateAsync"),Oi=Symbol("getCommandInstance"),Wi=Symbol("getContext"),Di=Symbol("getHasOutput"),Fi=Symbol("getLoggerInstance"),Bi=Symbol("getParseContext"),Li=Symbol("getUsageInstance"),Ai=Symbol("getValidationInstance"),cn=Symbol("hasParseCallback"),Ii=Symbol("isGlobalContext"),Ze=Symbol("postProcess"),ji=Symbol("rebase"),rr=Symbol("reset"),Lo=Symbol("runYargsParserAndExecuteCommands"),ir=Symbol("runValidation"),_i=Symbol("setHasOutput"),Qe=Symbol("kTrackManuallySetKeys");class Gi{constructor(t=[],e,o,n){this.customScriptName=!1,this.parsed=!1,bt.set(this,void 0),ke.set(this,void 0),Bo.set(this,{commands:[],fullCommands:[]}),kt.set(this,null),jt.set(this,null),Qo.set(this,"show-hidden"),Re.set(this,null),ze.set(this,!0),Yo.set(this,{}),zt.set(this,!0),tn.set(this,[]),vt.set(this,void 0),oe.set(this,{}),_t.set(this,!1),Ut.set(this,null),en.set(this,!0),ao.set(this,void 0),yt.set(this,""),J.set(this,void 0),on.set(this,void 0),nn.set(this,{}),Tt.set(this,null),ve.set(this,null),fo.set(this,{}),Ue.set(this,{}),Me.set(this,void 0),rn.set(this,!1),K.set(this,void 0),Ve.set(this,!1),Ke.set(this,!1),qe.set(this,!1),X.set(this,void 0),sn.set(this,{}),ne.set(this,null),gt.set(this,void 0),j(this,K,n,"f"),j(this,Me,t,"f"),j(this,ke,e,"f"),j(this,on,o,"f"),j(this,vt,new Un(this),"f"),this.$0=this[Pi](),this[rr](),j(this,bt,p(this,bt,"f"),"f"),j(this,X,p(this,X,"f"),"f"),j(this,gt,p(this,gt,"f"),"f"),j(this,J,p(this,J,"f"),"f"),p(this,J,"f").showHiddenOpt=p(this,Qo,"f"),j(this,ao,this[Ci](),"f")}addHelpOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),p(this,Ut,"f"))this[Xn](p(this,Ut,"f")),j(this,Ut,null,"f");if(t===!1&&e===void 0)return this;return j(this,Ut,typeof t==="string"?t:"help","f"),this.boolean(p(this,Ut,"f")),this.describe(p(this,Ut,"f"),e||p(this,X,"f").deferY18nLookup("Show help")),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(I("[string|boolean] [string]",[t,e],arguments.length),t===!1&&e===void 0)return this;let o=typeof t==="string"?t:p(this,Qo,"f");return this.boolean(o),this.describe(o,e||p(this,X,"f").deferY18nLookup("Show hidden options")),p(this,J,"f").showHiddenOpt=o,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Yn](this.alias.bind(this),"alias",t,e),this}array(t){return I("<array|string>",[t],arguments.length),this[Oe]("array",t),this[Qe](t),this}boolean(t){return I("<array|string>",[t],arguments.length),this[Oe]("boolean",t),this[Qe](t),this}check(t,e){return I("<function> [boolean]",[t,e],arguments.length),this.middleware((o,n)=>{return Je(()=>{return t(o,n.getOptions())},(r)=>{if(!r)p(this,X,"f").fail(p(this,K,"f").y18n.__("Argument check failed: %s",t.toString()));else if(typeof r==="string"||r instanceof Error)p(this,X,"f").fail(r.toString(),r);return o},(r)=>{return p(this,X,"f").fail(r.message?r.message:r.toString(),r),o})},!1,e),this}choices(t,e){return I("<object|string|array> [string|array]",[t,e],arguments.length),this[Yn](this.choices.bind(this),"choices",t,e),this}coerce(t,e){if(I("<object|string|array> [function]",[t,e],arguments.length),Array.isArray(t)){if(!e)throw new lt("coerce callback must be provided");for(let o of t)this.coerce(o,e);return this}else if(typeof t==="object"){for(let o of Object.keys(t))this.coerce(o,t[o]);return this}if(!e)throw new lt("coerce callback must be provided");return p(this,J,"f").key[t]=!0,p(this,vt,"f").addCoerceMiddleware((o,n)=>{let r;if(!Object.prototype.hasOwnProperty.call(o,t))return o;return Je(()=>{return r=n.getAliases(),e(o[t])},(s)=>{o[t]=s;let c=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&c!==!0)for(let f of r[t])o[f]=s;return o},(s)=>{throw new lt(s.message)})},t),this}conflicts(t,e){return I("<string|object> [string|array]",[t,e],arguments.length),p(this,gt,"f").conflicts(t,e),this}config(t="config",e,o){if(I("[object|string] [string|function] [function]",[t,e,o],arguments.length),typeof t==="object"&&!Array.isArray(t))return t=Fo(t,p(this,ke,"f"),this[Xe]()["deep-merge-config"]||!1,p(this,K,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(t),this;if(typeof e==="function")o=e,e=void 0;return this.describe(t,e||p(this,X,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((n)=>{p(this,J,"f").config[n]=o||!0}),this}completion(t,e,o){if(I("[string] [string|boolean|function] [function]",[t,e,o],arguments.length),typeof e==="function")o=e,e=void 0;if(j(this,jt,t||p(this,jt,"f")||"completion","f"),!e&&e!==!1)e="generate completion script";if(this.command(p(this,jt,"f"),e),o)p(this,kt,"f").registerFunction(o);return this}command(t,e,o,n,r,i){return I("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,o,n,r,i],arguments.length),p(this,bt,"f").addHandler(t,e,o,n,r,i),this}commands(t,e,o,n,r,i){return this.command(t,e,o,n,r,i)}commandDir(t,e){I("<string> [object]",[t,e],arguments.length);let o=p(this,on,"f")||p(this,K,"f").require;return p(this,bt,"f").addDirectory(t,o,p(this,K,"f").getCallerFile(),e),this}count(t){return I("<array|string>",[t],arguments.length),this[Oe]("count",t),this[Qe](t),this}default(t,e,o){if(I("<object|string|array> [*] [string]",[t,e,o],arguments.length),o)vn(t,p(this,K,"f")),p(this,J,"f").defaultDescription[t]=o;if(typeof e==="function"){if(vn(t,p(this,K,"f")),!p(this,J,"f").defaultDescription[t])p(this,J,"f").defaultDescription[t]=p(this,X,"f").functionDescription(e);e=e.call()}return this[lo](this.default.bind(this),"default",t,e),this}defaults(t,e,o){return this.default(t,e,o)}demandCommand(t=1,e,o,n){if(I("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,o,n],arguments.length),typeof e!=="number")o=e,e=1/0;return this.global("_",!1),p(this,J,"f").demandedCommands._={min:t,max:e,minMsg:o,maxMsg:n},this}demand(t,e,o){if(Array.isArray(e))e.forEach((n)=>{Bt(o,!0,p(this,K,"f")),this.demandOption(n,o)}),e=1/0;else if(typeof e!=="number")o=e,e=1/0;if(typeof t==="number")Bt(o,!0,p(this,K,"f")),this.demandCommand(t,e,o,o);else if(Array.isArray(t))t.forEach((n)=>{Bt(o,!0,p(this,K,"f")),this.demandOption(n,o)});else if(typeof o==="string")this.demandOption(t,o);else if(o===!0||typeof o>"u")this.demandOption(t);return this}demandOption(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[lo](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return I("<string> [string|boolean]",[t,e],arguments.length),p(this,J,"f").deprecatedOptions[t]=e,this}describe(t,e){return I("<object|string|array> [string]",[t,e],arguments.length),this[or](t,!0),p(this,X,"f").describe(t,e),this}detectLocale(t){return I("<boolean>",[t],arguments.length),j(this,ze,t,"f"),this}env(t){if(I("[string|boolean]",[t],arguments.length),t===!1)delete p(this,J,"f").envPrefix;else p(this,J,"f").envPrefix=t||"";return this}epilogue(t){return I("<string>",[t],arguments.length),p(this,X,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){if(I("<string|array> [string]",[t,e],arguments.length),Array.isArray(t))t.forEach((o)=>this.example(...o));else p(this,X,"f").example(t,e);return this}exit(t,e){if(j(this,_t,!0,"f"),j(this,Re,e,"f"),p(this,zt,"f"))p(this,K,"f").process.exit(t)}exitProcess(t=!0){return I("[boolean]",[t],arguments.length),j(this,zt,t,"f"),this}fail(t){if(I("<function|boolean>",[t],arguments.length),typeof t==="boolean"&&t!==!1)throw new lt("Invalid first argument. Expected function or boolean 'false'");return p(this,X,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){if(I("<array> [function]",[t,e],arguments.length),!e)return new Promise((o,n)=>{p(this,kt,"f").getCompletion(t,(r,i)=>{if(r)n(r);else o(i)})});else return p(this,kt,"f").getCompletion(t,e)}getDemandedOptions(){return I([],0),p(this,J,"f").demandedOptions}getDemandedCommands(){return I([],0),p(this,J,"f").demandedCommands}getDeprecatedOptions(){return I([],0),p(this,J,"f").deprecatedOptions}getDetectLocale(){return p(this,ze,"f")}getExitProcess(){return p(this,zt,"f")}getGroups(){return Object.assign({},p(this,oe,"f"),p(this,Ue,"f"))}getHelp(){if(j(this,_t,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let e=this[Lo](p(this,Me,"f"),void 0,void 0,0,!0);if(ht(e))return e.then(()=>{return p(this,X,"f").help()})}let t=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(t))return t.then(()=>{return p(this,X,"f").help()})}return Promise.resolve(p(this,X,"f").help())}getOptions(){return p(this,J,"f")}getStrict(){return p(this,Ve,"f")}getStrictCommands(){return p(this,Ke,"f")}getStrictOptions(){return p(this,qe,"f")}global(t,e){if(I("<string|array> [boolean]",[t,e],arguments.length),t=[].concat(t),e!==!1)p(this,J,"f").local=p(this,J,"f").local.filter((o)=>t.indexOf(o)===-1);else t.forEach((o)=>{if(!p(this,J,"f").local.includes(o))p(this,J,"f").local.push(o)});return this}group(t,e){I("<string|array> <string>",[t,e],arguments.length);let o=p(this,Ue,"f")[e]||p(this,oe,"f")[e];if(p(this,Ue,"f")[e])delete p(this,Ue,"f")[e];let n={};return p(this,oe,"f")[e]=(o||[]).concat(t).filter((r)=>{if(n[r])return!1;return n[r]=!0}),this}hide(t){return I("<string>",[t],arguments.length),p(this,J,"f").hiddenOptions.push(t),this}implies(t,e){return I("<string|object> [number|string|array]",[t,e],arguments.length),p(this,gt,"f").implies(t,e),this}locale(t){if(I("[string]",[t],arguments.length),t===void 0)return this[Zn](),p(this,K,"f").y18n.getLocale();return j(this,ze,!1,"f"),p(this,K,"f").y18n.setLocale(t),this}middleware(t,e,o){return p(this,vt,"f").addMiddleware(t,!!e,o)}nargs(t,e){return I("<string|object|array> [number]",[t,e],arguments.length),this[lo](this.nargs.bind(this),"narg",t,e),this}normalize(t){return I("<array|string>",[t],arguments.length),this[Oe]("normalize",t),this}number(t){return I("<array|string>",[t],arguments.length),this[Oe]("number",t),this[Qe](t),this}option(t,e){if(I("<string|object> [object]",[t,e],arguments.length),typeof t==="object")Object.keys(t).forEach((o)=>{this.options(o,t[o])});else{if(typeof e!=="object")e={};if(this[Qe](t),p(this,ne,"f")&&(t==="version"||(e===null||e===void 0?void 0:e.alias)==="version"))this[$i](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
219
- `),void 0,"versionWarning");if(p(this,J,"f").key[t]=!0,e.alias)this.alias(t,e.alias);let o=e.deprecate||e.deprecated;if(o)this.deprecateOption(t,o);let n=e.demand||e.required||e.require;if(n)this.demand(t,n);if(e.demandOption)this.demandOption(t,typeof e.demandOption==="string"?e.demandOption:void 0);if(e.conflicts)this.conflicts(t,e.conflicts);if("default"in e)this.default(t,e.default);if(e.implies!==void 0)this.implies(t,e.implies);if(e.nargs!==void 0)this.nargs(t,e.nargs);if(e.config)this.config(t,e.configParser);if(e.normalize)this.normalize(t);if(e.choices)this.choices(t,e.choices);if(e.coerce)this.coerce(t,e.coerce);if(e.group)this.group(t,e.group);if(e.boolean||e.type==="boolean"){if(this.boolean(t),e.alias)this.boolean(e.alias)}if(e.array||e.type==="array"){if(this.array(t),e.alias)this.array(e.alias)}if(e.number||e.type==="number"){if(this.number(t),e.alias)this.number(e.alias)}if(e.string||e.type==="string"){if(this.string(t),e.alias)this.string(e.alias)}if(e.count||e.type==="count")this.count(t);if(typeof e.global==="boolean")this.global(t,e.global);if(e.defaultDescription)p(this,J,"f").defaultDescription[t]=e.defaultDescription;if(e.skipValidation)this.skipValidation(t);let r=e.describe||e.description||e.desc,i=p(this,X,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(i,t)||typeof r==="string")this.describe(t,r);if(e.hidden)this.hide(t);if(e.requiresArg)this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,o){if(I("[string|array] [function|boolean|object] [function]",[t,e,o],arguments.length),this[Si](),typeof t>"u")t=p(this,Me,"f");if(typeof e==="object")j(this,ve,e,"f"),e=o;if(typeof e==="function")j(this,Tt,e,"f"),e=!1;if(!e)j(this,Me,t,"f");if(p(this,Tt,"f"))j(this,zt,!1,"f");let n=this[Lo](t,!!e),r=this.parsed;if(p(this,kt,"f").setParsed(this.parsed),ht(n))return n.then((i)=>{if(p(this,Tt,"f"))p(this,Tt,"f").call(this,p(this,Re,"f"),i,p(this,yt,"f"));return i}).catch((i)=>{if(p(this,Tt,"f"))p(this,Tt,"f")(i,this.parsed.argv,p(this,yt,"f"));throw i}).finally(()=>{this[nr](),this.parsed=r});else{if(p(this,Tt,"f"))p(this,Tt,"f").call(this,p(this,Re,"f"),n,p(this,yt,"f"));this[nr](),this.parsed=r}return n}parseAsync(t,e,o){let n=this.parse(t,e,o);return!ht(n)?Promise.resolve(n):n}parseSync(t,e,o){let n=this.parse(t,e,o);if(ht(n))throw new lt(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return I("<object>",[t],arguments.length),j(this,nn,t,"f"),this}pkgConf(t,e){I("<string> [string]",[t,e],arguments.length);let o=null,n=this[Qn](e||p(this,ke,"f"));if(n[t]&&typeof n[t]==="object")o=Fo(n[t],e||p(this,ke,"f"),this[Xe]()["deep-merge-config"]||!1,p(this,K,"f")),p(this,J,"f").configObjects=(p(this,J,"f").configObjects||[]).concat(o);return this}positional(t,e){I("<string> <object>",[t,e],arguments.length);let o=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=ye(e,(i,s)=>{if(i==="type"&&!["string","number","boolean"].includes(s))return!1;return o.includes(i)});let n=p(this,Bo,"f").fullCommands[p(this,Bo,"f").fullCommands.length-1],r=n?p(this,bt,"f").cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return so(r).forEach((i)=>{let s=r[i];if(Array.isArray(s)){if(s.indexOf(t)!==-1)e[i]=!0}else if(s[t]&&!(i in e))e[i]=s[t]}),this.group(t,p(this,X,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return I("[boolean]",[t],arguments.length),j(this,rn,t,"f"),this}required(t,e,o){return this.demand(t,e,o)}require(t,e,o){return this.demand(t,e,o)}requiresArg(t){if(I("<array|string|object> [number]",[t],arguments.length),typeof t==="string"&&p(this,J,"f").narg[t])return this;else this[lo](this.requiresArg.bind(this),"narg",t,NaN);return this}showCompletionScript(t,e){return I("[string] [string]",[t,e],arguments.length),t=t||this.$0,p(this,ao,"f").log(p(this,kt,"f").generateCompletionScript(t,e||p(this,jt,"f")||"completion")),this}showHelp(t){if(I("[string|function]",[t],arguments.length),j(this,_t,!0,"f"),!p(this,X,"f").hasCachedHelpMessage()){if(!this.parsed){let o=this[Lo](p(this,Me,"f"),void 0,void 0,0,!0);if(ht(o))return o.then(()=>{p(this,X,"f").showHelp(t)}),this}let e=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(e))return e.then(()=>{p(this,X,"f").showHelp(t)}),this}return p(this,X,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return I("[boolean|string] [string]",[t,e],arguments.length),p(this,X,"f").showHelpOnFail(t,e),this}showVersion(t){return I("[string|function]",[t],arguments.length),p(this,X,"f").showVersion(t),this}skipValidation(t){return I("<array|string>",[t],arguments.length),this[Oe]("skipValidation",t),this}strict(t){return I("[boolean]",[t],arguments.length),j(this,Ve,t!==!1,"f"),this}strictCommands(t){return I("[boolean]",[t],arguments.length),j(this,Ke,t!==!1,"f"),this}strictOptions(t){return I("[boolean]",[t],arguments.length),j(this,qe,t!==!1,"f"),this}string(t){return I("<array|string>",[t],arguments.length),this[Oe]("string",t),this[Qe](t),this}terminalWidth(){return I([],0),p(this,K,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return I("<object>",[t],arguments.length),j(this,ze,!1,"f"),p(this,K,"f").y18n.updateLocale(t),this}usage(t,e,o,n){if(I("<string|null|undefined> [string|boolean] [function|object] [function]",[t,e,o,n],arguments.length),e!==void 0)if(Bt(t,null,p(this,K,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,e,o,n);else throw new lt(".usage() description must start with $0 if being used as alias for .command()");else return p(this,X,"f").usage(t),this}usageConfiguration(t){return I("<object>",[t],arguments.length),j(this,sn,t,"f"),this}version(t,e,o){if(I("[boolean|string] [string] [string]",[t,e,o],arguments.length),p(this,ne,"f"))this[Xn](p(this,ne,"f")),p(this,X,"f").version(void 0),j(this,ne,null,"f");if(arguments.length===0)o=this[Ei](),t="version";else if(arguments.length===1){if(t===!1)return this;o=t,t="version"}else if(arguments.length===2)o=e,e=void 0;return j(this,ne,typeof t==="string"?t:"version","f"),e=e||p(this,X,"f").deferY18nLookup("Show version number"),p(this,X,"f").version(o||void 0),this.boolean(p(this,ne,"f")),this.describe(p(this,ne,"f"),e),this}wrap(t){return I("<number|null|undefined>",[t],arguments.length),p(this,X,"f").wrap(t),this}[(bt=new WeakMap,ke=new WeakMap,Bo=new WeakMap,kt=new WeakMap,jt=new WeakMap,Qo=new WeakMap,Re=new WeakMap,ze=new WeakMap,Yo=new WeakMap,zt=new WeakMap,tn=new WeakMap,vt=new WeakMap,oe=new WeakMap,_t=new WeakMap,Ut=new WeakMap,en=new WeakMap,ao=new WeakMap,yt=new WeakMap,J=new WeakMap,on=new WeakMap,nn=new WeakMap,Tt=new WeakMap,ve=new WeakMap,fo=new WeakMap,Ue=new WeakMap,Me=new WeakMap,rn=new WeakMap,K=new WeakMap,Ve=new WeakMap,Ke=new WeakMap,qe=new WeakMap,X=new WeakMap,sn=new WeakMap,ne=new WeakMap,gt=new WeakMap,bi)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(e){}return t}[Ci](){return{log:(...t)=>{if(!this[cn]())console.log(...t);if(j(this,_t,!0,"f"),p(this,yt,"f").length)j(this,yt,p(this,yt,"f")+`
220
- `,"f");j(this,yt,p(this,yt,"f")+t.join(" "),"f")},error:(...t)=>{if(!this[cn]())console.error(...t);if(j(this,_t,!0,"f"),p(this,yt,"f").length)j(this,yt,p(this,yt,"f")+`
221
- `,"f");j(this,yt,p(this,yt,"f")+t.join(" "),"f")}}}[Xn](t){so(p(this,J,"f")).forEach((e)=>{if(((n)=>n==="configObjects")(e))return;let o=p(this,J,"f")[e];if(Array.isArray(o)){if(o.includes(t))o.splice(o.indexOf(t),1)}else if(typeof o==="object")delete o[t]}),delete p(this,X,"f").getDescriptions()[t]}[$i](t,e,o){if(!p(this,Yo,"f")[o])p(this,K,"f").process.emitWarning(t,e),p(this,Yo,"f")[o]=!0}[Si](){p(this,tn,"f").push({options:p(this,J,"f"),configObjects:p(this,J,"f").configObjects.slice(0),exitProcess:p(this,zt,"f"),groups:p(this,oe,"f"),strict:p(this,Ve,"f"),strictCommands:p(this,Ke,"f"),strictOptions:p(this,qe,"f"),completionCommand:p(this,jt,"f"),output:p(this,yt,"f"),exitError:p(this,Re,"f"),hasOutput:p(this,_t,"f"),parsed:this.parsed,parseFn:p(this,Tt,"f"),parseContext:p(this,ve,"f")}),p(this,X,"f").freeze(),p(this,gt,"f").freeze(),p(this,bt,"f").freeze(),p(this,vt,"f").freeze()}[Pi](){let t="",e;if(/\b(node|iojs|electron)(\.exe)?$/.test(p(this,K,"f").process.argv()[0]))e=p(this,K,"f").process.argv().slice(1,2);else e=p(this,K,"f").process.argv().slice(0,1);if(t=e.map((o)=>{let n=this[ji](p(this,ke,"f"),o);return o.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<o.length?n:o}).join(" ").trim(),p(this,K,"f").getEnv("_")&&p(this,K,"f").getProcessArgvBin()===p(this,K,"f").getEnv("_"))t=p(this,K,"f").getEnv("_").replace(`${p(this,K,"f").path.dirname(p(this,K,"f").process.execPath())}/`,"");return t}[Xe](){return p(this,nn,"f")}[yi](){return p(this,sn,"f")}[Zn](){if(!p(this,ze,"f"))return;let t=p(this,K,"f").getEnv("LC_ALL")||p(this,K,"f").getEnv("LC_MESSAGES")||p(this,K,"f").getEnv("LANG")||p(this,K,"f").getEnv("LANGUAGE")||"en_US";this.locale(t.replace(/[.:].*/,""))}[Ei](){return this[Qn]().version||"unknown"}[Ri](t){let e=t["--"]?t["--"]:t._;for(let o=0,n;(n=e[o])!==void 0;o++)if(p(this,K,"f").Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`))))e[o]=Number(n);return t}[Qn](t){let e=t||"*";if(p(this,fo,"f")[e])return p(this,fo,"f")[e];let o={};try{let n=t||p(this,K,"f").mainFilename;if(!t&&p(this,K,"f").path.extname(n))n=p(this,K,"f").path.dirname(n);let r=p(this,K,"f").findUp(n,(i,s)=>{if(s.includes("package.json"))return"package.json";else return});Bt(r,void 0,p(this,K,"f")),o=JSON.parse(p(this,K,"f").readFileSync(r,"utf8"))}catch(n){}return p(this,fo,"f")[e]=o||{},p(this,fo,"f")[e]}[Oe](t,e){e=[].concat(e),e.forEach((o)=>{o=this[er](o),p(this,J,"f")[t].push(o)})}[lo](t,e,o,n){this[tr](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=s})}[Yn](t,e,o,n){this[tr](t,e,o,n,(r,i,s)=>{p(this,J,"f")[r][i]=(p(this,J,"f")[r][i]||[]).concat(s)})}[tr](t,e,o,n,r){if(Array.isArray(o))o.forEach((i)=>{t(i,n)});else if(((i)=>typeof i==="object")(o))for(let i of so(o))t(i,o[i]);else r(e,this[er](o),n)}[er](t){if(t==="__proto__")return"___proto___";return t}[or](t,e){return this[lo](this[or].bind(this),"key",t,e),this}[nr](){var t,e,o,n,r,i,s,c,f,a,h,u;let d=p(this,tn,"f").pop();Bt(d,void 0,p(this,K,"f"));let g;t=this,e=this,o=this,n=this,r=this,i=this,s=this,c=this,f=this,a=this,h=this,u=this,{options:{set value(x){j(t,J,x,"f")}}.value,configObjects:g,exitProcess:{set value(x){j(e,zt,x,"f")}}.value,groups:{set value(x){j(o,oe,x,"f")}}.value,output:{set value(x){j(n,yt,x,"f")}}.value,exitError:{set value(x){j(r,Re,x,"f")}}.value,hasOutput:{set value(x){j(i,_t,x,"f")}}.value,parsed:this.parsed,strict:{set value(x){j(s,Ve,x,"f")}}.value,strictCommands:{set value(x){j(c,Ke,x,"f")}}.value,strictOptions:{set value(x){j(f,qe,x,"f")}}.value,completionCommand:{set value(x){j(a,jt,x,"f")}}.value,parseFn:{set value(x){j(h,Tt,x,"f")}}.value,parseContext:{set value(x){j(u,ve,x,"f")}}.value}=d,p(this,J,"f").configObjects=g,p(this,X,"f").unfreeze(),p(this,gt,"f").unfreeze(),p(this,bt,"f").unfreeze(),p(this,vt,"f").unfreeze()}[Mi](t,e){return Je(e,(o)=>{return t(o),o})}getInternalMethods(){return{getCommandInstance:this[Oi].bind(this),getContext:this[Wi].bind(this),getHasOutput:this[Di].bind(this),getLoggerInstance:this[Fi].bind(this),getParseContext:this[Bi].bind(this),getParserConfiguration:this[Xe].bind(this),getUsageConfiguration:this[yi].bind(this),getUsageInstance:this[Li].bind(this),getValidationInstance:this[Ai].bind(this),hasParseCallback:this[cn].bind(this),isGlobalContext:this[Ii].bind(this),postProcess:this[Ze].bind(this),reset:this[rr].bind(this),runValidation:this[ir].bind(this),runYargsParserAndExecuteCommands:this[Lo].bind(this),setHasOutput:this[_i].bind(this)}}[Oi](){return p(this,bt,"f")}[Wi](){return p(this,Bo,"f")}[Di](){return p(this,_t,"f")}[Fi](){return p(this,ao,"f")}[Bi](){return p(this,ve,"f")||{}}[Li](){return p(this,X,"f")}[Ai](){return p(this,gt,"f")}[cn](){return!!p(this,Tt,"f")}[Ii](){return p(this,en,"f")}[Ze](t,e,o,n){if(o)return t;if(ht(t))return t;if(!e)t=this[bi](t);if(this[Xe]()["parse-positional-numbers"]||this[Xe]()["parse-positional-numbers"]===void 0)t=this[Ri](t);if(n)t=Ne(t,this,p(this,vt,"f").getMiddleware(),!1);return t}[rr](t={}){j(this,J,p(this,J,"f")||{},"f");let e={};e.local=p(this,J,"f").local||[],e.configObjects=p(this,J,"f").configObjects||[];let o={};e.local.forEach((i)=>{o[i]=!0,(t[i]||[]).forEach((s)=>{o[s]=!0})}),Object.assign(p(this,Ue,"f"),Object.keys(p(this,oe,"f")).reduce((i,s)=>{let c=p(this,oe,"f")[s].filter((f)=>!(f in o));if(c.length>0)i[s]=c;return i},{})),j(this,oe,{},"f");let n=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(n.forEach((i)=>{e[i]=(p(this,J,"f")[i]||[]).filter((s)=>!o[s])}),r.forEach((i)=>{e[i]=ye(p(this,J,"f")[i],(s)=>!o[s])}),e.envPrefix=p(this,J,"f").envPrefix,j(this,J,e,"f"),j(this,X,p(this,X,"f")?p(this,X,"f").reset(o):li(this,p(this,K,"f")),"f"),j(this,gt,p(this,gt,"f")?p(this,gt,"f").reset(o):gi(this,p(this,X,"f"),p(this,K,"f")),"f"),j(this,bt,p(this,bt,"f")?p(this,bt,"f").reset():ci(p(this,X,"f"),p(this,gt,"f"),p(this,vt,"f"),p(this,K,"f")),"f"),!p(this,kt,"f"))j(this,kt,di(this,p(this,X,"f"),p(this,bt,"f"),p(this,K,"f")),"f");return p(this,vt,"f").reset(),j(this,jt,null,"f"),j(this,yt,"","f"),j(this,Re,null,"f"),j(this,_t,!1,"f"),this.parsed=!1,this}[ji](t,e){return p(this,K,"f").path.relative(t,e)}[Lo](t,e,o,n=0,r=!1){let i=!!o||r;t=t||p(this,Me,"f"),p(this,J,"f").__=p(this,K,"f").y18n.__,p(this,J,"f").configuration=this[Xe]();let s=!!p(this,J,"f").configuration["populate--"],c=Object.assign({},p(this,J,"f").configuration,{"populate--":!0}),f=p(this,K,"f").Parser.detailed(t,Object.assign({},p(this,J,"f"),{configuration:{"parse-positional-numbers":!1,...c}})),a=Object.assign(f.argv,p(this,ve,"f")),h=void 0,u=f.aliases,d=!1,g=!1;if(Object.keys(a).forEach((x)=>{if(x===p(this,Ut,"f")&&a[x])d=!0;else if(x===p(this,ne,"f")&&a[x])g=!0}),a.$0=this.$0,this.parsed=f,n===0)p(this,X,"f").clearCachedHelpMessage();try{if(this[Zn](),e)return this[Ze](a,s,!!o,!1);if(p(this,Ut,"f")){if([p(this,Ut,"f")].concat(u[p(this,Ut,"f")]||[]).filter((E)=>E.length>1).includes(""+a._[a._.length-1]))a._.pop(),d=!0}j(this,en,!1,"f");let x=p(this,bt,"f").getCommands(),m=p(this,kt,"f").completionKey in a,b=d||m||r;if(a._.length){if(x.length){let S;for(let E=n||0,y;a._[E]!==void 0;E++)if(y=String(a._[E]),x.includes(y)&&y!==p(this,jt,"f")){let R=p(this,bt,"f").runCommand(y,this,f,E+1,r,d||g||r);return this[Ze](R,s,!!o,!1)}else if(!S&&y!==p(this,jt,"f")){S=y;break}if(!p(this,bt,"f").hasDefaultCommand()&&p(this,rn,"f")&&S&&!b)p(this,gt,"f").recommendCommands(S,x)}if(p(this,jt,"f")&&a._.includes(p(this,jt,"f"))&&!m){if(p(this,zt,"f"))Ee(!0);this.showCompletionScript(),this.exit(0)}}if(p(this,bt,"f").hasDefaultCommand()&&!b){let S=p(this,bt,"f").runCommand(null,this,f,0,r,d||g||r);return this[Ze](S,s,!!o,!1)}if(m){if(p(this,zt,"f"))Ee(!0);t=[].concat(t);let S=t.slice(t.indexOf(`--${p(this,kt,"f").completionKey}`)+1);return p(this,kt,"f").getCompletion(S,(E,y)=>{if(E)throw new lt(E.message);(y||[]).forEach((R)=>{p(this,ao,"f").log(R)}),this.exit(0)}),this[Ze](a,!s,!!o,!1)}if(!p(this,_t,"f")){if(d){if(p(this,zt,"f"))Ee(!0);i=!0,this.showHelp("log"),this.exit(0)}else if(g){if(p(this,zt,"f"))Ee(!0);i=!0,p(this,X,"f").showVersion("log"),this.exit(0)}}if(!i&&p(this,J,"f").skipValidation.length>0)i=Object.keys(a).some((S)=>p(this,J,"f").skipValidation.indexOf(S)>=0&&a[S]===!0);if(!i){if(f.error)throw new lt(f.error.message);if(!m){let S=this[ir](u,{},f.error);if(!o)h=Ne(a,this,p(this,vt,"f").getMiddleware(),!0);if(h=this[Mi](S,h!==null&&h!==void 0?h:a),ht(h)&&!o)h=h.then(()=>{return Ne(a,this,p(this,vt,"f").getMiddleware(),!1)})}}}catch(x){if(x instanceof lt)p(this,X,"f").fail(x.message,x);else throw x}return this[Ze](h!==null&&h!==void 0?h:a,s,!!o,!0)}[ir](t,e,o,n){let r={...this.getDemandedOptions()};return(i)=>{if(o)throw new lt(o.message);p(this,gt,"f").nonOptionCount(i),p(this,gt,"f").requiredArguments(i,r);let s=!1;if(p(this,Ke,"f"))s=p(this,gt,"f").unknownCommands(i);if(p(this,Ve,"f")&&!s)p(this,gt,"f").unknownArguments(i,t,e,!!n);else if(p(this,qe,"f"))p(this,gt,"f").unknownArguments(i,t,{},!1,!1);p(this,gt,"f").limitedChoices(i),p(this,gt,"f").implications(i),p(this,gt,"f").conflicting(i)}}[_i](){j(this,_t,!0,"f")}[Qe](t){if(typeof t==="string")p(this,J,"f").key[t]=!0;else for(let e of t)p(this,J,"f").key[e]=!0}}function ai(t){return!!t&&typeof t.getInternalMethods==="function"}var Sf=Ti(zn),Hi=Sf;import{readFileSync as yp}from"fs";import{join as Ep}from"path";var Rp=JSON.parse(yp(Ep(import.meta.dir,"../../package.json"),"utf-8"));if(process.argv.length===2){let{launchTUI:t}=await Promise.resolve().then(() => (tc(),Ys));await t()}else{let[t,e,o,n,r,i,s,c,f,a,h,u,d,g,x,m,b,S,E,y]=await Promise.all([Promise.resolve().then(() => (fc(),ac)),Promise.resolve().then(() => (hc(),lc)),Promise.resolve().then(() => (dc(),pc)),Promise.resolve().then(() => (xc(),mc)),Promise.resolve().then(() => ($c(),Cc)),Promise.resolve().then(() => (Wc(),Oc)),Promise.resolve().then(() => (Fc(),Dc)),Promise.resolve().then(() => (Ic(),Ac)),Promise.resolve().then(() => (Tc(),_c)),Promise.resolve().then(() => (Nc(),Hc)),Promise.resolve().then(() => (zc(),kc)),Promise.resolve().then(() => (Uc(),vc)),Promise.resolve().then(() => (Kc(),Vc)),Promise.resolve().then(() => (Xc(),qc)),Promise.resolve().then(() => (sa(),ia)),Promise.resolve().then(() => (aa(),ca)),Promise.resolve().then(() => (la(),fa)),Promise.resolve().then(() => (ga(),xa)),Promise.resolve().then(() => (ba(),wa)),Promise.resolve().then(() => (Ma(),Ra))]);Hi(kn(process.argv)).locale("en").scriptName("omw").version(`oh-my-worktree v${Rp.version}`).alias("version","v").help("help").alias("help","h").option("no-color",{type:"boolean",description:"Disable color output"}).command(t.default).command(e.default).command(o.default).command(n.default).command(r.default).command(i.default).command(s.default).command(c.default).command(f.default).command(a.default).command(h.default).command(u.default).command(d.default).command(g.default).command(x.default).command(m.default).command(b.default).command(S.default).command(E.default).command(y.default).completion("completion","Generate shell completion script").demandCommand(1,"Please specify a command. Run --help to see available commands.").strict().parse()}
215
+ `)}`:"";e.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(g).length,Object.keys(g).join(", ")+m))}},i.unknownArguments=function(u,d,g,x,m=!0){var b;let $=t.getInternalMethods().getCommandInstance().getCommands(),E=[],R=t.getInternalMethods().getContext();if(Object.keys(u).forEach((P)=>{if(!Ci.includes(P)&&!Object.prototype.hasOwnProperty.call(g,P)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),P)&&!i.isValidAndSomeAliasIsNotNew(P,d))E.push(P)}),m&&(R.commands.length>0||$.length>0||x))u._.slice(R.commands.length).forEach((P)=>{if(!$.includes(""+P))E.push(""+P)});if(m){let rt=((b=t.getDemandedCommands()._)===null||b===void 0?void 0:b.max)||0,at=R.commands.length+rt;if(at<u._.length)u._.slice(at).forEach((I)=>{if(I=String(I),!R.commands.includes(I)&&!E.includes(I))E.push(I)})}if(E.length)e.fail(r("Unknown argument: %s","Unknown arguments: %s",E.length,E.map((P)=>P.trim()?P:`"${P}"`).join(", ")))},i.unknownCommands=function(u){let d=t.getInternalMethods().getCommandInstance().getCommands(),g=[],x=t.getInternalMethods().getContext();if(x.commands.length>0||d.length>0)u._.slice(x.commands.length).forEach((m)=>{if(!d.includes(""+m))g.push(""+m)});if(g.length>0)return e.fail(r("Unknown command: %s","Unknown commands: %s",g.length,g.join(", "))),!0;else return!1},i.isValidAndSomeAliasIsNotNew=function(u,d){if(!Object.prototype.hasOwnProperty.call(d,u))return!1;let g=t.parsed.newAliases;return[u,...d[u]].some((x)=>!Object.prototype.hasOwnProperty.call(g,x)||!g[u])},i.limitedChoices=function(u){let d=t.getOptions(),g={};if(!Object.keys(d.choices).length)return;Object.keys(u).forEach((b)=>{if(Ci.indexOf(b)===-1&&Object.prototype.hasOwnProperty.call(d.choices,b))[].concat(u[b]).forEach(($)=>{if(d.choices[b].indexOf($)===-1&&$!==void 0)g[b]=(g[b]||[]).concat($)})});let x=Object.keys(g);if(!x.length)return;let m=n("Invalid values:");x.forEach((b)=>{m+=`
216
+ ${n("Argument: %s, Given: %s, Choices: %s",b,e.stringifiedValues(g[b]),e.stringifiedValues(d.choices[b]))}`}),e.fail(m)};let s={};i.implies=function(u,d){if(_("<string|object> [array|number|string]",[u,d],arguments.length),typeof u==="object")Object.keys(u).forEach((g)=>{i.implies(g,u[g])});else{if(t.global(u),!s[u])s[u]=[];if(Array.isArray(d))d.forEach((g)=>i.implies(u,g));else Bt(d,void 0,o),s[u].push(d)}},i.getImplied=function(){return s};function c(h,u){let d=Number(u);if(u=isNaN(d)?u:d,typeof u==="number")u=h._.length>=u;else if(u.match(/^--no-.+/))u=u.match(/^--no-(.+)/)[1],u=!Object.prototype.hasOwnProperty.call(h,u);else u=Object.prototype.hasOwnProperty.call(h,u);return u}i.implications=function(u){let d=[];if(Object.keys(s).forEach((g)=>{let x=g;(s[g]||[]).forEach((m)=>{let b=x,$=m;if(b=c(u,b),m=c(u,m),b&&!m)d.push(` ${x} -> ${$}`)})}),d.length){let g=`${n("Implications failed:")}
217
+ `;d.forEach((x)=>{g+=x}),e.fail(g)}};let l={};i.conflicts=function(u,d){if(_("<string|object> [array|string]",[u,d],arguments.length),typeof u==="object")Object.keys(u).forEach((g)=>{i.conflicts(g,u[g])});else{if(t.global(u),!l[u])l[u]=[];if(Array.isArray(d))d.forEach((g)=>i.conflicts(u,g));else l[u].push(d)}},i.getConflicting=()=>l,i.conflicting=function(u){if(Object.keys(u).forEach((d)=>{if(l[d])l[d].forEach((g)=>{if(g&&u[d]!==void 0&&u[g]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})}),t.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(l).forEach((d)=>{l[d].forEach((g)=>{if(g&&u[o.Parser.camelCase(d)]!==void 0&&u[o.Parser.camelCase(g)]!==void 0)e.fail(n("Arguments %s and %s are mutually exclusive",d,g))})})},i.recommendCommands=function(u,d){d=d.sort((b,$)=>$.length-b.length);let x=null,m=1/0;for(let b=0,$;($=d[b])!==void 0;b++){let E=bi(u,$);if(E<=3&&E<m)m=E,x=$}if(x)e.fail(n("Did you mean %s?",x))},i.reset=function(u){return s=Ee(s,(d)=>!u[d]),l=Ee(l,(d)=>!u[d]),i};let a=[];return i.freeze=function(){a.push({implied:s,conflicting:l})},i.unfreeze=function(){let u=a.pop();Bt(u,void 0,o),{implied:s,conflicting:l}=u},i}var Qn=[],Lo;function Io(t,e,o,n){Lo=n;let r={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if(typeof t.extends!=="string")return r;let i=/\.json|\..*rc$/.test(t.extends),s=null;if(!i)try{s=pe.resolve(t.extends)}catch(c){return t}else s=Rl(e,t.extends);El(s),Qn.push(s),r=i?JSON.parse(Lo.readFileSync(s,"utf8")):pe(t.extends),delete t.extends,r=Io(r,Lo.path.dirname(s),o,Lo)}return Qn=[],o?$i(r,t):Object.assign({},r,t)}function El(t){if(Qn.indexOf(t)>-1)throw new ft(`Circular extended configurations: '${t}'.`)}function Rl(t,e){return Lo.path.resolve(t,e)}function $i(t,e){let o={};function n(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(o,t);for(let r of Object.keys(e))if(n(e[r])&&n(o[r]))o[r]=$i(t[r],e[r]);else o[r]=e[r];return o}var T=function(t,e,o,n,r){if(n==="m")throw TypeError("Private method is not writable");if(n==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof e==="function"?t!==e||!r:!e.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(t,o):r?r.value=o:e.set(t,o),o},p=function(t,e,o,n){if(o==="a"&&!n)throw TypeError("Private accessor was defined without a getter");if(typeof e==="function"?t!==e||!n:!e.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?n:o==="a"?n.call(t):n?n.value:e.get(t)},bt,ze,Ao,Jt,Tt,on,Me,Ue,nn,zt,rn,Ut,ne,Gt,Vt,sn,lo,yt,k,cn,an,vt,Ve,fo,Ke,Oe,ln,K,Xe,qe,Ze,q,fn,re,gt;function ki(t){return(e=[],o=t.process.cwd(),n)=>{let r=new Ni(e,o,n,t);return Object.defineProperty(r,"argv",{get:()=>{return r.parse()},enumerable:!0}),r.help(),r.version(),r}}var Pi=Symbol("copyDoubleDash"),yi=Symbol("copyDoubleDash"),Yn=Symbol("deleteFromParserHintObject"),Ei=Symbol("emitWarning"),Ri=Symbol("freeze"),Mi=Symbol("getDollarZero"),Qe=Symbol("getParserConfiguration"),Oi=Symbol("getUsageConfiguration"),tr=Symbol("guessLocale"),Wi=Symbol("guessVersion"),Di=Symbol("parsePositionalNumbers"),er=Symbol("pkgUp"),We=Symbol("populateParserHintArray"),ho=Symbol("populateParserHintSingleValueDictionary"),or=Symbol("populateParserHintArrayDictionary"),nr=Symbol("populateParserHintDictionary"),rr=Symbol("sanitizeKey"),ir=Symbol("setKey"),sr=Symbol("unfreeze"),Fi=Symbol("validateAsync"),Bi=Symbol("getCommandInstance"),Li=Symbol("getContext"),Ii=Symbol("getHasOutput"),Ai=Symbol("getLoggerInstance"),ji=Symbol("getParseContext"),_i=Symbol("getUsageInstance"),Ti=Symbol("getValidationInstance"),hn=Symbol("hasParseCallback"),Gi=Symbol("isGlobalContext"),Ye=Symbol("postProcess"),vi=Symbol("rebase"),cr=Symbol("reset"),jo=Symbol("runYargsParserAndExecuteCommands"),ar=Symbol("runValidation"),Hi=Symbol("setHasOutput"),to=Symbol("kTrackManuallySetKeys");class Ni{constructor(t=[],e,o,n){this.customScriptName=!1,this.parsed=!1,bt.set(this,void 0),ze.set(this,void 0),Ao.set(this,{commands:[],fullCommands:[]}),Jt.set(this,null),Tt.set(this,null),on.set(this,"show-hidden"),Me.set(this,null),Ue.set(this,!0),nn.set(this,{}),zt.set(this,!0),rn.set(this,[]),Ut.set(this,void 0),ne.set(this,{}),Gt.set(this,!1),Vt.set(this,null),sn.set(this,!0),lo.set(this,void 0),yt.set(this,""),k.set(this,void 0),cn.set(this,void 0),an.set(this,{}),vt.set(this,null),Ve.set(this,null),fo.set(this,{}),Ke.set(this,{}),Oe.set(this,void 0),ln.set(this,!1),K.set(this,void 0),Xe.set(this,!1),qe.set(this,!1),Ze.set(this,!1),q.set(this,void 0),fn.set(this,{}),re.set(this,null),gt.set(this,void 0),T(this,K,n,"f"),T(this,Oe,t,"f"),T(this,ze,e,"f"),T(this,cn,o,"f"),T(this,Ut,new Xn(this),"f"),this.$0=this[Mi](),this[cr](),T(this,bt,p(this,bt,"f"),"f"),T(this,q,p(this,q,"f"),"f"),T(this,gt,p(this,gt,"f"),"f"),T(this,k,p(this,k,"f"),"f"),p(this,k,"f").showHiddenOpt=p(this,on,"f"),T(this,lo,this[yi](),"f")}addHelpOpt(t,e){if(_("[string|boolean] [string]",[t,e],arguments.length),p(this,Vt,"f"))this[Yn](p(this,Vt,"f")),T(this,Vt,null,"f");if(t===!1&&e===void 0)return this;return T(this,Vt,typeof t==="string"?t:"help","f"),this.boolean(p(this,Vt,"f")),this.describe(p(this,Vt,"f"),e||p(this,q,"f").deferY18nLookup("Show help")),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(_("[string|boolean] [string]",[t,e],arguments.length),t===!1&&e===void 0)return this;let o=typeof t==="string"?t:p(this,on,"f");return this.boolean(o),this.describe(o,e||p(this,q,"f").deferY18nLookup("Show hidden options")),p(this,k,"f").showHiddenOpt=o,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return _("<object|string|array> [string|array]",[t,e],arguments.length),this[or](this.alias.bind(this),"alias",t,e),this}array(t){return _("<array|string>",[t],arguments.length),this[We]("array",t),this[to](t),this}boolean(t){return _("<array|string>",[t],arguments.length),this[We]("boolean",t),this[to](t),this}check(t,e){return _("<function> [boolean]",[t,e],arguments.length),this.middleware((o,n)=>{return Je(()=>{return t(o,n.getOptions())},(r)=>{if(!r)p(this,q,"f").fail(p(this,K,"f").y18n.__("Argument check failed: %s",t.toString()));else if(typeof r==="string"||r instanceof Error)p(this,q,"f").fail(r.toString(),r);return o},(r)=>{return p(this,q,"f").fail(r.message?r.message:r.toString(),r),o})},!1,e),this}choices(t,e){return _("<object|string|array> [string|array]",[t,e],arguments.length),this[or](this.choices.bind(this),"choices",t,e),this}coerce(t,e){if(_("<object|string|array> [function]",[t,e],arguments.length),Array.isArray(t)){if(!e)throw new ft("coerce callback must be provided");for(let o of t)this.coerce(o,e);return this}else if(typeof t==="object"){for(let o of Object.keys(t))this.coerce(o,t[o]);return this}if(!e)throw new ft("coerce callback must be provided");return p(this,k,"f").key[t]=!0,p(this,Ut,"f").addCoerceMiddleware((o,n)=>{let r;if(!Object.prototype.hasOwnProperty.call(o,t))return o;return Je(()=>{return r=n.getAliases(),e(o[t])},(s)=>{o[t]=s;let c=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&c!==!0)for(let l of r[t])o[l]=s;return o},(s)=>{throw new ft(s.message)})},t),this}conflicts(t,e){return _("<string|object> [string|array]",[t,e],arguments.length),p(this,gt,"f").conflicts(t,e),this}config(t="config",e,o){if(_("[object|string] [string|function] [function]",[t,e,o],arguments.length),typeof t==="object"&&!Array.isArray(t))return t=Io(t,p(this,ze,"f"),this[Qe]()["deep-merge-config"]||!1,p(this,K,"f")),p(this,k,"f").configObjects=(p(this,k,"f").configObjects||[]).concat(t),this;if(typeof e==="function")o=e,e=void 0;return this.describe(t,e||p(this,q,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((n)=>{p(this,k,"f").config[n]=o||!0}),this}completion(t,e,o){if(_("[string] [string|boolean|function] [function]",[t,e,o],arguments.length),typeof e==="function")o=e,e=void 0;if(T(this,Tt,t||p(this,Tt,"f")||"completion","f"),!e&&e!==!1)e="generate completion script";if(this.command(p(this,Tt,"f"),e),o)p(this,Jt,"f").registerFunction(o);return this}command(t,e,o,n,r,i){return _("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,o,n,r,i],arguments.length),p(this,bt,"f").addHandler(t,e,o,n,r,i),this}commands(t,e,o,n,r,i){return this.command(t,e,o,n,r,i)}commandDir(t,e){_("<string> [object]",[t,e],arguments.length);let o=p(this,cn,"f")||p(this,K,"f").require;return p(this,bt,"f").addDirectory(t,o,p(this,K,"f").getCallerFile(),e),this}count(t){return _("<array|string>",[t],arguments.length),this[We]("count",t),this[to](t),this}default(t,e,o){if(_("<object|string|array> [*] [string]",[t,e,o],arguments.length),o)Kn(t,p(this,K,"f")),p(this,k,"f").defaultDescription[t]=o;if(typeof e==="function"){if(Kn(t,p(this,K,"f")),!p(this,k,"f").defaultDescription[t])p(this,k,"f").defaultDescription[t]=p(this,q,"f").functionDescription(e);e=e.call()}return this[ho](this.default.bind(this),"default",t,e),this}defaults(t,e,o){return this.default(t,e,o)}demandCommand(t=1,e,o,n){if(_("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,o,n],arguments.length),typeof e!=="number")o=e,e=1/0;return this.global("_",!1),p(this,k,"f").demandedCommands._={min:t,max:e,minMsg:o,maxMsg:n},this}demand(t,e,o){if(Array.isArray(e))e.forEach((n)=>{Bt(o,!0,p(this,K,"f")),this.demandOption(n,o)}),e=1/0;else if(typeof e!=="number")o=e,e=1/0;if(typeof t==="number")Bt(o,!0,p(this,K,"f")),this.demandCommand(t,e,o,o);else if(Array.isArray(t))t.forEach((n)=>{Bt(o,!0,p(this,K,"f")),this.demandOption(n,o)});else if(typeof o==="string")this.demandOption(t,o);else if(o===!0||typeof o>"u")this.demandOption(t);return this}demandOption(t,e){return _("<object|string|array> [string]",[t,e],arguments.length),this[ho](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return _("<string> [string|boolean]",[t,e],arguments.length),p(this,k,"f").deprecatedOptions[t]=e,this}describe(t,e){return _("<object|string|array> [string]",[t,e],arguments.length),this[ir](t,!0),p(this,q,"f").describe(t,e),this}detectLocale(t){return _("<boolean>",[t],arguments.length),T(this,Ue,t,"f"),this}env(t){if(_("[string|boolean]",[t],arguments.length),t===!1)delete p(this,k,"f").envPrefix;else p(this,k,"f").envPrefix=t||"";return this}epilogue(t){return _("<string>",[t],arguments.length),p(this,q,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){if(_("<string|array> [string]",[t,e],arguments.length),Array.isArray(t))t.forEach((o)=>this.example(...o));else p(this,q,"f").example(t,e);return this}exit(t,e){if(T(this,Gt,!0,"f"),T(this,Me,e,"f"),p(this,zt,"f"))p(this,K,"f").process.exit(t)}exitProcess(t=!0){return _("[boolean]",[t],arguments.length),T(this,zt,t,"f"),this}fail(t){if(_("<function|boolean>",[t],arguments.length),typeof t==="boolean"&&t!==!1)throw new ft("Invalid first argument. Expected function or boolean 'false'");return p(this,q,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){if(_("<array> [function]",[t,e],arguments.length),!e)return new Promise((o,n)=>{p(this,Jt,"f").getCompletion(t,(r,i)=>{if(r)n(r);else o(i)})});else return p(this,Jt,"f").getCompletion(t,e)}getDemandedOptions(){return _([],0),p(this,k,"f").demandedOptions}getDemandedCommands(){return _([],0),p(this,k,"f").demandedCommands}getDeprecatedOptions(){return _([],0),p(this,k,"f").deprecatedOptions}getDetectLocale(){return p(this,Ue,"f")}getExitProcess(){return p(this,zt,"f")}getGroups(){return Object.assign({},p(this,ne,"f"),p(this,Ke,"f"))}getHelp(){if(T(this,Gt,!0,"f"),!p(this,q,"f").hasCachedHelpMessage()){if(!this.parsed){let e=this[jo](p(this,Oe,"f"),void 0,void 0,0,!0);if(ht(e))return e.then(()=>{return p(this,q,"f").help()})}let t=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(t))return t.then(()=>{return p(this,q,"f").help()})}return Promise.resolve(p(this,q,"f").help())}getOptions(){return p(this,k,"f")}getStrict(){return p(this,Xe,"f")}getStrictCommands(){return p(this,qe,"f")}getStrictOptions(){return p(this,Ze,"f")}global(t,e){if(_("<string|array> [boolean]",[t,e],arguments.length),t=[].concat(t),e!==!1)p(this,k,"f").local=p(this,k,"f").local.filter((o)=>t.indexOf(o)===-1);else t.forEach((o)=>{if(!p(this,k,"f").local.includes(o))p(this,k,"f").local.push(o)});return this}group(t,e){_("<string|array> <string>",[t,e],arguments.length);let o=p(this,Ke,"f")[e]||p(this,ne,"f")[e];if(p(this,Ke,"f")[e])delete p(this,Ke,"f")[e];let n={};return p(this,ne,"f")[e]=(o||[]).concat(t).filter((r)=>{if(n[r])return!1;return n[r]=!0}),this}hide(t){return _("<string>",[t],arguments.length),p(this,k,"f").hiddenOptions.push(t),this}implies(t,e){return _("<string|object> [number|string|array]",[t,e],arguments.length),p(this,gt,"f").implies(t,e),this}locale(t){if(_("[string]",[t],arguments.length),t===void 0)return this[tr](),p(this,K,"f").y18n.getLocale();return T(this,Ue,!1,"f"),p(this,K,"f").y18n.setLocale(t),this}middleware(t,e,o){return p(this,Ut,"f").addMiddleware(t,!!e,o)}nargs(t,e){return _("<string|object|array> [number]",[t,e],arguments.length),this[ho](this.nargs.bind(this),"narg",t,e),this}normalize(t){return _("<array|string>",[t],arguments.length),this[We]("normalize",t),this}number(t){return _("<array|string>",[t],arguments.length),this[We]("number",t),this[to](t),this}option(t,e){if(_("<string|object> [object]",[t,e],arguments.length),typeof t==="object")Object.keys(t).forEach((o)=>{this.options(o,t[o])});else{if(typeof e!=="object")e={};if(this[to](t),p(this,re,"f")&&(t==="version"||(e===null||e===void 0?void 0:e.alias)==="version"))this[Ei](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
218
+ `),void 0,"versionWarning");if(p(this,k,"f").key[t]=!0,e.alias)this.alias(t,e.alias);let o=e.deprecate||e.deprecated;if(o)this.deprecateOption(t,o);let n=e.demand||e.required||e.require;if(n)this.demand(t,n);if(e.demandOption)this.demandOption(t,typeof e.demandOption==="string"?e.demandOption:void 0);if(e.conflicts)this.conflicts(t,e.conflicts);if("default"in e)this.default(t,e.default);if(e.implies!==void 0)this.implies(t,e.implies);if(e.nargs!==void 0)this.nargs(t,e.nargs);if(e.config)this.config(t,e.configParser);if(e.normalize)this.normalize(t);if(e.choices)this.choices(t,e.choices);if(e.coerce)this.coerce(t,e.coerce);if(e.group)this.group(t,e.group);if(e.boolean||e.type==="boolean"){if(this.boolean(t),e.alias)this.boolean(e.alias)}if(e.array||e.type==="array"){if(this.array(t),e.alias)this.array(e.alias)}if(e.number||e.type==="number"){if(this.number(t),e.alias)this.number(e.alias)}if(e.string||e.type==="string"){if(this.string(t),e.alias)this.string(e.alias)}if(e.count||e.type==="count")this.count(t);if(typeof e.global==="boolean")this.global(t,e.global);if(e.defaultDescription)p(this,k,"f").defaultDescription[t]=e.defaultDescription;if(e.skipValidation)this.skipValidation(t);let r=e.describe||e.description||e.desc,i=p(this,q,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(i,t)||typeof r==="string")this.describe(t,r);if(e.hidden)this.hide(t);if(e.requiresArg)this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,o){if(_("[string|array] [function|boolean|object] [function]",[t,e,o],arguments.length),this[Ri](),typeof t>"u")t=p(this,Oe,"f");if(typeof e==="object")T(this,Ve,e,"f"),e=o;if(typeof e==="function")T(this,vt,e,"f"),e=!1;if(!e)T(this,Oe,t,"f");if(p(this,vt,"f"))T(this,zt,!1,"f");let n=this[jo](t,!!e),r=this.parsed;if(p(this,Jt,"f").setParsed(this.parsed),ht(n))return n.then((i)=>{if(p(this,vt,"f"))p(this,vt,"f").call(this,p(this,Me,"f"),i,p(this,yt,"f"));return i}).catch((i)=>{if(p(this,vt,"f"))p(this,vt,"f")(i,this.parsed.argv,p(this,yt,"f"));throw i}).finally(()=>{this[sr](),this.parsed=r});else{if(p(this,vt,"f"))p(this,vt,"f").call(this,p(this,Me,"f"),n,p(this,yt,"f"));this[sr](),this.parsed=r}return n}parseAsync(t,e,o){let n=this.parse(t,e,o);return!ht(n)?Promise.resolve(n):n}parseSync(t,e,o){let n=this.parse(t,e,o);if(ht(n))throw new ft(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return _("<object>",[t],arguments.length),T(this,an,t,"f"),this}pkgConf(t,e){_("<string> [string]",[t,e],arguments.length);let o=null,n=this[er](e||p(this,ze,"f"));if(n[t]&&typeof n[t]==="object")o=Io(n[t],e||p(this,ze,"f"),this[Qe]()["deep-merge-config"]||!1,p(this,K,"f")),p(this,k,"f").configObjects=(p(this,k,"f").configObjects||[]).concat(o);return this}positional(t,e){_("<string> <object>",[t,e],arguments.length);let o=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=Ee(e,(i,s)=>{if(i==="type"&&!["string","number","boolean"].includes(s))return!1;return o.includes(i)});let n=p(this,Ao,"f").fullCommands[p(this,Ao,"f").fullCommands.length-1],r=n?p(this,bt,"f").cmdToParseOptions(n):{array:[],alias:{},default:{},demand:{}};return co(r).forEach((i)=>{let s=r[i];if(Array.isArray(s)){if(s.indexOf(t)!==-1)e[i]=!0}else if(s[t]&&!(i in e))e[i]=s[t]}),this.group(t,p(this,q,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return _("[boolean]",[t],arguments.length),T(this,ln,t,"f"),this}required(t,e,o){return this.demand(t,e,o)}require(t,e,o){return this.demand(t,e,o)}requiresArg(t){if(_("<array|string|object> [number]",[t],arguments.length),typeof t==="string"&&p(this,k,"f").narg[t])return this;else this[ho](this.requiresArg.bind(this),"narg",t,NaN);return this}showCompletionScript(t,e){return _("[string] [string]",[t,e],arguments.length),t=t||this.$0,p(this,lo,"f").log(p(this,Jt,"f").generateCompletionScript(t,e||p(this,Tt,"f")||"completion")),this}showHelp(t){if(_("[string|function]",[t],arguments.length),T(this,Gt,!0,"f"),!p(this,q,"f").hasCachedHelpMessage()){if(!this.parsed){let o=this[jo](p(this,Oe,"f"),void 0,void 0,0,!0);if(ht(o))return o.then(()=>{p(this,q,"f").showHelp(t)}),this}let e=p(this,bt,"f").runDefaultBuilderOn(this);if(ht(e))return e.then(()=>{p(this,q,"f").showHelp(t)}),this}return p(this,q,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return _("[boolean|string] [string]",[t,e],arguments.length),p(this,q,"f").showHelpOnFail(t,e),this}showVersion(t){return _("[string|function]",[t],arguments.length),p(this,q,"f").showVersion(t),this}skipValidation(t){return _("<array|string>",[t],arguments.length),this[We]("skipValidation",t),this}strict(t){return _("[boolean]",[t],arguments.length),T(this,Xe,t!==!1,"f"),this}strictCommands(t){return _("[boolean]",[t],arguments.length),T(this,qe,t!==!1,"f"),this}strictOptions(t){return _("[boolean]",[t],arguments.length),T(this,Ze,t!==!1,"f"),this}string(t){return _("<array|string>",[t],arguments.length),this[We]("string",t),this[to](t),this}terminalWidth(){return _([],0),p(this,K,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return _("<object>",[t],arguments.length),T(this,Ue,!1,"f"),p(this,K,"f").y18n.updateLocale(t),this}usage(t,e,o,n){if(_("<string|null|undefined> [string|boolean] [function|object] [function]",[t,e,o,n],arguments.length),e!==void 0)if(Bt(t,null,p(this,K,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,e,o,n);else throw new ft(".usage() description must start with $0 if being used as alias for .command()");else return p(this,q,"f").usage(t),this}usageConfiguration(t){return _("<object>",[t],arguments.length),T(this,fn,t,"f"),this}version(t,e,o){if(_("[boolean|string] [string] [string]",[t,e,o],arguments.length),p(this,re,"f"))this[Yn](p(this,re,"f")),p(this,q,"f").version(void 0),T(this,re,null,"f");if(arguments.length===0)o=this[Wi](),t="version";else if(arguments.length===1){if(t===!1)return this;o=t,t="version"}else if(arguments.length===2)o=e,e=void 0;return T(this,re,typeof t==="string"?t:"version","f"),e=e||p(this,q,"f").deferY18nLookup("Show version number"),p(this,q,"f").version(o||void 0),this.boolean(p(this,re,"f")),this.describe(p(this,re,"f"),e),this}wrap(t){return _("<number|null|undefined>",[t],arguments.length),p(this,q,"f").wrap(t),this}[(bt=new WeakMap,ze=new WeakMap,Ao=new WeakMap,Jt=new WeakMap,Tt=new WeakMap,on=new WeakMap,Me=new WeakMap,Ue=new WeakMap,nn=new WeakMap,zt=new WeakMap,rn=new WeakMap,Ut=new WeakMap,ne=new WeakMap,Gt=new WeakMap,Vt=new WeakMap,sn=new WeakMap,lo=new WeakMap,yt=new WeakMap,k=new WeakMap,cn=new WeakMap,an=new WeakMap,vt=new WeakMap,Ve=new WeakMap,fo=new WeakMap,Ke=new WeakMap,Oe=new WeakMap,ln=new WeakMap,K=new WeakMap,Xe=new WeakMap,qe=new WeakMap,Ze=new WeakMap,q=new WeakMap,fn=new WeakMap,re=new WeakMap,gt=new WeakMap,Pi)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(e){}return t}[yi](){return{log:(...t)=>{if(!this[hn]())console.log(...t);if(T(this,Gt,!0,"f"),p(this,yt,"f").length)T(this,yt,p(this,yt,"f")+`
219
+ `,"f");T(this,yt,p(this,yt,"f")+t.join(" "),"f")},error:(...t)=>{if(!this[hn]())console.error(...t);if(T(this,Gt,!0,"f"),p(this,yt,"f").length)T(this,yt,p(this,yt,"f")+`
220
+ `,"f");T(this,yt,p(this,yt,"f")+t.join(" "),"f")}}}[Yn](t){co(p(this,k,"f")).forEach((e)=>{if(((n)=>n==="configObjects")(e))return;let o=p(this,k,"f")[e];if(Array.isArray(o)){if(o.includes(t))o.splice(o.indexOf(t),1)}else if(typeof o==="object")delete o[t]}),delete p(this,q,"f").getDescriptions()[t]}[Ei](t,e,o){if(!p(this,nn,"f")[o])p(this,K,"f").process.emitWarning(t,e),p(this,nn,"f")[o]=!0}[Ri](){p(this,rn,"f").push({options:p(this,k,"f"),configObjects:p(this,k,"f").configObjects.slice(0),exitProcess:p(this,zt,"f"),groups:p(this,ne,"f"),strict:p(this,Xe,"f"),strictCommands:p(this,qe,"f"),strictOptions:p(this,Ze,"f"),completionCommand:p(this,Tt,"f"),output:p(this,yt,"f"),exitError:p(this,Me,"f"),hasOutput:p(this,Gt,"f"),parsed:this.parsed,parseFn:p(this,vt,"f"),parseContext:p(this,Ve,"f")}),p(this,q,"f").freeze(),p(this,gt,"f").freeze(),p(this,bt,"f").freeze(),p(this,Ut,"f").freeze()}[Mi](){let t="",e;if(/\b(node|iojs|electron)(\.exe)?$/.test(p(this,K,"f").process.argv()[0]))e=p(this,K,"f").process.argv().slice(1,2);else e=p(this,K,"f").process.argv().slice(0,1);if(t=e.map((o)=>{let n=this[vi](p(this,ze,"f"),o);return o.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<o.length?n:o}).join(" ").trim(),p(this,K,"f").getEnv("_")&&p(this,K,"f").getProcessArgvBin()===p(this,K,"f").getEnv("_"))t=p(this,K,"f").getEnv("_").replace(`${p(this,K,"f").path.dirname(p(this,K,"f").process.execPath())}/`,"");return t}[Qe](){return p(this,an,"f")}[Oi](){return p(this,fn,"f")}[tr](){if(!p(this,Ue,"f"))return;let t=p(this,K,"f").getEnv("LC_ALL")||p(this,K,"f").getEnv("LC_MESSAGES")||p(this,K,"f").getEnv("LANG")||p(this,K,"f").getEnv("LANGUAGE")||"en_US";this.locale(t.replace(/[.:].*/,""))}[Wi](){return this[er]().version||"unknown"}[Di](t){let e=t["--"]?t["--"]:t._;for(let o=0,n;(n=e[o])!==void 0;o++)if(p(this,K,"f").Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`))))e[o]=Number(n);return t}[er](t){let e=t||"*";if(p(this,fo,"f")[e])return p(this,fo,"f")[e];let o={};try{let n=t||p(this,K,"f").mainFilename;if(!t&&p(this,K,"f").path.extname(n))n=p(this,K,"f").path.dirname(n);let r=p(this,K,"f").findUp(n,(i,s)=>{if(s.includes("package.json"))return"package.json";else return});Bt(r,void 0,p(this,K,"f")),o=JSON.parse(p(this,K,"f").readFileSync(r,"utf8"))}catch(n){}return p(this,fo,"f")[e]=o||{},p(this,fo,"f")[e]}[We](t,e){e=[].concat(e),e.forEach((o)=>{o=this[rr](o),p(this,k,"f")[t].push(o)})}[ho](t,e,o,n){this[nr](t,e,o,n,(r,i,s)=>{p(this,k,"f")[r][i]=s})}[or](t,e,o,n){this[nr](t,e,o,n,(r,i,s)=>{p(this,k,"f")[r][i]=(p(this,k,"f")[r][i]||[]).concat(s)})}[nr](t,e,o,n,r){if(Array.isArray(o))o.forEach((i)=>{t(i,n)});else if(((i)=>typeof i==="object")(o))for(let i of co(o))t(i,o[i]);else r(e,this[rr](o),n)}[rr](t){if(t==="__proto__")return"___proto___";return t}[ir](t,e){return this[ho](this[ir].bind(this),"key",t,e),this}[sr](){var t,e,o,n,r,i,s,c,l,a,h,u;let d=p(this,rn,"f").pop();Bt(d,void 0,p(this,K,"f"));let g;t=this,e=this,o=this,n=this,r=this,i=this,s=this,c=this,l=this,a=this,h=this,u=this,{options:{set value(x){T(t,k,x,"f")}}.value,configObjects:g,exitProcess:{set value(x){T(e,zt,x,"f")}}.value,groups:{set value(x){T(o,ne,x,"f")}}.value,output:{set value(x){T(n,yt,x,"f")}}.value,exitError:{set value(x){T(r,Me,x,"f")}}.value,hasOutput:{set value(x){T(i,Gt,x,"f")}}.value,parsed:this.parsed,strict:{set value(x){T(s,Xe,x,"f")}}.value,strictCommands:{set value(x){T(c,qe,x,"f")}}.value,strictOptions:{set value(x){T(l,Ze,x,"f")}}.value,completionCommand:{set value(x){T(a,Tt,x,"f")}}.value,parseFn:{set value(x){T(h,vt,x,"f")}}.value,parseContext:{set value(x){T(u,Ve,x,"f")}}.value}=d,p(this,k,"f").configObjects=g,p(this,q,"f").unfreeze(),p(this,gt,"f").unfreeze(),p(this,bt,"f").unfreeze(),p(this,Ut,"f").unfreeze()}[Fi](t,e){return Je(e,(o)=>{return t(o),o})}getInternalMethods(){return{getCommandInstance:this[Bi].bind(this),getContext:this[Li].bind(this),getHasOutput:this[Ii].bind(this),getLoggerInstance:this[Ai].bind(this),getParseContext:this[ji].bind(this),getParserConfiguration:this[Qe].bind(this),getUsageConfiguration:this[Oi].bind(this),getUsageInstance:this[_i].bind(this),getValidationInstance:this[Ti].bind(this),hasParseCallback:this[hn].bind(this),isGlobalContext:this[Gi].bind(this),postProcess:this[Ye].bind(this),reset:this[cr].bind(this),runValidation:this[ar].bind(this),runYargsParserAndExecuteCommands:this[jo].bind(this),setHasOutput:this[Hi].bind(this)}}[Bi](){return p(this,bt,"f")}[Li](){return p(this,Ao,"f")}[Ii](){return p(this,Gt,"f")}[Ai](){return p(this,lo,"f")}[ji](){return p(this,Ve,"f")||{}}[_i](){return p(this,q,"f")}[Ti](){return p(this,gt,"f")}[hn](){return!!p(this,vt,"f")}[Gi](){return p(this,sn,"f")}[Ye](t,e,o,n){if(o)return t;if(ht(t))return t;if(!e)t=this[Pi](t);if(this[Qe]()["parse-positional-numbers"]||this[Qe]()["parse-positional-numbers"]===void 0)t=this[Di](t);if(n)t=Ne(t,this,p(this,Ut,"f").getMiddleware(),!1);return t}[cr](t={}){T(this,k,p(this,k,"f")||{},"f");let e={};e.local=p(this,k,"f").local||[],e.configObjects=p(this,k,"f").configObjects||[];let o={};e.local.forEach((i)=>{o[i]=!0,(t[i]||[]).forEach((s)=>{o[s]=!0})}),Object.assign(p(this,Ke,"f"),Object.keys(p(this,ne,"f")).reduce((i,s)=>{let c=p(this,ne,"f")[s].filter((l)=>!(l in o));if(c.length>0)i[s]=c;return i},{})),T(this,ne,{},"f");let n=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(n.forEach((i)=>{e[i]=(p(this,k,"f")[i]||[]).filter((s)=>!o[s])}),r.forEach((i)=>{e[i]=Ee(p(this,k,"f")[i],(s)=>!o[s])}),e.envPrefix=p(this,k,"f").envPrefix,T(this,k,e,"f"),T(this,q,p(this,q,"f")?p(this,q,"f").reset(o):di(this,p(this,K,"f")),"f"),T(this,gt,p(this,gt,"f")?p(this,gt,"f").reset(o):Si(this,p(this,q,"f"),p(this,K,"f")),"f"),T(this,bt,p(this,bt,"f")?p(this,bt,"f").reset():hi(p(this,q,"f"),p(this,gt,"f"),p(this,Ut,"f"),p(this,K,"f")),"f"),!p(this,Jt,"f"))T(this,Jt,wi(this,p(this,q,"f"),p(this,bt,"f"),p(this,K,"f")),"f");return p(this,Ut,"f").reset(),T(this,Tt,null,"f"),T(this,yt,"","f"),T(this,Me,null,"f"),T(this,Gt,!1,"f"),this.parsed=!1,this}[vi](t,e){return p(this,K,"f").path.relative(t,e)}[jo](t,e,o,n=0,r=!1){let i=!!o||r;t=t||p(this,Oe,"f"),p(this,k,"f").__=p(this,K,"f").y18n.__,p(this,k,"f").configuration=this[Qe]();let s=!!p(this,k,"f").configuration["populate--"],c=Object.assign({},p(this,k,"f").configuration,{"populate--":!0}),l=p(this,K,"f").Parser.detailed(t,Object.assign({},p(this,k,"f"),{configuration:{"parse-positional-numbers":!1,...c}})),a=Object.assign(l.argv,p(this,Ve,"f")),h=void 0,u=l.aliases,d=!1,g=!1;if(Object.keys(a).forEach((x)=>{if(x===p(this,Vt,"f")&&a[x])d=!0;else if(x===p(this,re,"f")&&a[x])g=!0}),a.$0=this.$0,this.parsed=l,n===0)p(this,q,"f").clearCachedHelpMessage();try{if(this[tr](),e)return this[Ye](a,s,!!o,!1);if(p(this,Vt,"f")){if([p(this,Vt,"f")].concat(u[p(this,Vt,"f")]||[]).filter((E)=>E.length>1).includes(""+a._[a._.length-1]))a._.pop(),d=!0}T(this,sn,!1,"f");let x=p(this,bt,"f").getCommands(),m=p(this,Jt,"f").completionKey in a,b=d||m||r;if(a._.length){if(x.length){let $;for(let E=n||0,R;a._[E]!==void 0;E++)if(R=String(a._[E]),x.includes(R)&&R!==p(this,Tt,"f")){let P=p(this,bt,"f").runCommand(R,this,l,E+1,r,d||g||r);return this[Ye](P,s,!!o,!1)}else if(!$&&R!==p(this,Tt,"f")){$=R;break}if(!p(this,bt,"f").hasDefaultCommand()&&p(this,ln,"f")&&$&&!b)p(this,gt,"f").recommendCommands($,x)}if(p(this,Tt,"f")&&a._.includes(p(this,Tt,"f"))&&!m){if(p(this,zt,"f"))Re(!0);this.showCompletionScript(),this.exit(0)}}if(p(this,bt,"f").hasDefaultCommand()&&!b){let $=p(this,bt,"f").runCommand(null,this,l,0,r,d||g||r);return this[Ye]($,s,!!o,!1)}if(m){if(p(this,zt,"f"))Re(!0);t=[].concat(t);let $=t.slice(t.indexOf(`--${p(this,Jt,"f").completionKey}`)+1);return p(this,Jt,"f").getCompletion($,(E,R)=>{if(E)throw new ft(E.message);(R||[]).forEach((P)=>{p(this,lo,"f").log(P)}),this.exit(0)}),this[Ye](a,!s,!!o,!1)}if(!p(this,Gt,"f")){if(d){if(p(this,zt,"f"))Re(!0);i=!0,this.showHelp("log"),this.exit(0)}else if(g){if(p(this,zt,"f"))Re(!0);i=!0,p(this,q,"f").showVersion("log"),this.exit(0)}}if(!i&&p(this,k,"f").skipValidation.length>0)i=Object.keys(a).some(($)=>p(this,k,"f").skipValidation.indexOf($)>=0&&a[$]===!0);if(!i){if(l.error)throw new ft(l.error.message);if(!m){let $=this[ar](u,{},l.error);if(!o)h=Ne(a,this,p(this,Ut,"f").getMiddleware(),!0);if(h=this[Fi]($,h!==null&&h!==void 0?h:a),ht(h)&&!o)h=h.then(()=>{return Ne(a,this,p(this,Ut,"f").getMiddleware(),!1)})}}}catch(x){if(x instanceof ft)p(this,q,"f").fail(x.message,x);else throw x}return this[Ye](h!==null&&h!==void 0?h:a,s,!!o,!0)}[ar](t,e,o,n){let r={...this.getDemandedOptions()};return(i)=>{if(o)throw new ft(o.message);p(this,gt,"f").nonOptionCount(i),p(this,gt,"f").requiredArguments(i,r);let s=!1;if(p(this,qe,"f"))s=p(this,gt,"f").unknownCommands(i);if(p(this,Xe,"f")&&!s)p(this,gt,"f").unknownArguments(i,t,e,!!n);else if(p(this,Ze,"f"))p(this,gt,"f").unknownArguments(i,t,{},!1,!1);p(this,gt,"f").limitedChoices(i),p(this,gt,"f").implications(i),p(this,gt,"f").conflicting(i)}}[Hi](){T(this,Gt,!0,"f")}[to](t){if(typeof t==="string")p(this,k,"f").key[t]=!0;else for(let e of t)p(this,k,"f").key[e]=!0}}function ui(t){return!!t&&typeof t.getInternalMethods==="function"}var Ml=ki(Vn),Ji=Ml;import{readFileSync as La}from"fs";import{join as Gr}from"path";function jp(){let t=import.meta.dir;for(let e=0;e<5;e++){let o=Gr(t,"package.json");try{return La(o,"utf-8"),o}catch{}t=Gr(t,"..")}return Gr(import.meta.dir,"../../package.json")}var _p=JSON.parse(La(jp(),"utf-8"));if(process.argv.length===2){let{launchTUI:t}=await Promise.resolve().then(() => (ic(),rc));await t()}else{let[t,e,o,n,r,i,s,c,l,a,h,u,d,g,x,m,b,$,E,R]=await Promise.all([Promise.resolve().then(() => (dc(),pc)),Promise.resolve().then(() => (xc(),mc)),Promise.resolve().then(() => (bc(),wc)),Promise.resolve().then(() => (Sc(),Cc)),Promise.resolve().then(() => (Rc(),Ec)),Promise.resolve().then(() => (Ic(),Lc)),Promise.resolve().then(() => (jc(),Ac)),Promise.resolve().then(() => (vc(),Gc)),Promise.resolve().then(() => (Nc(),kc)),Promise.resolve().then(() => (Uc(),zc)),Promise.resolve().then(() => (Xc(),Kc)),Promise.resolve().then(() => (Zc(),qc)),Promise.resolve().then(() => (Yc(),Qc)),Promise.resolve().then(() => (ea(),ta)),Promise.resolve().then(() => (ha(),fa)),Promise.resolve().then(() => (pa(),ua)),Promise.resolve().then(() => (ma(),da)),Promise.resolve().then(() => ($a(),Sa)),Promise.resolve().then(() => (ya(),Pa)),Promise.resolve().then(() => (Ba(),Fa))]);Ji(Un(process.argv)).locale("en").scriptName("omw").version(`oh-my-worktree v${_p.version}`).alias("version","v").help("help").alias("help","h").option("no-color",{type:"boolean",description:"Disable color output"}).command(t.default).command(e.default).command(o.default).command(n.default).command(r.default).command(i.default).command(s.default).command(c.default).command(l.default).command(a.default).command(h.default).command(u.default).command(d.default).command(g.default).command(x.default).command(m.default).command(b.default).command($.default).command(E.default).command(R.default).completion("completion","Generate shell completion script").demandCommand(1,"Please specify a command. Run --help to see available commands.").strict().parse()}