@crewx/sdk 0.9.0-rc.41 → 0.9.0-rc.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/wi-boards.d.ts +4 -0
- package/dist/desktop/command-runner.d.ts +4 -0
- package/dist/desktop/default-adapters.d.ts +4 -0
- package/dist/desktop/global-install.d.ts +17 -0
- package/dist/desktop/index.d.ts +2 -0
- package/dist/desktop/index.js +3 -0
- package/dist/desktop/install.d.ts +5 -0
- package/dist/desktop/lnk.d.ts +21 -0
- package/dist/desktop/manifest.d.ts +20 -0
- package/dist/desktop/types.d.ts +66 -0
- package/dist/desktop/version.d.ts +1 -0
- package/dist/desktop/windows-paths.d.ts +21 -0
- package/dist/desktop/wrapper.d.ts +18 -0
- package/dist/esm/desktop/index.js +3 -0
- package/dist/esm/index.js +119 -108
- package/dist/index.d.ts +6 -2
- package/dist/index.js +120 -109
- package/dist/paths.d.ts +1 -0
- package/dist/wi/create.d.ts +48 -0
- package/dist/wi/select.d.ts +20 -0
- package/package.json +9 -2
- package/templates/workflows/wi-default-flow.yaml +65 -0
- package/templates/workflows/wi-plan-flow.yaml +140 -0
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { CrewxProjectConfig } from '../types';
|
|
2
2
|
export declare const DEFAULT_WI_BOARD_ID = "default";
|
|
3
3
|
export declare const ARCHIVE_WI_BOARD_ID = "archive";
|
|
4
|
+
export declare const DEFAULT_WI_WORKFLOW_ID = "wi-default-flow";
|
|
5
|
+
export declare const WI_PLAN_WORKFLOW_ID = "wi-plan-flow";
|
|
6
|
+
export declare const WI_DEFAULT_FLOW_FILENAME = "wi-default-flow.yaml";
|
|
7
|
+
export declare const WI_PLAN_FLOW_FILENAME = "wi-plan-flow.yaml";
|
|
4
8
|
export declare const WI_BOARD_ID_PATTERN: RegExp;
|
|
5
9
|
export declare function isReservedWiBoardId(id: string): boolean;
|
|
6
10
|
export interface ResolvedWiBoard {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CommandRunner, GlobalCrewxInfo, ShortcutProgressEvent } from './types';
|
|
2
|
+
export interface DetectGlobalCrewxOptions {
|
|
3
|
+
env: NodeJS.ProcessEnv;
|
|
4
|
+
cwd: string;
|
|
5
|
+
run: CommandRunner;
|
|
6
|
+
}
|
|
7
|
+
export declare function detectGlobalCrewx(opts: DetectGlobalCrewxOptions): Promise<GlobalCrewxInfo>;
|
|
8
|
+
export interface EnsureGlobalCrewxOptions {
|
|
9
|
+
env: NodeJS.ProcessEnv;
|
|
10
|
+
cwd: string;
|
|
11
|
+
run: CommandRunner;
|
|
12
|
+
installRoot?: string;
|
|
13
|
+
onProgress?: (event: ShortcutProgressEvent) => void;
|
|
14
|
+
}
|
|
15
|
+
export declare function ensureGlobalCrewx(opts: EnsureGlobalCrewxOptions): Promise<{
|
|
16
|
+
info: GlobalCrewxInfo;
|
|
17
|
+
}>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { getShortcutStatus, installShortcut, uninstallShortcut, dismissShortcutNotice, } from './install';
|
|
2
|
+
export { ShortcutError, type ShortcutState, type DesktopSource, type GlobalCrewxInfo, type ShortcutStatus, type ShortcutInstallResult, type ShortcutProgressPhase, type ShortcutProgressEvent, type ShortcutEnvOptions, type InstallShortcutOptions, type ShortcutErrorCode, type CommandResult, type CommandRunner, type CommandRunOptions, type ShortcutFsLike, } from './types';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var d=require('path'),fs=require('fs'),os=require('os'),child_process=require('child_process'),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 d__namespace=/*#__PURE__*/_interopNamespace(d);var N=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var p=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var A={existsSync:t=>fs.existsSync(t),readFileSync:t=>fs.readFileSync(t,"utf8"),writeFileSync:(t,e)=>fs.writeFileSync(t,e,"utf8"),mkdirSync:t=>{fs.mkdirSync(t,{recursive:true});},unlinkSync:t=>{fs.unlinkSync(t);}},T=os.homedir;function y(t){return typeof t!="string"?void 0:t.trim()||void 0}function C(t){return y(t)?.toLowerCase()??""}function E(t){try{return fs.statSync(t).isFile()}catch{return false}}function yt(t,e){if(t===e)return true;let n=d__namespace.default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__namespace.default.isAbsolute(n)}function Ct(t,e){if(d__namespace.default.basename(t)!==".bin")return false;let n=d__namespace.default.dirname(t);if(d__namespace.default.basename(n)!=="node_modules")return false;let r=d__namespace.default.dirname(n);return yt(r,e)}function M(t,e={}){if(t.includes("/")||t.includes("\\")||d__namespace.default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__namespace.default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__namespace.default.extname(t).length>0,m=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",h=n==="win32"?l?[""]:m.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let f=d__namespace.default.resolve(s,u);if(!(c&&Ct(f,s)))for(let L of h){let ft=C(L),ht=L.toUpperCase();for(let mt of [L,ft,ht]){let W=d__namespace.default.join(f,`${t}${mt}`);if(E(W))return W}}}return t}function xt(t){if(!E(t))return null;try{let e=fs.readFileSync(t,"utf8"),n=d__namespace.default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let m=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!m)continue;let h=m.replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,""),u=d__namespace.default.resolve(n,h);E(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,d__namespace.default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&E(l)&&s.push(l);}let o=i=>i.find(a=>{let l=C(d__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function kt(t,e){if(typeof e=="string")return y(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?y(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?y(n):void 0;if(r)return r}return null}function _t(t,e){if(!e)return null;let n=d__namespace.default.dirname(t),r=[d__namespace.default.resolve(n,"..",e),d__namespace.default.resolve(n,"node_modules",e)];for(let s of r){let c=d__namespace.default.join(s,"package.json");if(E(c))try{let o=JSON.parse(fs.readFileSync(c,"utf8")),i=kt(e,o.bin);if(!i)continue;let a=d__namespace.default.resolve(s,i);if(E(a))return a}catch{}}return null}function Lt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:M(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=M(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=C(d__namespace.default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=xt(o)??_t(o,t.packageName);return a?C(d__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Nt(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__namespace.default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function B(t){let e=Lt(t);return Nt({candidate:e})}function $(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var X=3e4;function Ot(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){child_process.spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var H=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let f=B({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=$(f,e);}catch(f){s(f instanceof Error?f:new Error(String(f)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",m="",h=false,u=setTimeout(()=>{h||(h=true,Ot(a),s(new Error(`Command timed out after ${n.timeoutMs??X}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??X);a.stdout?.on("data",f=>{l+=f.toString();}),a.stderr?.on("data",f=>{m+=f.toString();}),a.on("error",f=>{h||(h=true,clearTimeout(u),s(f));}),a.on("close",f=>{h||(h=true,clearTimeout(u),r({code:f??0,stdout:l,stderr:m}));});});function Dt(){try{return (typeof N=="function"?N:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function Wt(){let t=[Dt(),d.join(__dirname,"../../package.json"),d.join(__dirname,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(fs.readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var j=Wt();var g=d__namespace.win32;function O(t){return g.join(t,".crewx")}function K(t){return g.join(O(t),"shortcut.json")}function U(t){return g.join(O(t),"launcher.json")}function z(t){return g.join(O(t),"bin","crewx-launcher.cmd")}function q(t){return g.join(t,"CrewX.lnk")}function Q(t,e){return g.normalize(t).toLowerCase()===g.normalize(e).toLowerCase()}var At="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Y(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",At],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:g.join(e,"Desktop"),source:"fallback"}:null}function I(t,e){let n=g.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?g.resolve(r).toLowerCase()!==n:true).join(";")}function Z(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Tt(t,e){let n=a=>{let[l,...m]=a.split("-"),h=m.join("-")||void 0;return {parts:(l??"").split(".").map(f=>Number.parseInt(f,10)||0),pre:h}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,m=s.parts[a]??0;if(l!==m)return l<m?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function tt(t,e){return Tt(t,e)<0}var nt=d__namespace.win32,rt=1;function ot(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??rt,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function x(t,e,n){let r={schema:rt,...n,updatedAt:new Date().toISOString()};t.mkdirSync(nt.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function k(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function st(t,e,n){t.mkdirSync(nt.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var Mt=d__namespace.win32,R=1;function Ft(t){return t.replace(/%/g,"%%")}function Bt(t){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%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ft(t.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 at(t){let e=k(t.fs,t.launcherManifestPath),n=!!e&&e.schema>=R&&t.fs.existsSync(t.wrapperPath),r=n&&!e.binPath&&!!t.bakedBinPath;if(n&&!r)return {wrapperPath:t.wrapperPath,wrote:false,schema:e.schema};let c=Bt({bakedBinPath:t.bakedBinPath});try{t.fs.mkdirSync(Mt.dirname(t.wrapperPath)),t.fs.writeFileSync(t.wrapperPath,c),st(t.fs,t.launcherManifestPath,{schema:R,binPath:t.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof p?o:new p("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:t.wrapperPath,wrote:true,schema:R}}var $t=["$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("; "),Xt=["$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 ct(t){let e={...t.env,CREWX_LNK_PATH:t.shortcutPath,CREWX_LNK_TARGET:t.targetPath,CREWX_LNK_WORKDIR:t.workingDirectory??"",CREWX_LNK_ICON:t.iconPath??""},n;try{n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",$t],{env:e});}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}`)}async function lt(t){try{let e={...t.env,CREWX_LNK_PATH:t.shortcutPath},n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Xt],{env:e});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 D=d__namespace.win32;async function v(t){let e=I(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r;try{r=await t.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let s;try{s=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=s.dependencies?.crewx;if(!c?.version)return {installed:false};let o;try{let a=await t.run("npm",["prefix","-g"],{env:n});a.code===0&&(o=a.stdout.trim()||void 0);}catch{}let i=o?D.join(o,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:o}}var Vt=/EACCES|EPERM|EROFS/,Ht=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,b=10*6e4;async function dt(t){let e=I(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e};t.onProgress?.({phase:"global-install",message:"Installing crewx globally (npm install -g crewx@latest)"});let r;try{r=await t.run("npm",["install","-g","crewx@latest","--no-audit","--no-fund"],{env:n,timeoutMs:b});}catch(c){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${c instanceof Error?c.message:String(c)}`)}if(r.code===0)return {info:await v({env:n,cwd:t.cwd,run:t.run})};let s=`${r.stdout}
|
|
3
|
+
${r.stderr}`;if(Vt.test(s)){t.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let c=t.env.LOCALAPPDATA||D.join(t.env.USERPROFILE??"","AppData","Local"),o={...n,npm_config_prefix:D.join(c,"crewx","npm")},i;try{i=await t.run("npm",["install","-g","crewx@latest","--no-audit","--no-fund"],{env:o,timeoutMs:b});}catch(a){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${a instanceof Error?a.message:String(a)}`)}if(i.code===0)return {info:await v({env:o,cwd:t.cwd,run:t.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${i.stderr||i.stdout}`)}if(Ht.test(s)){if(!t.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");t.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${t.installRoot}`});let c;try{c=await t.run("npm",["install","-g",t.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:b});}catch(o){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o instanceof Error?o.message:String(o)}`)}if(c.code===0)return {info:await v({env:n,cwd:t.cwd,run:t.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${c.stderr||c.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",s.trim()||"npm install -g crewx@latest failed")}function Gt(t){return t.run??H}function jt(t){return t.fs??A}async function _(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.homedir??T,s=Gt(t),c=jt(t),o=t.runningVersion??j,i=t.cwd??process.cwd(),a=r(),l=K(a),m=U(a),h=z(a),u=null;e==="win32"&&(u=await Y({env:n,homedir:r,run:s}));let f=u?q(u.dir):null;return {platform:e,env:n,homedir:r,run:s,fs:c,runningVersion:o,cwd:i,installRoot:t.installRoot,shortcutManifestPath:l,launcherManifestPath:m,wrapperPath:h,desktop:u,shortcutPath:f}}async function S(t){if(t.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:t.runningVersion,errors:[],manifest:null};let e=[];t.desktop||e.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=ot(t.fs,t.shortcutManifestPath),r=k(t.fs,t.launcherManifestPath),s=await v({env:t.env,cwd:t.cwd,run:t.run}),c=t.shortcutPath?t.fs.existsSync(t.shortcutPath):false,o;if(!c)o=n?.declined?"declined":"not-installed";else {let i=!!n?.owned&&!!t.shortcutPath&&n.shortcutPath===t.shortcutPath,a=false;if(!i&&t.shortcutPath){let l=await lt({run:t.run,env:t.env,shortcutPath:t.shortcutPath});l&&Q(l.targetPath,t.wrapperPath)?i=true:l&&Z(l.targetPath)&&(a=true);}a?(o="foreign",e.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected")):i?n?.version&&tt(t.runningVersion,n.version)?(o="superseded",e.push(`SUPERSEDED: running version ${t.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`)):!r||r.schema<R||!t.fs.existsSync(t.wrapperPath)?o="stale":o="installed":o="foreign";}return {supported:true,state:o,shortcutPath:t.shortcutPath??void 0,desktopDir:t.desktop?.dir,desktopSource:t.desktop?.source,wrapperPath:t.wrapperPath,wrapperSchema:r?.schema,globalCrewx:s.installed?s:{installed:false},runningVersion:t.runningVersion,errors:e,manifest:n}}function Jt(t){if(!(!t?.installed||!t.prefix))return d__namespace.win32.join(t.prefix,"node_modules","crewx","bin","crewx.ico")}function P(t){let{manifest:e,...n}=t;return n}async function Kt(t={}){let e=await _(t),n=await S(e);return P(n)}async function Ut(t={}){let e=await _(t);t.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await S(e),r=P(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(u=>u.startsWith("NSIS_PRESENT")))throw new p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!t.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!e.desktop||!e.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let s=false,c=false,o=r.globalCrewx,i=[];if(!o?.installed){let u=await dt({env:e.env,cwd:e.cwd,run:e.run,installRoot:e.installRoot,onProgress:t.onProgress});o=u.info,c=u.info.installed,s=true,c||i.push("GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@latest exited successfully but a follow-up check could not confirm the global install");}t.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),at({fs:e.fs,wrapperPath:e.wrapperPath,launcherManifestPath:e.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(s=true),r.state==="installed"||r.state==="stale"||(t.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await ct({run:e.run,env:e.env,shortcutPath:e.shortcutPath,targetPath:e.wrapperPath,iconPath:Jt(o)}),s=true),s&&x(e.fs,e.shortcutManifestPath,{shortcutPath:e.shortcutPath,version:e.runningVersion,owned:true,declined:false,desktopSource:e.desktop.source});let m=await S(e),h=P(m);return {...h,errors:[...h.errors,...i],changed:s,installedGlobal:c}}async function zt(t={}){let e=await _(t),n=await S(e),r=P(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&e.shortcutPath)try{e.fs.unlinkSync(e.shortcutPath);}catch{}x(e.fs,e.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0});let s=await S(e);return P(s)}async function qt(t={}){let e=await _(t),n=await S(e),r=P(n);if(!r.supported)return r;x(e.fs,e.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource});let s=await S(e);return P(s)}exports.ShortcutError=p;exports.dismissShortcutNotice=qt;exports.getShortcutStatus=Kt;exports.installShortcut=Ut;exports.uninstallShortcut=zt;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type InstallShortcutOptions, type ShortcutEnvOptions, type ShortcutInstallResult, type ShortcutStatus } from './types';
|
|
2
|
+
export declare function getShortcutStatus(options?: ShortcutEnvOptions): Promise<ShortcutStatus>;
|
|
3
|
+
export declare function installShortcut(options?: InstallShortcutOptions): Promise<ShortcutInstallResult>;
|
|
4
|
+
export declare function uninstallShortcut(options?: ShortcutEnvOptions): Promise<ShortcutStatus>;
|
|
5
|
+
export declare function dismissShortcutNotice(options?: ShortcutEnvOptions): Promise<ShortcutStatus>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { CommandRunner } from './types';
|
|
2
|
+
export interface WriteLnkOptions {
|
|
3
|
+
run: CommandRunner;
|
|
4
|
+
env: NodeJS.ProcessEnv;
|
|
5
|
+
shortcutPath: string;
|
|
6
|
+
targetPath: string;
|
|
7
|
+
workingDirectory?: string;
|
|
8
|
+
iconPath?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function writeLnk(opts: WriteLnkOptions): Promise<void>;
|
|
11
|
+
export interface LnkInfo {
|
|
12
|
+
targetPath: string;
|
|
13
|
+
workingDirectory: string;
|
|
14
|
+
iconLocation: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ReadLnkOptions {
|
|
17
|
+
run: CommandRunner;
|
|
18
|
+
env: NodeJS.ProcessEnv;
|
|
19
|
+
shortcutPath: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function readLnkTarget(opts: ReadLnkOptions): Promise<LnkInfo | null>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DesktopSource, ShortcutFsLike } from './types';
|
|
2
|
+
export declare const MANIFEST_SCHEMA_VERSION = 1;
|
|
3
|
+
export interface ShortcutManifest {
|
|
4
|
+
schema: number;
|
|
5
|
+
shortcutPath?: string;
|
|
6
|
+
version?: string;
|
|
7
|
+
owned: boolean;
|
|
8
|
+
declined: boolean;
|
|
9
|
+
desktopSource?: DesktopSource;
|
|
10
|
+
updatedAt?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface LauncherManifest {
|
|
13
|
+
schema: number;
|
|
14
|
+
binPath?: string;
|
|
15
|
+
updatedAt?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function readShortcutManifest(fs: ShortcutFsLike, manifestPath: string): ShortcutManifest | null;
|
|
18
|
+
export declare function writeShortcutManifest(fs: ShortcutFsLike, manifestPath: string, data: Omit<ShortcutManifest, 'schema' | 'updatedAt'>): void;
|
|
19
|
+
export declare function readLauncherManifest(fs: ShortcutFsLike, manifestPath: string): LauncherManifest | null;
|
|
20
|
+
export declare function writeLauncherManifest(fs: ShortcutFsLike, manifestPath: string, data: LauncherManifest): void;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export type ShortcutState = 'unsupported' | 'not-installed' | 'installed' | 'stale' | 'foreign' | 'superseded' | 'declined';
|
|
2
|
+
export type DesktopSource = 'known-folder' | 'fallback';
|
|
3
|
+
export interface GlobalCrewxInfo {
|
|
4
|
+
installed: boolean;
|
|
5
|
+
version?: string;
|
|
6
|
+
binPath?: string;
|
|
7
|
+
prefix?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ShortcutStatus {
|
|
10
|
+
supported: boolean;
|
|
11
|
+
state: ShortcutState;
|
|
12
|
+
shortcutPath?: string;
|
|
13
|
+
desktopDir?: string;
|
|
14
|
+
desktopSource?: DesktopSource;
|
|
15
|
+
wrapperPath?: string;
|
|
16
|
+
wrapperSchema?: number;
|
|
17
|
+
globalCrewx: GlobalCrewxInfo | null;
|
|
18
|
+
runningVersion: string;
|
|
19
|
+
errors: string[];
|
|
20
|
+
}
|
|
21
|
+
export interface ShortcutInstallResult extends ShortcutStatus {
|
|
22
|
+
changed: boolean;
|
|
23
|
+
installedGlobal: boolean;
|
|
24
|
+
}
|
|
25
|
+
export type ShortcutProgressPhase = 'detect' | 'global-install' | 'wrapper' | 'lnk';
|
|
26
|
+
export interface ShortcutProgressEvent {
|
|
27
|
+
phase: ShortcutProgressPhase;
|
|
28
|
+
message: string;
|
|
29
|
+
}
|
|
30
|
+
export interface CommandResult {
|
|
31
|
+
code: number;
|
|
32
|
+
stdout: string;
|
|
33
|
+
stderr: string;
|
|
34
|
+
}
|
|
35
|
+
export interface CommandRunOptions {
|
|
36
|
+
env?: NodeJS.ProcessEnv;
|
|
37
|
+
cwd?: string;
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
}
|
|
40
|
+
export type CommandRunner = (command: string, args: string[], opts?: CommandRunOptions) => Promise<CommandResult>;
|
|
41
|
+
export interface ShortcutFsLike {
|
|
42
|
+
existsSync(path: string): boolean;
|
|
43
|
+
readFileSync(path: string): string;
|
|
44
|
+
writeFileSync(path: string, data: string): void;
|
|
45
|
+
mkdirSync(path: string): void;
|
|
46
|
+
unlinkSync(path: string): void;
|
|
47
|
+
}
|
|
48
|
+
export interface ShortcutEnvOptions {
|
|
49
|
+
platform?: NodeJS.Platform;
|
|
50
|
+
env?: NodeJS.ProcessEnv;
|
|
51
|
+
homedir?: () => string;
|
|
52
|
+
run?: CommandRunner;
|
|
53
|
+
fs?: ShortcutFsLike;
|
|
54
|
+
runningVersion?: string;
|
|
55
|
+
cwd?: string;
|
|
56
|
+
}
|
|
57
|
+
export interface InstallShortcutOptions extends ShortcutEnvOptions {
|
|
58
|
+
force?: boolean;
|
|
59
|
+
onProgress?: (event: ShortcutProgressEvent) => void;
|
|
60
|
+
installRoot?: string;
|
|
61
|
+
}
|
|
62
|
+
export type ShortcutErrorCode = 'NOT_WINDOWS' | 'NO_DESKTOP_DIR' | 'NPM_UNAVAILABLE' | 'NPM_PERMISSION_DENIED' | 'OFFLINE_NO_SOURCE' | 'GLOBAL_INSTALL_FAILED' | 'POWERSHELL_UNAVAILABLE' | 'WRITE_DENIED' | 'FOREIGN_SHORTCUT' | 'NSIS_PRESENT';
|
|
63
|
+
export declare class ShortcutError extends Error {
|
|
64
|
+
readonly code: ShortcutErrorCode;
|
|
65
|
+
constructor(code: ShortcutErrorCode, message: string);
|
|
66
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const SDK_VERSION: string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { CommandRunner, DesktopSource } from './types';
|
|
2
|
+
export declare function crewxHomeDir(homedir: string): string;
|
|
3
|
+
export declare function shortcutManifestPath(homedir: string): string;
|
|
4
|
+
export declare function launcherManifestPath(homedir: string): string;
|
|
5
|
+
export declare function wrapperPath(homedir: string): string;
|
|
6
|
+
export declare function shortcutLnkPath(desktopDir: string): string;
|
|
7
|
+
export declare function samePath(a: string, b: string): boolean;
|
|
8
|
+
export interface ResolveDesktopDirOptions {
|
|
9
|
+
env: NodeJS.ProcessEnv;
|
|
10
|
+
homedir: () => string;
|
|
11
|
+
run: CommandRunner;
|
|
12
|
+
}
|
|
13
|
+
export interface ResolvedDesktopDir {
|
|
14
|
+
dir: string;
|
|
15
|
+
source: DesktopSource;
|
|
16
|
+
}
|
|
17
|
+
export declare function resolveDesktopDir(opts: ResolveDesktopDirOptions): Promise<ResolvedDesktopDir | null>;
|
|
18
|
+
export declare function filterWorkspaceLocalBin(pathValue: string, cwd: string): string;
|
|
19
|
+
export declare function looksLikeNsisInstall(targetPath: string): boolean;
|
|
20
|
+
export declare function compareVersions(a: string, b: string): -1 | 0 | 1;
|
|
21
|
+
export declare function isOlderVersion(a: string, b: string): boolean;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ShortcutFsLike } from './types';
|
|
2
|
+
export declare const WRAPPER_SCHEMA_VERSION = 1;
|
|
3
|
+
export interface BuildWrapperScriptOptions {
|
|
4
|
+
bakedBinPath?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function buildWrapperScript(opts: BuildWrapperScriptOptions): string;
|
|
7
|
+
export interface EnsureWrapperOptions {
|
|
8
|
+
fs: ShortcutFsLike;
|
|
9
|
+
wrapperPath: string;
|
|
10
|
+
launcherManifestPath: string;
|
|
11
|
+
bakedBinPath?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface EnsureWrapperResult {
|
|
14
|
+
wrapperPath: string;
|
|
15
|
+
wrote: boolean;
|
|
16
|
+
schema: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function ensureWrapper(opts: EnsureWrapperOptions): EnsureWrapperResult;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import*as d from'path';import d__default,{join}from'path';import {fileURLToPath}from'url';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {spawn}from'child_process';import {createRequire}from'module';var O=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var T=()=>fileURLToPath(import.meta.url),Et=()=>d__default.dirname(T()),w=Et(),g=T();var p=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var M={existsSync:t=>existsSync(t),readFileSync:t=>readFileSync(t,"utf8"),writeFileSync:(t,e)=>writeFileSync(t,e,"utf8"),mkdirSync:t=>{mkdirSync(t,{recursive:true});},unlinkSync:t=>{unlinkSync(t);}},F=homedir;function C(t){return typeof t!="string"?void 0:t.trim()||void 0}function x(t){return C(t)?.toLowerCase()??""}function R(t){try{return statSync(t).isFile()}catch{return false}}function Lt(t,e){if(t===e)return true;let n=d__default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__default.isAbsolute(n)}function Nt(t,e){if(d__default.basename(t)!==".bin")return false;let n=d__default.dirname(t);if(d__default.basename(n)!=="node_modules")return false;let r=d__default.dirname(n);return Lt(r,e)}function B(t,e={}){if(t.includes("/")||t.includes("\\")||d__default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__default.extname(t).length>0,m=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",h=n==="win32"?l?[""]:m.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let f=d__default.resolve(s,u);if(!(c&&Nt(f,s)))for(let N of h){let mt=x(N),wt=N.toUpperCase();for(let gt of [N,mt,wt]){let A=d__default.join(f,`${t}${gt}`);if(R(A))return A}}}return t}function Ot(t){if(!R(t))return null;try{let e=readFileSync(t,"utf8"),n=d__default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let m=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!m)continue;let h=m.replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,""),u=d__default.resolve(n,h);R(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,"");c.set(a,d__default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&R(l)&&s.push(l);}let o=i=>i.find(a=>{let l=x(d__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function It(t,e){if(typeof e=="string")return C(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?C(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?C(n):void 0;if(r)return r}return null}function bt(t,e){if(!e)return null;let n=d__default.dirname(t),r=[d__default.resolve(n,"..",e),d__default.resolve(n,"node_modules",e)];for(let s of r){let c=d__default.join(s,"package.json");if(R(c))try{let o=JSON.parse(readFileSync(c,"utf8")),i=It(e,o.bin);if(!i)continue;let a=d__default.resolve(s,i);if(R(a))return a}catch{}}return null}function Dt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:B(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=B(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=x(d__default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=Ot(o)??bt(o,t.packageName);return a?x(d__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Wt(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function X(t){let e=Dt(t);return Wt({candidate:e})}function V(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var H=3e4;function At(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var j=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let f=X({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=V(f,e);}catch(f){s(f instanceof Error?f:new Error(String(f)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",m="",h=false,u=setTimeout(()=>{h||(h=true,At(a),s(new Error(`Command timed out after ${n.timeoutMs??H}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??H);a.stdout?.on("data",f=>{l+=f.toString();}),a.stderr?.on("data",f=>{m+=f.toString();}),a.on("error",f=>{h||(h=true,clearTimeout(u),s(f));}),a.on("close",f=>{h||(h=true,clearTimeout(u),r({code:f??0,stdout:l,stderr:m}));});});function Ft(){try{return (typeof O=="function"?O:createRequire(g)).resolve("@crewx/sdk/package.json")}catch{return null}}function Bt(){let t=[Ft(),join(w,"../../package.json"),join(w,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var J=Bt();var S=d.win32;function I(t){return S.join(t,".crewx")}function z(t){return S.join(I(t),"shortcut.json")}function q(t){return S.join(I(t),"launcher.json")}function Q(t){return S.join(I(t),"bin","crewx-launcher.cmd")}function Y(t){return S.join(t,"CrewX.lnk")}function Z(t,e){return S.normalize(t).toLowerCase()===S.normalize(e).toLowerCase()}var $t="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function tt(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",$t],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:S.join(e,"Desktop"),source:"fallback"}:null}function b(t,e){let n=S.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?S.resolve(r).toLowerCase()!==n:true).join(";")}function et(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Xt(t,e){let n=a=>{let[l,...m]=a.split("-"),h=m.join("-")||void 0;return {parts:(l??"").split(".").map(f=>Number.parseInt(f,10)||0),pre:h}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,m=s.parts[a]??0;if(l!==m)return l<m?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function nt(t,e){return Xt(t,e)<0}var ot=d.win32,st=1;function it(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??st,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function k(t,e,n){let r={schema:st,...n,updatedAt:new Date().toISOString()};t.mkdirSync(ot.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function _(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function at(t,e,n){t.mkdirSync(ot.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var Vt=d.win32,v=1;function Ht(t){return t.replace(/%/g,"%%")}function Gt(t){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%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ht(t.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 lt(t){let e=_(t.fs,t.launcherManifestPath),n=!!e&&e.schema>=v&&t.fs.existsSync(t.wrapperPath),r=n&&!e.binPath&&!!t.bakedBinPath;if(n&&!r)return {wrapperPath:t.wrapperPath,wrote:false,schema:e.schema};let c=Gt({bakedBinPath:t.bakedBinPath});try{t.fs.mkdirSync(Vt.dirname(t.wrapperPath)),t.fs.writeFileSync(t.wrapperPath,c),at(t.fs,t.launcherManifestPath,{schema:v,binPath:t.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof p?o:new p("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:t.wrapperPath,wrote:true,schema:v}}var jt=["$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("; "),Ut=["$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 ut(t){let e={...t.env,CREWX_LNK_PATH:t.shortcutPath,CREWX_LNK_TARGET:t.targetPath,CREWX_LNK_WORKDIR:t.workingDirectory??"",CREWX_LNK_ICON:t.iconPath??""},n;try{n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",jt],{env:e});}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}`)}async function dt(t){try{let e={...t.env,CREWX_LNK_PATH:t.shortcutPath},n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Ut],{env:e});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 W=d.win32;async function y(t){let e=b(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r;try{r=await t.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let s;try{s=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=s.dependencies?.crewx;if(!c?.version)return {installed:false};let o;try{let a=await t.run("npm",["prefix","-g"],{env:n});a.code===0&&(o=a.stdout.trim()||void 0);}catch{}let i=o?W.join(o,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:o}}var Jt=/EACCES|EPERM|EROFS/,Kt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,D=10*6e4;async function ft(t){let e=b(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e};t.onProgress?.({phase:"global-install",message:"Installing crewx globally (npm install -g crewx@latest)"});let r;try{r=await t.run("npm",["install","-g","crewx@latest","--no-audit","--no-fund"],{env:n,timeoutMs:D});}catch(c){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${c instanceof Error?c.message:String(c)}`)}if(r.code===0)return {info:await y({env:n,cwd:t.cwd,run:t.run})};let s=`${r.stdout}
|
|
3
|
+
${r.stderr}`;if(Jt.test(s)){t.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let c=t.env.LOCALAPPDATA||W.join(t.env.USERPROFILE??"","AppData","Local"),o={...n,npm_config_prefix:W.join(c,"crewx","npm")},i;try{i=await t.run("npm",["install","-g","crewx@latest","--no-audit","--no-fund"],{env:o,timeoutMs:D});}catch(a){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${a instanceof Error?a.message:String(a)}`)}if(i.code===0)return {info:await y({env:o,cwd:t.cwd,run:t.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${i.stderr||i.stdout}`)}if(Kt.test(s)){if(!t.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");t.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${t.installRoot}`});let c;try{c=await t.run("npm",["install","-g",t.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:D});}catch(o){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o instanceof Error?o.message:String(o)}`)}if(c.code===0)return {info:await y({env:n,cwd:t.cwd,run:t.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${c.stderr||c.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",s.trim()||"npm install -g crewx@latest failed")}function zt(t){return t.run??j}function qt(t){return t.fs??M}async function L(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.homedir??F,s=zt(t),c=qt(t),o=t.runningVersion??J,i=t.cwd??process.cwd(),a=r(),l=z(a),m=q(a),h=Q(a),u=null;e==="win32"&&(u=await tt({env:n,homedir:r,run:s}));let f=u?Y(u.dir):null;return {platform:e,env:n,homedir:r,run:s,fs:c,runningVersion:o,cwd:i,installRoot:t.installRoot,shortcutManifestPath:l,launcherManifestPath:m,wrapperPath:h,desktop:u,shortcutPath:f}}async function P(t){if(t.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:t.runningVersion,errors:[],manifest:null};let e=[];t.desktop||e.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=it(t.fs,t.shortcutManifestPath),r=_(t.fs,t.launcherManifestPath),s=await y({env:t.env,cwd:t.cwd,run:t.run}),c=t.shortcutPath?t.fs.existsSync(t.shortcutPath):false,o;if(!c)o=n?.declined?"declined":"not-installed";else {let i=!!n?.owned&&!!t.shortcutPath&&n.shortcutPath===t.shortcutPath,a=false;if(!i&&t.shortcutPath){let l=await dt({run:t.run,env:t.env,shortcutPath:t.shortcutPath});l&&Z(l.targetPath,t.wrapperPath)?i=true:l&&et(l.targetPath)&&(a=true);}a?(o="foreign",e.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected")):i?n?.version&&nt(t.runningVersion,n.version)?(o="superseded",e.push(`SUPERSEDED: running version ${t.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`)):!r||r.schema<v||!t.fs.existsSync(t.wrapperPath)?o="stale":o="installed":o="foreign";}return {supported:true,state:o,shortcutPath:t.shortcutPath??void 0,desktopDir:t.desktop?.dir,desktopSource:t.desktop?.source,wrapperPath:t.wrapperPath,wrapperSchema:r?.schema,globalCrewx:s.installed?s:{installed:false},runningVersion:t.runningVersion,errors:e,manifest:n}}function Qt(t){if(!(!t?.installed||!t.prefix))return d.win32.join(t.prefix,"node_modules","crewx","bin","crewx.ico")}function E(t){let{manifest:e,...n}=t;return n}async function Yt(t={}){let e=await L(t),n=await P(e);return E(n)}async function Zt(t={}){let e=await L(t);t.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await P(e),r=E(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(u=>u.startsWith("NSIS_PRESENT")))throw new p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!t.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!e.desktop||!e.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let s=false,c=false,o=r.globalCrewx,i=[];if(!o?.installed){let u=await ft({env:e.env,cwd:e.cwd,run:e.run,installRoot:e.installRoot,onProgress:t.onProgress});o=u.info,c=u.info.installed,s=true,c||i.push("GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@latest exited successfully but a follow-up check could not confirm the global install");}t.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),lt({fs:e.fs,wrapperPath:e.wrapperPath,launcherManifestPath:e.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(s=true),r.state==="installed"||r.state==="stale"||(t.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await ut({run:e.run,env:e.env,shortcutPath:e.shortcutPath,targetPath:e.wrapperPath,iconPath:Qt(o)}),s=true),s&&k(e.fs,e.shortcutManifestPath,{shortcutPath:e.shortcutPath,version:e.runningVersion,owned:true,declined:false,desktopSource:e.desktop.source});let m=await P(e),h=E(m);return {...h,errors:[...h.errors,...i],changed:s,installedGlobal:c}}async function te(t={}){let e=await L(t),n=await P(e),r=E(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&e.shortcutPath)try{e.fs.unlinkSync(e.shortcutPath);}catch{}k(e.fs,e.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0});let s=await P(e);return E(s)}async function ee(t={}){let e=await L(t),n=await P(e),r=E(n);if(!r.supported)return r;k(e.fs,e.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource});let s=await P(e);return E(s)}export{p as ShortcutError,ee as dismissShortcutNotice,Yt as getShortcutStatus,Zt as installShortcut,te as uninstallShortcut};
|