@crewx/sdk 0.9.0-rc.97 → 0.9.0-rc.99

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.
@@ -1,3 +1,3 @@
1
- 'use strict';var m=require('path'),crypto=require('crypto'),fs=require('fs'),os=require('os'),child_process=require('child_process'),string_decoder=require('string_decoder'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var m__namespace=/*#__PURE__*/_interopNamespace(m);var B=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var q={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},Y=os.homedir;function N(e){return typeof e!="string"?void 0:e.trim()||void 0}function O(e){return N(e)?.toLowerCase()??""}function b(e){try{return fs.statSync(e).isFile()}catch{return false}}function Ke(e,t){if(e===t)return true;let n=m__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!m__namespace.default.isAbsolute(n)}function je(e,t){if(m__namespace.default.basename(e)!==".bin")return false;let n=m__namespace.default.dirname(e);if(m__namespace.default.basename(n)!=="node_modules")return false;let r=m__namespace.default.dirname(n);return Ke(r,t)}function Q(e,t={}){if(e.includes("/")||e.includes("\\")||m__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=m__namespace.default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=m__namespace.default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let P=m__namespace.default.resolve(o,u);if(!(c&&je(P,o)))for(let h of f){let C=O(h),g=h.toUpperCase();for(let w of [h,C,g]){let y=m__namespace.default.join(P,`${e}${w}`);if(b(y))return y}}}return e}function ze(e){if(!b(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=m__namespace.default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,m__namespace.default.sep).replace(/^[\\/]+/,""),u=m__namespace.default.resolve(n,f);b(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,m__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,m__namespace.default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&b(l)&&o.push(l);}let s=i=>i.find(a=>{let l=O(m__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function qe(e,t){if(typeof t=="string")return N(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?N(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?N(n):void 0;if(r)return r}return null}function Ye(e,t){if(!t)return null;let n=m__namespace.default.dirname(e),r=[m__namespace.default.resolve(n,"..",t),m__namespace.default.resolve(n,"node_modules",t)];for(let o of r){let c=m__namespace.default.join(o,"package.json");if(b(c))try{let s=JSON.parse(fs.readFileSync(c,"utf8")),i=qe(t,s.bin);if(!i)continue;let a=m__namespace.default.resolve(o,i);if(b(a))return a}catch{}}return null}function Qe(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=O(m__namespace.default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=ze(s)??Ye(s,e.packageName);return a?O(m__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct"}}function Ze(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${m__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ee(e){let t=Qe(e);return Ze({candidate:t})}function te(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var T="\uFFFD",$=8,re=1e3,tt=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),D;function U(e){let t=0;for(let n of e)n===T&&(t+=1);return t}function H(e,t){return U(t)<U(e)?t:e}function nt(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function rt(e){if(e!==65001)return tt.get(e)}function ot(e){let t=rt(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function st(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),re),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:re,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(nt(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ie(){return process.platform!=="win32"?Promise.resolve(null):(D||(D=st(),D.then(e=>{},()=>{})),D)}function it(){process.platform==="win32"&&ie();}function se(e,t){if(t.length>=$)return t.subarray(t.length-$);let n=$-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var k=class{platform;detectCodePage;utf8Decoder=new string_decoder.StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ie,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:ot(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(T);if(r&&(this.utf8Decoder=new string_decoder.StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=se(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),H(d,f)}if(U(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=se(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return H(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(T)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(T)?H(n,o):n}};it();var ae=3e3,ct=2e3,lt=25,ut=100;function ue(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ce(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function dt(e){return Number.isSafeInteger(e)&&e>0}function ft(e,t){return new Promise(n=>{let r;try{r=child_process.spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:ue(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${ae}ms`)});},ae);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function mt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):ft(e,t)}function pt(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function ht(){return new Promise(e=>{setImmediate(e);})}function A(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ce(n)==="ESRCH"?"not_found":ce(n)==="EPERM"?"alive":"unknown"}}function gt(e,t){let n=A(-e,t),r=A(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function de(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??lt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await ht();;){let d=gt(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,pt(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function le(e,t,n,r,o){let c=await de(e,t,o.hardConfirmMs??ut,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function fe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!dt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=A(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await mt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:ue(h)};}let P=A(e,c);return P==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(P==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return le(e,c,i,r,t);if(await de(e,c,t.graceMs??ct,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await le(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var wt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function Pt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function me(e){return Pt(e,wt)}var pe=3e4;function he(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}fe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var ge=(e,t,n={})=>new Promise((r,o)=>{let c=me(n.env??process.env),s=process.platform,i;try{let w=ee({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=te(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new k({platform:s}),P=new k({platform:s}),h=Promise.resolve(),C=Promise.resolve(),g=setTimeout(()=>{f||(f=true,he(a),o(new Error(`Command timed out after ${n.timeoutMs??pe}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??pe);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{C=C.then(async()=>{d+=await P.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,C]);let[y,$e]=await Promise.all([u.end(),P.end()]);f||(l+=y,d+=$e,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(y=>{f||(f=true,clearTimeout(g),o(y instanceof Error?y:new Error(String(y))));});});});function yt(){try{return (typeof B=="function"?B:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function vt(){let e=[yt(),m.join(__dirname,"../../package.json"),m.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Pe=vt();var E=m__namespace.win32;function V(e){return E.join(e,".crewx")}function Ee(e){return E.join(V(e),"shortcut.json")}function Ce(e){return E.join(V(e),"launcher.json")}function ye(e){return E.join(V(e),"bin","crewx-launcher.cmd")}function ve(e){return E.join(e,"CrewX.lnk")}function X(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var Rt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Re(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Rt],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:E.join(t,"Desktop"),source:"fallback"}:null}function G(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function be(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function bt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(P=>Number.parseInt(P,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function _(e,t){return bt(e,t)<0}var _e=m__namespace.win32,xe=1;function Ie(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??xe,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function W(e,t,n){let r={schema:xe,...n,updatedAt:new Date().toISOString()};e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function M(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Le(e,t,n){e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var kt=m__namespace.win32,x=1;function _t(e){return e.replace(/%/g,"%%")}function xt(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${_t(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
- `)}function Oe(e){let t=M(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=x&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=xt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(kt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Le(e.fs,e.launcherManifestPath,{schema:x,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof p?s:new p("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:x}}var It=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),Lt=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function De(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:t});}catch(r){throw new p("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new p("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function Te(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Ae(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Lt],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var K=m__namespace.win32;async function I(e){let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?K.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Nt=/EACCES|EPERM|EROFS/,Ot=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Dt=/^\d+\.\d+\.\d+/;function Tt(e){return !!e&&e!=="0.0.0"&&Dt.test(e)}var J=10*6e4;async function Me(e){if(!Tt(e.targetVersion))throw new p("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!_(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(s){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
- ${o.stderr}`;if(Nt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||K.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:K.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:J});}catch(l){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await I({env:i,cwd:e.cwd,run:e.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Ot.test(c)){if(!e.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(i){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Wt(e){return e.run??ge}function Mt(e){return e.fs??q}async function F(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Y,o=Wt(e),c=Mt(e),s=e.runningVersion??Pe,i=e.cwd??process.cwd(),a=r(),l=Ee(a),d=Ce(a),f=ye(a),u=null;t==="win32"&&(u=await Re({env:n,homedir:r,run:o}));let P=u?ve(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:P}}function Fe(e){return e?m__namespace.win32.normalize(e).toLowerCase().endsWith(`${m__namespace.win32.sep}bin${m__namespace.win32.sep}crewx.ico`):false}function j(e,t){let n=e.readBinaryFileSync;if(n)try{return crypto.createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Ft(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function v(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ie(e.fs,e.shortcutManifestPath),r=M(e.fs,e.launcherManifestPath),o=await I({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Ae({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&X(u.targetPath,e.wrapperPath)?d=true:u&&be(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&_(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let P=!r||r.schema<x||!e.fs.existsSync(e.wrapperPath);if(u){let h=Te(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=Be(o,e.fs);g?X(h,g)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true:Fe(h)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=P||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function Be(e,t){if(!e?.installed||!e.prefix)return;let n=m__namespace.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function R(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Bt(e={}){let t=await F(e),n=await v(t);return R(n)}async function $t(e={}){let t=await F(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await v(t),r=R(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&_(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Me({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Oe({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=Be(s,t.fs)??(n.iconPath&&Fe(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new p("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await De({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?j(t.fs,g):void 0;w&&(a=w);}o&&W(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Ft(t);let h=await v(t),C=R(h);return {...C,errors:[...C.errors,...i],changed:o,installedGlobal:c}}async function Ht(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}W(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await v(t);return R(o)}async function Ut(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;W(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await v(t);return R(o)}exports.ShortcutError=p;exports.dismissShortcutNotice=Ut;exports.getShortcutStatus=Bt;exports.installShortcut=$t;exports.killProcessTree=he;exports.uninstallShortcut=Ht;
1
+ 'use strict';var p=require('path'),crypto=require('crypto'),fs=require('fs'),os=require('os'),child_process=require('child_process'),string_decoder=require('string_decoder'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var p__namespace=/*#__PURE__*/_interopNamespace(p);var B=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var q={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},Y=os.homedir;function N(e){return typeof e!="string"?void 0:e.trim()||void 0}function O(e){return N(e)?.toLowerCase()??""}function b(e){try{return fs.statSync(e).isFile()}catch{return false}}function Ke(e,t){if(e===t)return true;let n=p__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!p__namespace.default.isAbsolute(n)}function je(e,t){if(p__namespace.default.basename(e)!==".bin")return false;let n=p__namespace.default.dirname(e);if(p__namespace.default.basename(n)!=="node_modules")return false;let r=p__namespace.default.dirname(n);return Ke(r,t)}function Q(e,t={}){if(e.includes("/")||e.includes("\\")||p__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=p__namespace.default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=p__namespace.default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let P=p__namespace.default.resolve(o,u);if(!(c&&je(P,o)))for(let h of f){let C=O(h),g=h.toUpperCase();for(let w of [h,C,g]){let y=p__namespace.default.join(P,`${e}${w}`);if(b(y))return y}}}return e}function ze(e){if(!b(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=p__namespace.default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,""),u=p__namespace.default.resolve(n,f);b(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,p__namespace.default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&b(l)&&o.push(l);}let s=i=>i.find(a=>{let l=O(p__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function qe(e,t){if(typeof t=="string")return N(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?N(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?N(n):void 0;if(r)return r}return null}function Ye(e,t){if(!t)return null;let n=p__namespace.default.dirname(e),r=[p__namespace.default.resolve(n,"..",t),p__namespace.default.resolve(n,"node_modules",t)];for(let o of r){let c=p__namespace.default.join(o,"package.json");if(b(c))try{let s=JSON.parse(fs.readFileSync(c,"utf8")),i=qe(t,s.bin);if(!i)continue;let a=p__namespace.default.resolve(o,i);if(b(a))return a}catch{}}return null}function Qe(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=O(p__namespace.default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=ze(s)??Ye(s,e.packageName);return a?O(p__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct"}}function Ze(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${p__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ee(e){let t=Qe(e);return Ze({candidate:t})}function te(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var D="\uFFFD",$=8,re=1e3,tt=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),T;function U(e){let t=0;for(let n of e)n===D&&(t+=1);return t}function H(e,t){return U(t)<U(e)?t:e}function nt(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function rt(e){if(e!==65001)return tt.get(e)}function ot(e){let t=rt(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function st(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),re),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:re,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(nt(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ie(){return process.platform!=="win32"?Promise.resolve(null):(T||(T=st(),T.then(e=>{},()=>{})),T)}function it(){process.platform==="win32"&&ie();}function se(e,t){if(t.length>=$)return t.subarray(t.length-$);let n=$-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var k=class{platform;detectCodePage;utf8Decoder=new string_decoder.StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ie,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:ot(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(D);if(r&&(this.utf8Decoder=new string_decoder.StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=se(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),H(d,f)}if(U(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=se(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return H(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(D)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(D)?H(n,o):n}};it();var ae=3e3;var ct=2e3,lt=25,ut=100;function ue(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ce(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function dt(e){return Number.isSafeInteger(e)&&e>0}function ft(e,t){return new Promise(n=>{let r;try{r=child_process.spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:ue(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${ae}ms`)});},ae);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):ft(e,t)}function mt(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function ht(){return new Promise(e=>{setImmediate(e);})}function A(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ce(n)==="ESRCH"?"not_found":ce(n)==="EPERM"?"alive":"unknown"}}function gt(e,t){let n=A(-e,t),r=A(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function de(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??lt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await ht();;){let d=gt(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,mt(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function le(e,t,n,r,o){let c=await de(e,t,o.hardConfirmMs??ut,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function fe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!dt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=A(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:ue(h)};}let P=A(e,c);return P==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(P==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return le(e,c,i,r,t);if(await de(e,c,t.graceMs??ct,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await le(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var wt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function Pt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function pe(e){return Pt(e,wt)}var me=3e4;function he(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}fe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var ge=(e,t,n={})=>new Promise((r,o)=>{let c=pe(n.env??process.env),s=process.platform,i;try{let w=ee({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=te(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new k({platform:s}),P=new k({platform:s}),h=Promise.resolve(),C=Promise.resolve(),g=setTimeout(()=>{f||(f=true,he(a),o(new Error(`Command timed out after ${n.timeoutMs??me}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??me);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{C=C.then(async()=>{d+=await P.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,C]);let[y,$e]=await Promise.all([u.end(),P.end()]);f||(l+=y,d+=$e,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(y=>{f||(f=true,clearTimeout(g),o(y instanceof Error?y:new Error(String(y))));});});});function yt(){try{return (typeof B=="function"?B:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function vt(){let e=[yt(),p.join(__dirname,"../../package.json"),p.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Pe=vt();var E=p__namespace.win32;function V(e){return E.join(e,".crewx")}function Ee(e){return E.join(V(e),"shortcut.json")}function Ce(e){return E.join(V(e),"launcher.json")}function ye(e){return E.join(V(e),"bin","crewx-launcher.cmd")}function ve(e){return E.join(e,"CrewX.lnk")}function X(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var Rt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Re(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Rt],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:E.join(t,"Desktop"),source:"fallback"}:null}function G(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function be(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function bt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(P=>Number.parseInt(P,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function _(e,t){return bt(e,t)<0}var _e=p__namespace.win32,xe=1;function Ie(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??xe,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function W(e,t,n){let r={schema:xe,...n,updatedAt:new Date().toISOString()};e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function M(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Le(e,t,n){e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var kt=p__namespace.win32,x=1;function _t(e){return e.replace(/%/g,"%%")}function xt(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${_t(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
+ `)}function Oe(e){let t=M(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=x&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=xt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(kt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Le(e.fs,e.launcherManifestPath,{schema:x,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof m?s:new m("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:x}}var It=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),Lt=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function Te(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:t});}catch(r){throw new m("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new m("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function De(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Ae(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Lt],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var K=p__namespace.win32;async function I(e){let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?K.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Nt=/EACCES|EPERM|EROFS/,Ot=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Tt=/^\d+\.\d+\.\d+/;function Dt(e){return !!e&&e!=="0.0.0"&&Tt.test(e)}var J=10*6e4;async function Me(e){if(!Dt(e.targetVersion))throw new m("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!_(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(s){throw new m("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
+ ${o.stderr}`;if(Nt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||K.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:K.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:J});}catch(l){throw new m("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await I({env:i,cwd:e.cwd,run:e.run})};throw new m("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Ot.test(c)){if(!e.installRoot)throw new m("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(i){throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new m("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Wt(e){return e.run??ge}function Mt(e){return e.fs??q}async function F(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Y,o=Wt(e),c=Mt(e),s=e.runningVersion??Pe,i=e.cwd??process.cwd(),a=r(),l=Ee(a),d=Ce(a),f=ye(a),u=null;t==="win32"&&(u=await Re({env:n,homedir:r,run:o}));let P=u?ve(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:P}}function Fe(e){return e?p__namespace.win32.normalize(e).toLowerCase().endsWith(`${p__namespace.win32.sep}bin${p__namespace.win32.sep}crewx.ico`):false}function j(e,t){let n=e.readBinaryFileSync;if(n)try{return crypto.createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Ft(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function v(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ie(e.fs,e.shortcutManifestPath),r=M(e.fs,e.launcherManifestPath),o=await I({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Ae({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&X(u.targetPath,e.wrapperPath)?d=true:u&&be(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&_(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let P=!r||r.schema<x||!e.fs.existsSync(e.wrapperPath);if(u){let h=De(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=Be(o,e.fs);g?X(h,g)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true:Fe(h)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=P||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function Be(e,t){if(!e?.installed||!e.prefix)return;let n=p__namespace.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function R(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Bt(e={}){let t=await F(e),n=await v(t);return R(n)}async function $t(e={}){let t=await F(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await v(t),r=R(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new m("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new m("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new m("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&_(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Me({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Oe({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=Be(s,t.fs)??(n.iconPath&&Fe(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new m("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Te({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?j(t.fs,g):void 0;w&&(a=w);}o&&W(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Ft(t);let h=await v(t),C=R(h);return {...C,errors:[...C.errors,...i],changed:o,installedGlobal:c}}async function Ht(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}W(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await v(t);return R(o)}async function Ut(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;W(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await v(t);return R(o)}exports.ShortcutError=m;exports.dismissShortcutNotice=Ut;exports.getShortcutStatus=Bt;exports.installShortcut=$t;exports.killProcessTree=he;exports.uninstallShortcut=Ht;
@@ -1,3 +1,3 @@
1
- import*as m from'path';import m__default,{join}from'path';import {fileURLToPath}from'url';import {createHash}from'crypto';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {execFile,spawn}from'child_process';import {StringDecoder}from'string_decoder';import {createRequire}from'module';var $=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var q=()=>fileURLToPath(import.meta.url),Ge=()=>m__default.dirname(q()),P=Ge(),S=q();var p=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var Q={existsSync:e=>existsSync(e),readFileSync:e=>readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(readFileSync(e)),writeFileSync:(e,t)=>writeFileSync(e,t,"utf8"),mkdirSync:e=>{mkdirSync(e,{recursive:true});},unlinkSync:e=>{unlinkSync(e);}},Z=homedir;function O(e){return typeof e!="string"?void 0:e.trim()||void 0}function D(e){return O(e)?.toLowerCase()??""}function k(e){try{return statSync(e).isFile()}catch{return false}}function Qe(e,t){if(e===t)return true;let n=m__default.relative(e,t);return n!==""&&!n.startsWith("..")&&!m__default.isAbsolute(n)}function Ze(e,t){if(m__default.basename(e)!==".bin")return false;let n=m__default.dirname(e);if(m__default.basename(n)!=="node_modules")return false;let r=m__default.dirname(n);return Qe(r,t)}function ee(e,t={}){if(e.includes("/")||e.includes("\\")||m__default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=m__default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=m__default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let E=m__default.resolve(o,u);if(!(c&&Ze(E,o)))for(let h of f){let y=D(h),g=h.toUpperCase();for(let w of [h,y,g]){let v=m__default.join(E,`${e}${w}`);if(k(v))return v}}}return e}function et(e){if(!k(e))return null;try{let t=readFileSync(e,"utf8"),n=m__default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,""),u=m__default.resolve(n,f);k(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,"");c.set(a,m__default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&k(l)&&o.push(l);}let s=i=>i.find(a=>{let l=D(m__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function tt(e,t){if(typeof t=="string")return O(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?O(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?O(n):void 0;if(r)return r}return null}function nt(e,t){if(!t)return null;let n=m__default.dirname(e),r=[m__default.resolve(n,"..",t),m__default.resolve(n,"node_modules",t)];for(let o of r){let c=m__default.join(o,"package.json");if(k(c))try{let s=JSON.parse(readFileSync(c,"utf8")),i=tt(t,s.bin);if(!i)continue;let a=m__default.resolve(o,i);if(k(a))return a}catch{}}return null}function rt(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=D(m__default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=et(s)??nt(s,e.packageName);return a?D(m__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct"}}function ot(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${m__default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ne(e){let t=rt(e);return ot({candidate:t})}function re(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var A="\uFFFD",H=8,se=1e3,it=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),T;function V(e){let t=0;for(let n of e)n===A&&(t+=1);return t}function U(e,t){return V(t)<V(e)?t:e}function at(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function ct(e){if(e!==65001)return it.get(e)}function lt(e){let t=ct(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function ut(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),se),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:se,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(at(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ce(){return process.platform!=="win32"?Promise.resolve(null):(T||(T=ut(),T.then(e=>{},()=>{})),T)}function dt(){process.platform==="win32"&&ce();}function ae(e,t){if(t.length>=H)return t.subarray(t.length-H);let n=H-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var _=class{platform;detectCodePage;utf8Decoder=new StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ce,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:lt(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(A);if(r&&(this.utf8Decoder=new StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=ae(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),U(d,f)}if(V(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=ae(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return U(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(A)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(A)?U(n,o):n}};dt();var le=3e3,mt=2e3,pt=25,ht=100;function fe(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ue(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function gt(e){return Number.isSafeInteger(e)&&e>0}function wt(e,t){return new Promise(n=>{let r;try{r=spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:fe(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${le}ms`)});},le);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function Pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):wt(e,t)}function St(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function Et(){return new Promise(e=>{setImmediate(e);})}function W(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ue(n)==="ESRCH"?"not_found":ue(n)==="EPERM"?"alive":"unknown"}}function Ct(e,t){let n=W(-e,t),r=W(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function me(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??pt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await Et();;){let d=Ct(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,St(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function de(e,t,n,r,o){let c=await me(e,t,o.hardConfirmMs??ht,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function pe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!gt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=W(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await Pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:fe(h)};}let E=W(e,c);return E==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(E==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return de(e,c,i,r,t);if(await me(e,c,t.graceMs??mt,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await de(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var yt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function vt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function he(e){return vt(e,yt)}var ge=3e4;function we(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}pe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var Pe=(e,t,n={})=>new Promise((r,o)=>{let c=he(n.env??process.env),s=process.platform,i;try{let w=ne({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=re(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new _({platform:s}),E=new _({platform:s}),h=Promise.resolve(),y=Promise.resolve(),g=setTimeout(()=>{f||(f=true,we(a),o(new Error(`Command timed out after ${n.timeoutMs??ge}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??ge);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{y=y.then(async()=>{d+=await E.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,y]);let[v,Ue]=await Promise.all([u.end(),E.end()]);f||(l+=v,d+=Ue,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(v=>{f||(f=true,clearTimeout(g),o(v instanceof Error?v:new Error(String(v))));});});});function _t(){try{return (typeof $=="function"?$:createRequire(S)).resolve("@crewx/sdk/package.json")}catch{return null}}function xt(){let e=[_t(),join(P,"../../package.json"),join(P,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Ee=xt();var C=m.win32;function X(e){return C.join(e,".crewx")}function ye(e){return C.join(X(e),"shortcut.json")}function ve(e){return C.join(X(e),"launcher.json")}function Re(e){return C.join(X(e),"bin","crewx-launcher.cmd")}function be(e){return C.join(e,"CrewX.lnk")}function G(e,t){return C.normalize(e).toLowerCase()===C.normalize(t).toLowerCase()}var It="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ke(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:C.join(t,"Desktop"),source:"fallback"}:null}function J(e,t){let n=C.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?C.resolve(r).toLowerCase()!==n:true).join(";")}function _e(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function Lt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(E=>Number.parseInt(E,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function x(e,t){return Lt(e,t)<0}var Ie=m.win32,Le=1;function Ne(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??Le,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function M(e,t,n){let r={schema:Le,...n,updatedAt:new Date().toISOString()};e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function F(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Oe(e,t,n){e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var Nt=m.win32,I=1;function Ot(e){return e.replace(/%/g,"%%")}function Dt(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ot(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
- `)}function Te(e){let t=F(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=I&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=Dt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(Nt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Oe(e.fs,e.launcherManifestPath,{schema:I,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof p?s:new p("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:I}}var Tt=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),At=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function Ae(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Tt],{env:t});}catch(r){throw new p("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new p("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function We(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Me(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",At],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var j=m.win32;async function L(e){let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?j.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Wt=/EACCES|EPERM|EROFS/,Mt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Ft=/^\d+\.\d+\.\d+/;function Bt(e){return !!e&&e!=="0.0.0"&&Ft.test(e)}var K=10*6e4;async function Be(e){if(!Bt(e.targetVersion))throw new p("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!x(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(s){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
- ${o.stderr}`;if(Wt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||j.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:j.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:K});}catch(l){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await L({env:i,cwd:e.cwd,run:e.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Mt.test(c)){if(!e.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(i){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Ht(e){return e.run??Pe}function Ut(e){return e.fs??Q}async function B(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Z,o=Ht(e),c=Ut(e),s=e.runningVersion??Ee,i=e.cwd??process.cwd(),a=r(),l=ye(a),d=ve(a),f=Re(a),u=null;t==="win32"&&(u=await ke({env:n,homedir:r,run:o}));let E=u?be(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:E}}function $e(e){return e?m.win32.normalize(e).toLowerCase().endsWith(`${m.win32.sep}bin${m.win32.sep}crewx.ico`):false}function z(e,t){let n=e.readBinaryFileSync;if(n)try{return createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Vt(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function R(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ne(e.fs,e.shortcutManifestPath),r=F(e.fs,e.launcherManifestPath),o=await L({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Me({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&G(u.targetPath,e.wrapperPath)?d=true:u&&_e(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&x(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let E=!r||r.schema<I||!e.fs.existsSync(e.wrapperPath);if(u){let h=We(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=He(o,e.fs);g?G(h,g)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true:$e(h)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=E||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function He(e,t){if(!e?.installed||!e.prefix)return;let n=m.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function b(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Xt(e={}){let t=await B(e),n=await R(t);return b(n)}async function Gt(e={}){let t=await B(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await R(t),r=b(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&x(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Be({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Te({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=He(s,t.fs)??(n.iconPath&&$e(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new p("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Ae({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?z(t.fs,g):void 0;w&&(a=w);}o&&M(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Vt(t);let h=await R(t),y=b(h);return {...y,errors:[...y.errors,...i],changed:o,installedGlobal:c}}async function Jt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}M(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await R(t);return b(o)}async function Kt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;M(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await R(t);return b(o)}export{p as ShortcutError,Kt as dismissShortcutNotice,Xt as getShortcutStatus,Gt as installShortcut,we as killProcessTree,Jt as uninstallShortcut};
1
+ import*as m from'path';import m__default,{join}from'path';import {fileURLToPath}from'url';import {createHash}from'crypto';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {execFile,spawn}from'child_process';import {StringDecoder}from'string_decoder';import {createRequire}from'module';var $=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var q=()=>fileURLToPath(import.meta.url),Ge=()=>m__default.dirname(q()),P=Ge(),S=q();var p=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var Q={existsSync:e=>existsSync(e),readFileSync:e=>readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(readFileSync(e)),writeFileSync:(e,t)=>writeFileSync(e,t,"utf8"),mkdirSync:e=>{mkdirSync(e,{recursive:true});},unlinkSync:e=>{unlinkSync(e);}},Z=homedir;function O(e){return typeof e!="string"?void 0:e.trim()||void 0}function T(e){return O(e)?.toLowerCase()??""}function k(e){try{return statSync(e).isFile()}catch{return false}}function Qe(e,t){if(e===t)return true;let n=m__default.relative(e,t);return n!==""&&!n.startsWith("..")&&!m__default.isAbsolute(n)}function Ze(e,t){if(m__default.basename(e)!==".bin")return false;let n=m__default.dirname(e);if(m__default.basename(n)!=="node_modules")return false;let r=m__default.dirname(n);return Qe(r,t)}function ee(e,t={}){if(e.includes("/")||e.includes("\\")||m__default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=m__default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=m__default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let E=m__default.resolve(o,u);if(!(c&&Ze(E,o)))for(let h of f){let y=T(h),g=h.toUpperCase();for(let w of [h,y,g]){let v=m__default.join(E,`${e}${w}`);if(k(v))return v}}}return e}function et(e){if(!k(e))return null;try{let t=readFileSync(e,"utf8"),n=m__default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,""),u=m__default.resolve(n,f);k(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,"");c.set(a,m__default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&k(l)&&o.push(l);}let s=i=>i.find(a=>{let l=T(m__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function tt(e,t){if(typeof t=="string")return O(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?O(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?O(n):void 0;if(r)return r}return null}function nt(e,t){if(!t)return null;let n=m__default.dirname(e),r=[m__default.resolve(n,"..",t),m__default.resolve(n,"node_modules",t)];for(let o of r){let c=m__default.join(o,"package.json");if(k(c))try{let s=JSON.parse(readFileSync(c,"utf8")),i=tt(t,s.bin);if(!i)continue;let a=m__default.resolve(o,i);if(k(a))return a}catch{}}return null}function rt(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=T(m__default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=et(s)??nt(s,e.packageName);return a?T(m__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct"}}function ot(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${m__default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ne(e){let t=rt(e);return ot({candidate:t})}function re(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var A="\uFFFD",H=8,se=1e3,it=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),D;function V(e){let t=0;for(let n of e)n===A&&(t+=1);return t}function U(e,t){return V(t)<V(e)?t:e}function at(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function ct(e){if(e!==65001)return it.get(e)}function lt(e){let t=ct(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function ut(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),se),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:se,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(at(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ce(){return process.platform!=="win32"?Promise.resolve(null):(D||(D=ut(),D.then(e=>{},()=>{})),D)}function dt(){process.platform==="win32"&&ce();}function ae(e,t){if(t.length>=H)return t.subarray(t.length-H);let n=H-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var _=class{platform;detectCodePage;utf8Decoder=new StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ce,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:lt(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(A);if(r&&(this.utf8Decoder=new StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=ae(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),U(d,f)}if(V(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=ae(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return U(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(A)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(A)?U(n,o):n}};dt();var le=3e3;var mt=2e3,pt=25,ht=100;function fe(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ue(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function gt(e){return Number.isSafeInteger(e)&&e>0}function wt(e,t){return new Promise(n=>{let r;try{r=spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:fe(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${le}ms`)});},le);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function Pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):wt(e,t)}function St(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function Et(){return new Promise(e=>{setImmediate(e);})}function W(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ue(n)==="ESRCH"?"not_found":ue(n)==="EPERM"?"alive":"unknown"}}function Ct(e,t){let n=W(-e,t),r=W(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function me(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??pt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await Et();;){let d=Ct(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,St(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function de(e,t,n,r,o){let c=await me(e,t,o.hardConfirmMs??ht,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function pe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!gt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=W(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await Pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:fe(h)};}let E=W(e,c);return E==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(E==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return de(e,c,i,r,t);if(await me(e,c,t.graceMs??mt,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await de(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var yt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function vt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function he(e){return vt(e,yt)}var ge=3e4;function we(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}pe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var Pe=(e,t,n={})=>new Promise((r,o)=>{let c=he(n.env??process.env),s=process.platform,i;try{let w=ne({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=re(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new _({platform:s}),E=new _({platform:s}),h=Promise.resolve(),y=Promise.resolve(),g=setTimeout(()=>{f||(f=true,we(a),o(new Error(`Command timed out after ${n.timeoutMs??ge}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??ge);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{y=y.then(async()=>{d+=await E.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,y]);let[v,Ue]=await Promise.all([u.end(),E.end()]);f||(l+=v,d+=Ue,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(v=>{f||(f=true,clearTimeout(g),o(v instanceof Error?v:new Error(String(v))));});});});function _t(){try{return (typeof $=="function"?$:createRequire(S)).resolve("@crewx/sdk/package.json")}catch{return null}}function xt(){let e=[_t(),join(P,"../../package.json"),join(P,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Ee=xt();var C=m.win32;function X(e){return C.join(e,".crewx")}function ye(e){return C.join(X(e),"shortcut.json")}function ve(e){return C.join(X(e),"launcher.json")}function Re(e){return C.join(X(e),"bin","crewx-launcher.cmd")}function be(e){return C.join(e,"CrewX.lnk")}function G(e,t){return C.normalize(e).toLowerCase()===C.normalize(t).toLowerCase()}var It="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ke(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:C.join(t,"Desktop"),source:"fallback"}:null}function J(e,t){let n=C.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?C.resolve(r).toLowerCase()!==n:true).join(";")}function _e(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function Lt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(E=>Number.parseInt(E,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function x(e,t){return Lt(e,t)<0}var Ie=m.win32,Le=1;function Ne(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??Le,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function M(e,t,n){let r={schema:Le,...n,updatedAt:new Date().toISOString()};e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function F(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Oe(e,t,n){e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var Nt=m.win32,I=1;function Ot(e){return e.replace(/%/g,"%%")}function Tt(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ot(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
+ `)}function De(e){let t=F(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=I&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=Tt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(Nt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Oe(e.fs,e.launcherManifestPath,{schema:I,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof p?s:new p("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:I}}var Dt=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),At=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function Ae(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Dt],{env:t});}catch(r){throw new p("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new p("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function We(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Me(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",At],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var j=m.win32;async function L(e){let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?j.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Wt=/EACCES|EPERM|EROFS/,Mt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Ft=/^\d+\.\d+\.\d+/;function Bt(e){return !!e&&e!=="0.0.0"&&Ft.test(e)}var K=10*6e4;async function Be(e){if(!Bt(e.targetVersion))throw new p("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!x(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(s){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
+ ${o.stderr}`;if(Wt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||j.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:j.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:K});}catch(l){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await L({env:i,cwd:e.cwd,run:e.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Mt.test(c)){if(!e.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(i){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Ht(e){return e.run??Pe}function Ut(e){return e.fs??Q}async function B(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Z,o=Ht(e),c=Ut(e),s=e.runningVersion??Ee,i=e.cwd??process.cwd(),a=r(),l=ye(a),d=ve(a),f=Re(a),u=null;t==="win32"&&(u=await ke({env:n,homedir:r,run:o}));let E=u?be(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:E}}function $e(e){return e?m.win32.normalize(e).toLowerCase().endsWith(`${m.win32.sep}bin${m.win32.sep}crewx.ico`):false}function z(e,t){let n=e.readBinaryFileSync;if(n)try{return createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Vt(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function R(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ne(e.fs,e.shortcutManifestPath),r=F(e.fs,e.launcherManifestPath),o=await L({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Me({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&G(u.targetPath,e.wrapperPath)?d=true:u&&_e(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&x(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let E=!r||r.schema<I||!e.fs.existsSync(e.wrapperPath);if(u){let h=We(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=He(o,e.fs);g?G(h,g)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true:$e(h)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=E||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function He(e,t){if(!e?.installed||!e.prefix)return;let n=m.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function b(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Xt(e={}){let t=await B(e),n=await R(t);return b(n)}async function Gt(e={}){let t=await B(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await R(t),r=b(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&x(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Be({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),De({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=He(s,t.fs)??(n.iconPath&&$e(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new p("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Ae({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?z(t.fs,g):void 0;w&&(a=w);}o&&M(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Vt(t);let h=await R(t),y=b(h);return {...y,errors:[...y.errors,...i],changed:o,installedGlobal:c}}async function Jt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}M(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await R(t);return b(o)}async function Kt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;M(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await R(t);return b(o)}export{p as ShortcutError,Kt as dismissShortcutNotice,Xt as getShortcutStatus,Gt as installShortcut,we as killProcessTree,Jt as uninstallShortcut};