@xship/cli 0.0.193 → 0.0.194
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/lib/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{configManager as v}from"./config.js";import{npmCacheArgs as y}from"./npm-cache.js";import{i18n as b}from"./i18n.js";import{appLatest as _,appStatus as $,appStatusWith as P,cachedAppStatus as x,getApp as A}from"./app-update.js";import{compareVersions as k}from"./model-registry.js";import{isJsonMode as D}from"./runtime-options.js";import{maskSecrets as S,track as j}from"./telemetry.js";import{failureContext as L,lastCommandExit as E,lastCommandOutput as C,runWatched as R}from"./tool-upgrade.js";import{runInstallScript as M,traceSummary as T}from"./install-script.js";import{atomicWriteFile as N}from"./tools/backup.js";import{getAdapter as O}from"./tools/registry.js";import{findInstallsIncludingNative as U,forgetInstalls as I,NPM_MIRROR as B,npmMirrorVersion as F}from"./tools/tool-installs.js";import{toolHome as J}from"./tools/types.js";import{logger as V}from"../utils/logger.js";let H=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}export function setComponentManifestForTests(t){H=null===t?null:parseManifest(t)}export function listComponents(){return(H||(H=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),H).components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let W=null;export function componentPlatform(){return W??process.platform}const G=/\{(scripts|agy|devtools|claudeDesktop|chatgptDesktop)\}/g;export function devtoolsMirror(){return h().installMirror?.devtools?.replace(/\/+$/,"")||void 0}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(G,(t,n)=>{const r=e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(G,(t,e)=>{const o=h().installMirror?.[e];return o??t})}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(q??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let q=null,K=!0,X=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},Z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function z(t){try{return a(t)}catch{return t}}function Y(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=J();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(Q(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function Q(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=J();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let tt=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},et=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],i=o=>{if(!function(t){try{return s(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!Z())return;const i=z(o),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=n.exec(X(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...et??=st(()=>tt())??[]);for(const t of l)if(t&&p(t))for(const n of Y(o.command,e))i(d(t,n));for(const o of knownRuntimePaths(t.id,e))(K||o.startsWith(J()))&&i(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=J();return"node"===t?"win32"===e?d(Q(e,o),"aliases","default","node.exe"):d(Q(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=z(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,i=a(r),s=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>i.includes(a(t))||s.includes(a(t)),p=t=>i.startsWith(a(t)+l)||s.startsWith(a(t)+l),f=J(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(Q(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function ot(){return d(v.getConfigDir(),"component-releases.json")}function nt(){try{const t=JSON.parse(n(ot(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function rt(t,e){try{o(v.getConfigDir(),{recursive:!0}),l(ot(),JSON.stringify({...nt(),[t]:e},null,2))}catch(t){V.logError("components.writeCache",t)}}let at=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const it=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?it.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=nt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await at(o.url));case"devtools":if(o.platforms&&!o.platforms.includes(e))return null;{const t=devtoolsMirror();return t?devtoolsVersion(await at(`${t}/versions.txt`),o.key):null}case"npm":{if(o.staleTag){const e=O(t.adapter??"")?.installSpec,o=e?await F(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await at(`${B}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=it.exec(await at(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&rt(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return V.logError(`components.latest(${t.id})`,e),rt(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,A(t.app)?await _(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=A(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?P(t.app,e.latest):e.offline?x(t.app):await $(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?st(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,i=null,s=null;if("cli"===t.category){const e=O(t.adapter)?.installSpec,o=e?U(e)[0]:void 0;o&&(a=o.version,i=o.path,s={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,i=e.path,s=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:nt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?nt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&k(a,u.version)>=0);return{...r,installed:Boolean(i),current:a,latest:l,outdated:Boolean(a&&l&&k(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:i,managed_by:s?.by??null,auto_upgrade:s?.auto??!1,...s?.hint?{hint:s.hint}:{},...c?{error:c}:{}}}function st(t){try{return t()}catch{return null}}const lt={idleMs:18e4,timeoutMs:36e5};let ct,ut=async(t,e)=>(ct=await M({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...lt,env:e},output:C,run:(t,e,o)=>R(t,e,o)}),"ok"===ct.outcome),pt=async(t,e)=>"ok"===await R(t,e,lt);function dt(t){D()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(z(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),i=[],s=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&i.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return i}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||s(d(a,t,e),`${t}/${e}`)}catch{}else s(d(a,t),t);return i}function mt(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function ft(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),i=await componentStatus(t,{refresh:!0}),s=t.name;if(!i.supported)return dt(g.yellow(" ! "+b.t("components.unsupported_platform",{tool:s}))),mt(i,"unavailable",{reason:"unsupported_platform"});if(i.blocker)return dt(g.yellow(" ! "+function(t,e){return b.t(`components.blocked_${t}`,{tool:e})}(i.blocker,s))),mt(i,"unavailable",{reason:i.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(i.installed&&!n.force){const o=g.gray(`(${i.path})`);if(i.latest&&!i.outdated)return dt(g.green(" √ "+b.t("components.up_to_date",{tool:s,current:i.current??"?"}))+o),"upgrade"===e&&dt(g.gray(" "+b.t("components.force_hint",{command:`${ft(t.id)} --force`}))),mt(i,"install"===e?"already_installed":"up_to_date");if("install"===e)return dt(g.green(" √ "+b.t("components.already_installed",{tool:s,current:i.current??"?"}))+o),i.outdated&&dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"already_installed",i.outdated?{hint:upgradeAdvice(i)}:{});if(!i.latest)return dt(g.yellow(" ! "+b.t("components.no_latest",{tool:s,current:i.current??"?",how:ht(i)}))),mt(i,"manual",{reason:i.error??"no_latest",hint:i.hint});if(!i.auto_upgrade)return dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"manual",{hint:i.hint})}if(!l)return dt(g.yellow(" ! "+b.t("components.no_mirror",{tool:s}))),mt(i,"unavailable",{reason:"no_mirror"});i.installed&&!i.auto_upgrade&&dt(g.yellow(" ! "+b.t("components.force_beside",{tool:s,path:i.path??"?",by:i.managed_by??"?"})));const p={};i.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&i.installed&&i.auto_upgrade&&i.path&&(p.UV_INSTALL_DIR=u(i.path));const d=t.upgrade?.migrateGlobalPackages&&i.installed&&"fnm"===i.managed_by&&i.path,m=d?globalPackages(i.path,a):[],f=d?z(i.path):null;dt(g.gray(" "+b.t(i.installed?"components.upgrading":"components.installing",{tool:s,latest:i.latest??"",source:i.source}))),j(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:i.current}}),d&&m.length&&f&&function(t){try{o(v.getConfigDir(),{recursive:!0}),N(vt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){V.logError("components: note migration",t)}}({packages:m,old_node:f}),ct=void 0;const w=await ut(l,p);I(),et=null;const y=probeRuntime(t,a),_=scriptTarget(t.id,a,{...process.env,...p}),$=(_?y.find(t=>{return e=t.path,o=_,"win32"===a?z(e).toLowerCase()===z(o).toLowerCase():z(e)===z(o);var e,o}):void 0)??y.find(e=>runtimeManager(t.id,e.path,a).auto)??y[0];if(!w||!$){yt();const e=ct;return j(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(C())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...T(e.trace)}:{},...E(),...L()}}),dt(g.red(" × "+b.t("components.script_failed",{tool:s,command:(i.installed?ft:gt)(t.id)}))),mt(i,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&z($.path)!==f&&(P=await wt(m,$.path,a)?"done":"failed"),"failed"!==P&&yt();const x=y[0];x&&x.path!==$.path&&x.version&&$.version&&k(x.version,$.version)<0&&dt(g.yellow(" ! "+b.t("components.path_shadowed",{tool:s,active:x.path,version:$.version,path:$.path}))),i.latest&&$.version&&k($.version,i.latest)<0&&(rt(`${t.id}:${a}:ceiling`,{version:$.version,error:i.latest,checked_at:Date.now()}),dt(g.yellow(" ! "+b.t("components.capped",{tool:s,latest:i.latest,version:$.version})))),j(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=i.installed?n.force&&!i.outdated?"reinstalled":"upgraded":"installed";var D;return dt(g.green(" √ "+("installed"===A?b.t("components.installed",{tool:s,version:$.version??"?"}):"reinstalled"===A?b.t("components.reinstalled",{tool:s,version:$.version??"?"}):b.t("components.upgraded",{tool:s,from:i.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),D=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===D.toLowerCase():t===D)||dt(g.gray(" "+b.t("components.new_terminal"))),mt(i,A,{version_after:$.version})}function gt(t){return`${w} install ${t}`}function ht(t){return t.hint?t.hint:b.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?b.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:ft(t.id)}):b.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:ht(t),command:`${ft(t.id)} --force`})}async function wt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;dt(g.gray(" "+b.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(z(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),i=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${B}`,"--no-fund","--no-audit","--loglevel=error",...y(v.getConfigDir())];return!!await pt(a,i)||(dt(g.yellow(" ! "+b.t("components.migrate_failed",{command:[a,...i].join(" ")}))),!1)}const vt=()=>d(v.getConfigDir(),"node-migration.json");function yt(){try{i(vt(),{force:!0})}catch(t){V.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(vt()))return"none";t=JSON.parse(n(vt(),"utf-8"))}catch{return yt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||z(a.path)===t.old_node)return yt(),"none";j("component:node","start",{detail:{mode:"resume-migration"}});const i=await wt(t.packages,a.path,o);return i&&yt(),j("component:node",i?"ok":"fail",{detail:{mode:"resume-migration",migration:i?"done":"failed"}}),i?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(W=t.platform),void 0!==t.uid&&(q=t.uid),void 0!==t.systemPaths&&(K=t.systemPaths),t.registryPath&&(tt=t.registryPath,et=null),t.versionRunner&&(X=t.versionRunner),t.macDeveloperTools&&(Z=t.macDeveloperTools),t.fetchText&&(at=t.fetchText),t.scriptRunner&&(ut=t.scriptRunner),t.commandRunner&&(pt=t.commandRunner)}
|
|
1
|
+
import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{withDownloadFallback as v}from"./mirror-url.js";import{configManager as y}from"./config.js";import{npmCacheArgs as b}from"./npm-cache.js";import{i18n as _}from"./i18n.js";import{appLatest as $,appStatus as P,appStatusWith as x,cachedAppStatus as A,getApp as k}from"./app-update.js";import{compareVersions as D}from"./model-registry.js";import{isJsonMode as j}from"./runtime-options.js";import{maskSecrets as S,track as L}from"./telemetry.js";import{failureContext as E,lastCommandExit as C,lastCommandOutput as R,runWatched as M}from"./tool-upgrade.js";import{runInstallScript as T,traceSummary as N}from"./install-script.js";import{atomicWriteFile as O}from"./tools/backup.js";import{getAdapter as U}from"./tools/registry.js";import{findInstallsIncludingNative as I,forgetInstalls as B,NPM_MIRROR as F,npmMirrorVersion as J}from"./tools/tool-installs.js";import{toolHome as V}from"./tools/types.js";import{logger as H}from"../utils/logger.js";let W=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}export function setComponentManifestForTests(t){W=null===t?null:parseManifest(t)}export function listComponents(){return(W||(W=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),W).components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let G=null;export function componentPlatform(){return G??process.platform}const q=/\{(scripts|agy|devtools|claudeDesktop|chatgptDesktop)\}/g;export function devtoolsMirror(){return h().installMirror?.devtools?.replace(/\/+$/,"")||void 0}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(q,(t,n)=>{const r=e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(q,(t,e)=>{const o=h().installMirror?.[e];return o??t})}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(K??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let K=null,X=!0,Z=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function Y(t){try{return a(t)}catch{return t}}function Q(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=V();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(tt(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function tt(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=V();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let et=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},ot=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],i=o=>{if(!function(t){try{return s(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!z())return;const i=Y(o),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=n.exec(Z(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...ot??=lt(()=>et())??[]);for(const t of l)if(t&&p(t))for(const n of Q(o.command,e))i(d(t,n));for(const o of knownRuntimePaths(t.id,e))(X||o.startsWith(V()))&&i(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=V();return"node"===t?"win32"===e?d(tt(e,o),"aliases","default","node.exe"):d(tt(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=Y(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,i=a(r),s=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>i.includes(a(t))||s.includes(a(t)),p=t=>i.startsWith(a(t)+l)||s.startsWith(a(t)+l),f=V(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(tt(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function nt(){return d(y.getConfigDir(),"component-releases.json")}function rt(){try{const t=JSON.parse(n(nt(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function at(t,e){try{o(y.getConfigDir(),{recursive:!0}),l(nt(),JSON.stringify({...rt(),[t]:e},null,2))}catch(t){H.logError("components.writeCache",t)}}let it=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const st=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?st.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=rt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await it(o.url));case"devtools":if(o.platforms&&!o.platforms.includes(e))return null;{const t=devtoolsMirror();return t?devtoolsVersion(await v(`${t}/versions.txt`,void 0,t=>it(t)),o.key):null}case"npm":{if(o.staleTag){const e=U(t.adapter??"")?.installSpec,o=e?await J(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await it(`${F}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=st.exec(await it(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&at(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return H.logError(`components.latest(${t.id})`,e),at(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,k(t.app)?await $(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=k(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?x(t.app,e.latest):e.offline?A(t.app):await P(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?lt(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,i=null,s=null;if("cli"===t.category){const e=U(t.adapter)?.installSpec,o=e?I(e)[0]:void 0;o&&(a=o.version,i=o.path,s={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,i=e.path,s=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:rt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?rt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&D(a,u.version)>=0);return{...r,installed:Boolean(i),current:a,latest:l,outdated:Boolean(a&&l&&D(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:i,managed_by:s?.by??null,auto_upgrade:s?.auto??!1,...s?.hint?{hint:s.hint}:{},...c?{error:c}:{}}}function lt(t){try{return t()}catch{return null}}const ct={idleMs:18e4,timeoutMs:36e5};let ut,pt=async(t,e)=>(ut=await T({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...ct,env:e},output:R,run:(t,e,o)=>M(t,e,o)}),"ok"===ut.outcome),dt=async(t,e)=>"ok"===await M(t,e,ct);function mt(t){j()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(Y(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),i=[],s=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&i.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return i}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||s(d(a,t,e),`${t}/${e}`)}catch{}else s(d(a,t),t);return i}function ft(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function gt(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),i=await componentStatus(t,{refresh:!0}),s=t.name;if(!i.supported)return mt(g.yellow(" ! "+_.t("components.unsupported_platform",{tool:s}))),ft(i,"unavailable",{reason:"unsupported_platform"});if(i.blocker)return mt(g.yellow(" ! "+function(t,e){return _.t(`components.blocked_${t}`,{tool:e})}(i.blocker,s))),ft(i,"unavailable",{reason:i.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(i.installed&&!n.force){const o=g.gray(`(${i.path})`);if(i.latest&&!i.outdated)return mt(g.green(" √ "+_.t("components.up_to_date",{tool:s,current:i.current??"?"}))+o),"upgrade"===e&&mt(g.gray(" "+_.t("components.force_hint",{command:`${gt(t.id)} --force`}))),ft(i,"install"===e?"already_installed":"up_to_date");if("install"===e)return mt(g.green(" √ "+_.t("components.already_installed",{tool:s,current:i.current??"?"}))+o),i.outdated&&mt(g.yellow(" ! "+upgradeAdvice(i))),ft(i,"already_installed",i.outdated?{hint:upgradeAdvice(i)}:{});if(!i.latest)return mt(g.yellow(" ! "+_.t("components.no_latest",{tool:s,current:i.current??"?",how:wt(i)}))),ft(i,"manual",{reason:i.error??"no_latest",hint:i.hint});if(!i.auto_upgrade)return mt(g.yellow(" ! "+upgradeAdvice(i))),ft(i,"manual",{hint:i.hint})}if(!l)return mt(g.yellow(" ! "+_.t("components.no_mirror",{tool:s}))),ft(i,"unavailable",{reason:"no_mirror"});i.installed&&!i.auto_upgrade&&mt(g.yellow(" ! "+_.t("components.force_beside",{tool:s,path:i.path??"?",by:i.managed_by??"?"})));const p={};i.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&i.installed&&i.auto_upgrade&&i.path&&(p.UV_INSTALL_DIR=u(i.path));const d=t.upgrade?.migrateGlobalPackages&&i.installed&&"fnm"===i.managed_by&&i.path,m=d?globalPackages(i.path,a):[],f=d?Y(i.path):null;mt(g.gray(" "+_.t(i.installed?"components.upgrading":"components.installing",{tool:s,latest:i.latest??"",source:i.source}))),L(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:i.current}}),d&&m.length&&f&&function(t){try{o(y.getConfigDir(),{recursive:!0}),O(yt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){H.logError("components: note migration",t)}}({packages:m,old_node:f}),ut=void 0;const w=await pt(l,p);B(),ot=null;const v=probeRuntime(t,a),b=scriptTarget(t.id,a,{...process.env,...p}),$=(b?v.find(t=>{return e=t.path,o=b,"win32"===a?Y(e).toLowerCase()===Y(o).toLowerCase():Y(e)===Y(o);var e,o}):void 0)??v.find(e=>runtimeManager(t.id,e.path,a).auto)??v[0];if(!w||!$){bt();const e=ut;return L(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(R())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...N(e.trace)}:{},...C(),...E()}}),mt(g.red(" × "+_.t("components.script_failed",{tool:s,command:(i.installed?gt:ht)(t.id)}))),ft(i,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&Y($.path)!==f&&(P=await vt(m,$.path,a)?"done":"failed"),"failed"!==P&&bt();const x=v[0];x&&x.path!==$.path&&x.version&&$.version&&D(x.version,$.version)<0&&mt(g.yellow(" ! "+_.t("components.path_shadowed",{tool:s,active:x.path,version:$.version,path:$.path}))),i.latest&&$.version&&D($.version,i.latest)<0&&(at(`${t.id}:${a}:ceiling`,{version:$.version,error:i.latest,checked_at:Date.now()}),mt(g.yellow(" ! "+_.t("components.capped",{tool:s,latest:i.latest,version:$.version})))),L(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=i.installed?n.force&&!i.outdated?"reinstalled":"upgraded":"installed";var k;return mt(g.green(" √ "+("installed"===A?_.t("components.installed",{tool:s,version:$.version??"?"}):"reinstalled"===A?_.t("components.reinstalled",{tool:s,version:$.version??"?"}):_.t("components.upgraded",{tool:s,from:i.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),k=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===k.toLowerCase():t===k)||mt(g.gray(" "+_.t("components.new_terminal"))),ft(i,A,{version_after:$.version})}function ht(t){return`${w} install ${t}`}function wt(t){return t.hint?t.hint:_.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?_.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:gt(t.id)}):_.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:wt(t),command:`${gt(t.id)} --force`})}async function vt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;mt(g.gray(" "+_.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(Y(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),i=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${F}`,"--no-fund","--no-audit","--loglevel=error",...b(y.getConfigDir())];return!!await dt(a,i)||(mt(g.yellow(" ! "+_.t("components.migrate_failed",{command:[a,...i].join(" ")}))),!1)}const yt=()=>d(y.getConfigDir(),"node-migration.json");function bt(){try{i(yt(),{force:!0})}catch(t){H.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(yt()))return"none";t=JSON.parse(n(yt(),"utf-8"))}catch{return bt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||Y(a.path)===t.old_node)return bt(),"none";L("component:node","start",{detail:{mode:"resume-migration"}});const i=await vt(t.packages,a.path,o);return i&&bt(),L("component:node",i?"ok":"fail",{detail:{mode:"resume-migration",migration:i?"done":"failed"}}),i?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(G=t.platform),void 0!==t.uid&&(K=t.uid),void 0!==t.systemPaths&&(X=t.systemPaths),t.registryPath&&(et=t.registryPath,ot=null),t.versionRunner&&(Z=t.versionRunner),t.macDeveloperTools&&(z=t.macDeveloperTools),t.fetchText&&(it=t.fetchText),t.scriptRunner&&(pt=t.scriptRunner),t.commandRunner&&(dt=t.commandRunner)}
|
package/dist/lib/mirror-url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{brand as t}from"./brand.js";import{configManager as e}from"./config.js";const r=/\/-\/releases\/latest$/;export function mirrorFileUrl(t,e,o){const n=t.replace(/\/+$/,"");if(r.test(n)){const t=n.replace(r,"");return o?`${t}/-/releases/download/${o}/${e}`:`${t}/-/releases/latest/download/${e}`}return`${n}/${e}`}export function mirrorPageUrl(t){const e=t.replace(/\/+$/,""),r=/^(.*\/-\/releases)\/download\/([^/]+)$/.exec(e);return r?`${r[1]}/tag/${r[2]}`:e.replace(/\/-\/releases\/latest\/download$/,"/-/releases/latest")}const o=/^\/[^?#]+\/-\/releases\/(?:latest\/download|download\/[^/]+)\/[^/]+$/,n=/^\/dl\/[^/]+\/[^/]+$/;function a(t){try{const e=new URL(t);return"https:"===e.protocol&&!e.search&&n.test(e.pathname)?e:null}catch{return null}}export function downloadUrls(t,e){if(a(t))return[t,`${t}?alt=1`];if(!e||!t.startsWith("https://cnb.cool/"))return[t];const r=t.slice(16);return o.test(r)?[`${e.replace(/\/+$/,"")}${r}`,t]:[t]}export async function withDownloadFallback(t,e,r){const o=downloadUrls(t,e);for(const t of o.slice(0,-1))try{return await r(t)}catch{}return r(o[o.length-1])}export async function mirrorFetch(r,o={},n=(...t)=>fetch(...t),s=()=>e.getApiKey()?.trim()){const l=a(r.replace(/\?alt=\d+$/,"")),c=l&&function(){const e=new Set;for(const r of Object.values(t().installMirror??{}))try{const t="string"==typeof r&&r?new URL(r):null;"https:"===t?.protocol&&t.pathname.startsWith("/dl/")&&e.add(t.origin)}catch{}return e}().has(l.origin)?s():void 0;if(!c)return n(r,o);let i=new URL(r);for(let t=0;t<=5;t++){const t=new Headers(o.headers);t.set("Authorization",`Bearer ${c}`);const e=await n(i.toString(),{...o,headers:t,redirect:"manual"}),r=e.headers.get("location");if(e.status<300||e.status>=400||!r)return e;await(e.body?.cancel().catch(()=>{}));const a=new URL(r,i);if(a.origin!==i.origin)return n(a.toString(),o);i=a}throw new Error(`${r}: too many redirects`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as r}from"child_process";import{createHash as e}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{
|
|
1
|
+
import{execFileSync as r}from"child_process";import{createHash as e}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{mirrorFetch as P,mirrorFileUrl as L,withDownloadFallback as O}from"../mirror-url.js";import{powerShellEnv as E}from"../powershell-env.js";export function readDesktopCliPin(r,e,t=!1){const o=r.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=r.lastIndexOf("JSON.parse('",o),n=r.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(r.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[e],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function j(){const e=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(e)){const r=n(e).filter(r=>/^app-\d+\.\d+\.\d+$/.test(r)).sort((r,e)=>e.localeCompare(r,void 0,{numeric:!0}));for(const t of r){const r=m(e,t,"resources","app.asar");if(s(r))return r}}try{const e=r("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(r=>`'${r}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:E()});for(const r of e.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)){const e=m(r,"app","resources","app.asar");if(s(e))return e}}catch(r){y.logError("claude-desktop-cli.windowsAsarPath",r)}return null}function F(){if($("TEST_HOME")?.trim())return null;for(const r of["/usr/lib/claude-desktop","/opt/Claude"]){const e=m(r,"resources","app.asar");if(s(e))return e}return null}function T(){for(const r of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const e=m(r,"Contents","Resources","app.asar");if(s(e))return e}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?j():"darwin"===process.platform?T():"linux"===process.platform?F():null}class K extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(r){super(),this.dest=r}_write(r,e,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,r]):r,this.drain().then(()=>t()).catch(t)}_final(r){this.remaining>0?r(new Error("archive ends inside an entry")):r()}target(r){const e=h(r);if(!e||d(e)||".."===e||e.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${r}`);return m(this.dest,e)}async closeFile(){const r=this.file;this.file=null,r&&await new Promise((e,t)=>r.end(r=>r?t(r):e()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const r=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(r.length),this.remaining-=r.length,this.collectingLongName?this.collectingLongName.push(r):this.file&&!this.file.write(r)&&await new Promise(r=>this.file.once("drain",()=>r())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const r=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),r.every(r=>0===r))continue;const e=(e,t)=>r.subarray(e,e+t).toString("utf-8").replace(/\0.*$/s,""),t=e(345,155);let s=t?`${t}/${e(0,100)}`:e(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(e(124,12).trim()||"0",8),i=511&parseInt(e(100,8).trim()||"644",8),a=e(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(s),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${s}`);{const r=this.target(s);await l(m(r,".."),{recursive:!0}),this.file=o(r,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(r){const o=readDesktopCliPin(r.asar,r.platformKey,r.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(r.bundle&&!r.download)return{status:"skipped",reason:"no bundle mirror"};const n=r.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(r.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=r.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(s(h)&&(await c(w,"utf-8")).trim()===o.checksum)return{status:"present",version:o.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${o.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(r.bundle){if(r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version),await r.download(o.version,y),await async function(r,o,s){const n=e("sha256");if(await v(t(r),new b({write(r,e,t){n.update(r),t()}})),n.digest("hex")!==o)throw new Error("downloaded bundle does not match the app's checksum");const i=D.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await v(t(r),i(),new K(s))}(y,o.checksum,g),!s(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const e=r.localVersionsDir?m(r.localVersionsDir,o.version):null;if(e&&s(e))r.onStart?.(o.version,"local"),await a(e,g),n="local";else{r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version);const e=r.download??((e,t)=>C(r.platformKey,e,t));await e(o.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,o.checksum),{status:"installed",version:o.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let V=(...r)=>fetch(...r);export function setDesktopCliFetchForTests(r){V=r}export async function ensureDesktopCli(r){const e=x();if(!e)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=j();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,localVersionsDir:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=T();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=r;return installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,bundle:!0,onDownload:r.onDownload,onStart:r.onStart,download:s&&n?(r,t)=>O(L(s,`d1-cli-${r}-${e}.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,r=>async function(r,e){const t=await P(r,{signal:AbortSignal.timeout(9e5)},V);if(!t.ok||!t.body)throw new Error(`${r}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(e))}(r,t)):void 0})}if("linux"===process.platform){const t=F();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e.replace(/-musl$/,""),localVersionsDir:e.endsWith("-musl")?void 0:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readdirSync as p,readFileSync as u,renameSync as d,rmSync as f,statSync as m}from"fs";import{cpus as g,tmpdir as h}from"os";import{basename as w,dirname as $,join as y}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as E}from"../../utils/logger.js";import{i18n as v}from"../i18n.js";import{powerShellEnv as k}from"../powershell-env.js";import{toolHome as P}from"./types.js";import{configManager as _}from"../config.js";import{brand as b}from"../brand.js";import{mirrorFileUrl as I,withDownloadFallback as C}from"../mirror-url.js";import{processAlive as T}from"../../utils/process-alive.js";const M=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:k()});return n.error&&E.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let j=M,R=(...t)=>fetch(...t),F=null,N=null,O=null,D=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(j=t.run??M),void 0!==t.fetch&&(R=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(F=t.platform),void 0!==t.arm64&&(N=t.arm64),void 0!==t.privileged&&(O=t.privileged),void 0!==t.remote&&(D=t.remote)}export function appPlatform(){return F??process.platform}export function isArm64Machine(){return null!==N?N:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(g()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||v.t("app_update.reason_unknown");throw new DesktopInstallError(v.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function W(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function B(t,e){const r=await R(t,{signal:AbortSignal.timeout(e)});if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function H(t,e){try{const r=u(y(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return H(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(H(t,"CFBundleShortVersionString")??"")?.[0]??null}function V(t){try{return r(t,o.W_OK),!0}catch{return!1}}const L=t=>`'${t.replace(/'/g,"''")}'`;function U(t,e=12e4){return j("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>["/Applications",y(P(),"Applications")],s=()=>{const e=[];for(const r of o()){let o;try{o=p(r)}catch{continue}for(const n of t.macApp.installedNames)for(const t of o){if(!t.startsWith(`.${n}.`))continue;const o=/^(\d+)\.(new|old)$/.exec(t.slice(n.length+2));o&&!T(Number(o[1]))&&e.push({path:y(r,t),target:y(r,n),kind:o[2]})}}return e},g=()=>{if("darwin"===appPlatform())for(const e of s())if("old"===e.kind&&!a(e.target)&&a(y(e.path,"Contents","Info.plist")))try{d(e.path,e.target),E.debug(`${t.id}: restored ${e.target} from an interrupted install`)}catch(e){E.logError(`${t.id}: restore interrupted install`,e)}},k=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(O??0===process.getuid?.())?"root":"win32"===o&&(null!==O?O:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==D?D:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},M=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await B(I(o,n),r),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},F=()=>{g();for(const e of o())for(const r of t.macApp.installedNames){const o=y(e,r);if(!a(y(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},N=e=>{const r=j("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=j("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=j("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},H=()=>{const e=F();let r=e;if(!r){const e=V("/Applications")?"/Applications":y(P(),"Applications");r=y(e,t.macApp.installedNames[0])}const o=$(r);return(a(o)&&!V(o)||e&&!V(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},G=e=>{const r=U(`$s = Get-AuthenticodeSignature -LiteralPath ${L(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},J=()=>{const e=U(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:k,latestVersion:M,installedMacApp:F,windowsPackageVersion:J,verifyMacApp:N,verifyWindowsPackage:G,install:async(o={})=>{const P=k();P&&fail("blocked",{reason:v.t(`app_update.reason_${P}`)}),(()=>{if("darwin"===appPlatform()){g();for(const e of s())try{f(e.path,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove leftover`,e)}}const e=new Set(["mnt"]);for(const r of["darwin","win32"])for(const o of[!0,!1]){const n=t.asset(r,o);n&&e.add(n)}const r=new RegExp(`^${t.id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}-[A-Za-z0-9]{6}$`);let o=[];try{o=p(h())}catch{}for(const n of o){if(!r.test(n))continue;const o=y(h(),n);try{if(!m(o).isDirectory())continue;const t=p(o);if(0===t.length||!t.every(t=>e.has(t)))continue;const r=Math.max(...[o,...t.map(t=>y(o,t))].map(t=>m(t).mtimeMs));if(Date.now()-r<864e5)continue;const n=y(o,"mnt");if("darwin"===appPlatform()&&a(n)&&(j("hdiutil",["detach",n,"-force"],{timeout:6e4}),p(n).length>0))continue;f(o,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove stale work folder`,e)}}})();const T=e(),F=r();let O;try{O=await M(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const D=e=>I(T,e,t.releaseTag?.(O)),V=b().installMirror?.downloadCounter;let X;try{X=parseSha256Sums(await C(D("SHA256SUMS"),V,t=>B(t,15e3))).get(F)}catch(e){E.logError(`${t.id}: SHA256SUMS`,e)}X||fail("no_checksum",{file:F}),"darwin"===appPlatform()&&H();const q=y(_.getConfigDir(),"downloads",t.id),z=y(q,F),K=l(y(h(),`${t.id}-`));let Q=y(K,F),Y=!1;try{a(z)&&await W(z)===X?(Q=z,o.reusing?.(O)):(o.downloading?.(O),await C(D(F),V,t=>async function(t,e,r){let o;try{o=await R(t,{signal:AbortSignal.timeout(18e5)})}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){f(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,Q,o.percent))),o.verifying?.();const e=await W(Q);e!==X&&fail("checksum",{file:F,expected:X.slice(0,12),actual:e.slice(0,12)}),o.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=y(r,"mnt");c(o,{recursive:!0});const n=j("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=y(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=H(),i=$(r),l=w(r);c(i,{recursive:!0}),s=y(i,`.${l}.${process.pid}.new`),f(s,{recursive:!0,force:!0});const p=j("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),N(s);const u=macAppVersion(s);u||fail("bad_package",{reason:"Info.plist"});const m=y(i,`.${l}.${process.pid}.old`);try{n&&d(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{d(s,r)}catch(t){throw n&&d(m,n),t}return s=null,f(m,{recursive:!0,force:!0}),{version:u,location:r}}finally{s&&f(s,{recursive:!0,force:!0}),j("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(Q,K):await(async(t,e)=>{G(t);const r=U(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=y($(t),"elevated-install.log");f(e,{force:!0});const r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${L(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=U(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=u(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),J()||fail("other_account")}const o=J();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(Q,o);return Y=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw Q!==z&&a(Q)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{f(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{d(t,r)}catch{n(t,r)}}catch(t){E.logError("desktop-app: keep package",t),f(e,{recursive:!0,force:!0})}}(Q,q,z),Q===z&&["signature","bad_package","mount"].includes(e??"")&&f(q,{recursive:!0,force:!0}),t}finally{Y&&f(q,{recursive:!0,force:!0}),f(K,{recursive:!0,force:!0})}}}}
|
|
1
|
+
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readdirSync as p,readFileSync as u,renameSync as d,rmSync as f,statSync as m}from"fs";import{cpus as g,tmpdir as h}from"os";import{basename as w,dirname as $,join as y}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as E}from"../../utils/logger.js";import{i18n as v}from"../i18n.js";import{powerShellEnv as k}from"../powershell-env.js";import{toolHome as P}from"./types.js";import{configManager as _}from"../config.js";import{brand as b}from"../brand.js";import{mirrorFetch as I,mirrorFileUrl as C,withDownloadFallback as T}from"../mirror-url.js";import{processAlive as M}from"../../utils/process-alive.js";const j=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:k()});return n.error&&E.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let R=j,F=(...t)=>fetch(...t),N=null,O=null,D=null,W=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(R=t.run??j),void 0!==t.fetch&&(F=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(N=t.platform),void 0!==t.arm64&&(O=t.arm64),void 0!==t.privileged&&(D=t.privileged),void 0!==t.remote&&(W=t.remote)}export function appPlatform(){return N??process.platform}export function isArm64Machine(){return null!==O?O:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(g()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||v.t("app_update.reason_unknown");throw new DesktopInstallError(v.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function B(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function H(t,e){const r=await I(t,{signal:AbortSignal.timeout(e)},F);if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function V(t,e){try{const r=u(y(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return V(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(V(t,"CFBundleShortVersionString")??"")?.[0]??null}function L(t){try{return r(t,o.W_OK),!0}catch{return!1}}const U=t=>`'${t.replace(/'/g,"''")}'`;function G(t,e=12e4){return R("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>["/Applications",y(P(),"Applications")],s=()=>{const e=[];for(const r of o()){let o;try{o=p(r)}catch{continue}for(const n of t.macApp.installedNames)for(const t of o){if(!t.startsWith(`.${n}.`))continue;const o=/^(\d+)\.(new|old)$/.exec(t.slice(n.length+2));o&&!M(Number(o[1]))&&e.push({path:y(r,t),target:y(r,n),kind:o[2]})}}return e},g=()=>{if("darwin"===appPlatform())for(const e of s())if("old"===e.kind&&!a(e.target)&&a(y(e.path,"Contents","Info.plist")))try{d(e.path,e.target),E.debug(`${t.id}: restored ${e.target} from an interrupted install`)}catch(e){E.logError(`${t.id}: restore interrupted install`,e)}},k=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(D??0===process.getuid?.())?"root":"win32"===o&&(null!==D?D:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==W?W:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},j=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await T(C(o,n),void 0,t=>H(t,r)),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},N=()=>{g();for(const e of o())for(const r of t.macApp.installedNames){const o=y(e,r);if(!a(y(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},O=e=>{const r=R("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=R("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=R("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},V=()=>{const e=N();let r=e;if(!r){const e=L("/Applications")?"/Applications":y(P(),"Applications");r=y(e,t.macApp.installedNames[0])}const o=$(r);return(a(o)&&!L(o)||e&&!L(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},J=e=>{const r=G(`$s = Get-AuthenticodeSignature -LiteralPath ${U(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},X=()=>{const e=G(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:k,latestVersion:j,installedMacApp:N,windowsPackageVersion:X,verifyMacApp:O,verifyWindowsPackage:J,install:async(o={})=>{const P=k();P&&fail("blocked",{reason:v.t(`app_update.reason_${P}`)}),(()=>{if("darwin"===appPlatform()){g();for(const e of s())try{f(e.path,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove leftover`,e)}}const e=new Set(["mnt"]);for(const r of["darwin","win32"])for(const o of[!0,!1]){const n=t.asset(r,o);n&&e.add(n)}const r=new RegExp(`^${t.id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}-[A-Za-z0-9]{6}$`);let o=[];try{o=p(h())}catch{}for(const n of o){if(!r.test(n))continue;const o=y(h(),n);try{if(!m(o).isDirectory())continue;const t=p(o);if(0===t.length||!t.every(t=>e.has(t)))continue;const r=Math.max(...[o,...t.map(t=>y(o,t))].map(t=>m(t).mtimeMs));if(Date.now()-r<864e5)continue;const n=y(o,"mnt");if("darwin"===appPlatform()&&a(n)&&(R("hdiutil",["detach",n,"-force"],{timeout:6e4}),p(n).length>0))continue;f(o,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove stale work folder`,e)}}})();const M=e(),N=r();let D;try{D=await j(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const W=e=>C(M,e,t.releaseTag?.(D)),L=b().installMirror?.downloadCounter;let q;try{q=parseSha256Sums(await T(W("SHA256SUMS"),L,t=>H(t,15e3))).get(N)}catch(e){E.logError(`${t.id}: SHA256SUMS`,e)}q||fail("no_checksum",{file:N}),"darwin"===appPlatform()&&V();const z=y(_.getConfigDir(),"downloads",t.id),K=y(z,N),Q=l(y(h(),`${t.id}-`));let Y=y(Q,N),Z=!1;try{a(K)&&await B(K)===q?(Y=K,o.reusing?.(D)):(o.downloading?.(D),await T(W(N),L,t=>async function(t,e,r){let o;try{o=await I(t,{signal:AbortSignal.timeout(18e5)},F)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){f(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,Y,o.percent))),o.verifying?.();const e=await B(Y);e!==q&&fail("checksum",{file:N,expected:q.slice(0,12),actual:e.slice(0,12)}),o.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=y(r,"mnt");c(o,{recursive:!0});const n=R("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=y(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=V(),i=$(r),l=w(r);c(i,{recursive:!0}),s=y(i,`.${l}.${process.pid}.new`),f(s,{recursive:!0,force:!0});const p=R("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),O(s);const u=macAppVersion(s);u||fail("bad_package",{reason:"Info.plist"});const m=y(i,`.${l}.${process.pid}.old`);try{n&&d(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{d(s,r)}catch(t){throw n&&d(m,n),t}return s=null,f(m,{recursive:!0,force:!0}),{version:u,location:r}}finally{s&&f(s,{recursive:!0,force:!0}),R("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(Y,Q):await(async(t,e)=>{J(t);const r=G(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${U(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=y($(t),"elevated-install.log");f(e,{force:!0});const r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${U(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${U(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=G(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=u(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),X()||fail("other_account")}const o=X();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(Y,o);return Z=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw Y!==K&&a(Y)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{f(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{d(t,r)}catch{n(t,r)}}catch(t){E.logError("desktop-app: keep package",t),f(e,{recursive:!0,force:!0})}}(Y,z,K),Y===K&&["signature","bad_package","mount"].includes(e??"")&&f(z,{recursive:!0,force:!0}),t}finally{Z&&f(z,{recursive:!0,force:!0}),f(Q,{recursive:!0,force:!0})}}}}
|