install-source.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
  2. import path from 'node:path';
  3. import spawn from 'cross-spawn';
  4. import { parseMcodeVersion } from './release.js';
  5. import { isManagedMcodeInstallRoot } from './service.js';
  6. import type { McodeUpdateOperationOptions } from './progress.js';
  7. export const MCODE_INTERNAL_NPM_REGISTRY = 'https://npmmirror.example.invalid/';
  8. export const MCODE_PUBLIC_NPM_REGISTRY = 'https://registry.npmjs.org/';
  9. export const MCODE_PUBLIC_NPM_MIRROR_REGISTRY = 'https://registry.npmmirror.com/';
  10. const REGISTRY_FETCH_TIMEOUT_MS = 30_000;
  11. const MCODE_PACKAGE_BASENAME = 'code';
  12. const MCODE_INTERNAL_SCOPE = '@minimax';
  13. const MCODE_PUBLIC_SCOPE = '@minimax-ai';
  14. // Public packaging rewrites this marker together with the bundled package identity.
  15. const MCODE_EMBEDDED_PACKAGE_NAME = '@minimax-ai/code' as McodeNpmPackageName;
  16. export type McodeNpmDistTag = 'latest' | 'test' | 'preview';
  17. export type McodeNpmPackageName = '@minimax/code' | '@minimax-ai/code';
  18. type TuiBuildEnvironment = 'test' | 'staging' | 'prod';
  19. declare const __TUI_BUILD_ENV__: TuiBuildEnvironment | undefined;
  20. declare const __TUI_NPM_DIST_TAG__: McodeNpmDistTag | undefined;
  21. export type McodePackageManagerInstallSource =
  22. | 'npm-global'
  23. | 'npm-prefix'
  24. | 'pnpm-global'
  25. | 'yarn-global'
  26. | 'bun-global';
  27. export type McodeInstallSource =
  28. | 'managed-installer'
  29. | McodePackageManagerInstallSource
  30. | 'unsupported';
  31. export interface McodePackageManagerCommand {
  32. readonly executable: string;
  33. readonly args: readonly string[];
  34. readonly display: string;
  35. }
  36. export interface McodeNpmPrefixInstall {
  37. readonly executable: string;
  38. readonly packageName: McodeNpmPackageName;
  39. readonly prefix: string;
  40. readonly registry: string;
  41. }
  42. export type McodePackageManagerRunOptions = McodeUpdateOperationOptions;
  43. export interface McodeNpmDistribution {
  44. readonly packageName: McodeNpmPackageName;
  45. readonly registry: string;
  46. }
  47. export interface ResolveLatestMcodeRegistryVersionDependencies {
  48. readonly platform: NodeJS.Platform;
  49. readonly run: (command: string, args: readonly string[]) => Promise<string>;
  50. readonly distribution: McodeNpmDistribution;
  51. readonly npmExecutable: string;
  52. readonly environment: NodeJS.ProcessEnv;
  53. readonly runtimeExecutable: string;
  54. }
  55. export interface DetectMcodeInstallSourceDependencies {
  56. readonly installRoot: string;
  57. readonly platform: NodeJS.Platform;
  58. readonly packageRoot: () => string | undefined;
  59. readonly npmGlobalPrefix: () => Promise<string>;
  60. readonly managedInstall: (installRoot: string) => boolean;
  61. readonly prefixInstall: () => McodeNpmPrefixInstall | undefined;
  62. }
  63. export async function detectMcodeInstallSource(
  64. dependencies: Partial<DetectMcodeInstallSourceDependencies> & { installRoot: string },
  65. ): Promise<McodeInstallSource> {
  66. const platform = dependencies.platform ?? process.platform;
  67. const resolved: DetectMcodeInstallSourceDependencies = {
  68. installRoot: dependencies.installRoot,
  69. platform,
  70. packageRoot: dependencies.packageRoot ?? resolveMcodePackageRoot,
  71. npmGlobalPrefix:
  72. dependencies.npmGlobalPrefix ??
  73. (() => runText(platform === 'win32' ? 'npm.cmd' : 'npm', ['prefix', '--global'])),
  74. managedInstall: dependencies.managedInstall ?? isManagedMcodeInstallRoot,
  75. prefixInstall: dependencies.prefixInstall ?? resolveMcodeNpmPrefixInstall,
  76. };
  77. if (resolved.managedInstall(resolved.installRoot)) return 'managed-installer';
  78. if (resolved.prefixInstall()) return 'npm-prefix';
  79. const packageRoot = resolved.packageRoot();
  80. if (!packageRoot) return 'unsupported';
  81. const heuristic = classifyMcodeInstallPath(packageRoot);
  82. if (heuristic) return heuristic;
  83. try {
  84. return classifyNpmGlobalInstall(packageRoot, await resolved.npmGlobalPrefix(), platform);
  85. } catch {
  86. return 'unsupported';
  87. }
  88. }
  89. export function classifyMcodeInstallPath(
  90. packageRoot: string,
  91. ): McodePackageManagerInstallSource | undefined {
  92. const normalized = packageRoot.replaceAll('\\', '/').toLocaleLowerCase();
  93. if (
  94. /\/pnpm\/global\/(?:v11\/[^/]+|[^/]+)\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  95. ) {
  96. return 'pnpm-global';
  97. }
  98. if (
  99. /\/(?:\.config\/yarn|\.yarn)\/global\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  100. ) {
  101. return 'yarn-global';
  102. }
  103. if (/\/\.bun\/install\/global\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)) {
  104. return 'bun-global';
  105. }
  106. if (
  107. /\/lib\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized) ||
  108. /\/npm\/node_modules\/@minimax(?:-ai)?\/code$/u.test(normalized)
  109. ) {
  110. return 'npm-global';
  111. }
  112. return undefined;
  113. }
  114. export function resolveMcodeNpmDistribution(
  115. packageName: McodeNpmPackageName = resolveMcodePackageName() ?? MCODE_EMBEDDED_PACKAGE_NAME,
  116. registry?: string,
  117. ): McodeNpmDistribution {
  118. if (packageName === mcodePackageName(MCODE_INTERNAL_SCOPE)) {
  119. const resolvedRegistry = registry ? new URL(registry).href : MCODE_INTERNAL_NPM_REGISTRY;
  120. if (resolvedRegistry === MCODE_INTERNAL_NPM_REGISTRY) {
  121. return { packageName, registry: resolvedRegistry };
  122. }
  123. throw new Error(`Unsupported MCode npm registry: ${resolvedRegistry}`);
  124. }
  125. if (packageName === mcodePackageName(MCODE_PUBLIC_SCOPE)) {
  126. const resolvedRegistry = registry ? new URL(registry).href : MCODE_PUBLIC_NPM_REGISTRY;
  127. if (
  128. resolvedRegistry === MCODE_PUBLIC_NPM_REGISTRY ||
  129. resolvedRegistry === MCODE_PUBLIC_NPM_MIRROR_REGISTRY
  130. ) {
  131. return { packageName, registry: resolvedRegistry };
  132. }
  133. throw new Error(`Unsupported MCode npm registry: ${resolvedRegistry}`);
  134. }
  135. throw new Error(`Unsupported MCode npm package: ${String(packageName)}`);
  136. }
  137. export function resolveMcodeNpmDistTag(
  138. environment: TuiBuildEnvironment | undefined = readEmbeddedTuiBuildEnvironment(),
  139. embeddedTag: McodeNpmDistTag | undefined = readEmbeddedTuiNpmDistTag(),
  140. ): McodeNpmDistTag {
  141. if (embeddedTag) return embeddedTag;
  142. if (environment === 'test') return 'test';
  143. if (environment === 'staging') return 'preview';
  144. return 'latest';
  145. }
  146. export function classifyNpmGlobalInstall(
  147. packageRoot: string,
  148. globalPrefix: string,
  149. platform: NodeJS.Platform = process.platform,
  150. ): McodeInstallSource {
  151. const normalizedRoot = normalizeResolvedPath(packageRoot, platform);
  152. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  153. const packageName =
  154. mcodePackageNameFromPath(packageRoot) ?? mcodePackageName(MCODE_INTERNAL_SCOPE);
  155. const candidates =
  156. platform === 'win32'
  157. ? [platformPath.join(globalPrefix, 'node_modules', packageName)]
  158. : [
  159. platformPath.join(globalPrefix, 'lib', 'node_modules', packageName),
  160. platformPath.join(globalPrefix, 'node_modules', packageName),
  161. ];
  162. return candidates.some(
  163. (candidate) => normalizeResolvedPath(candidate, platform) === normalizedRoot,
  164. )
  165. ? 'npm-global'
  166. : 'unsupported';
  167. }
  168. export function buildMcodePackageManagerCommand(
  169. source: McodePackageManagerInstallSource,
  170. version: string,
  171. platform: NodeJS.Platform = process.platform,
  172. distribution: McodeNpmDistribution = resolveMcodeNpmDistribution(),
  173. prefixInstall?: McodeNpmPrefixInstall,
  174. ): McodePackageManagerCommand {
  175. const targetVersion = ['latest', 'preview', 'test'].includes(version)
  176. ? version
  177. : parseMcodeVersion(version);
  178. const target = `${distribution.packageName}@${targetVersion}`;
  179. const registryArgs = ['--registry', distribution.registry] as const;
  180. const registryDisplay = `--registry ${distribution.registry}`;
  181. const npmInstallArgs = [
  182. '--ignore-scripts=false',
  183. '--include=optional',
  184. `--allow-scripts=${distribution.packageName},better-sqlite3`,
  185. ];
  186. const npmInstallDisplay = npmInstallArgs.join(' ');
  187. switch (source) {
  188. case 'npm-prefix': {
  189. if (!prefixInstall) throw new Error('MCode npm prefix ownership metadata is missing.');
  190. if (
  191. prefixInstall.packageName !== distribution.packageName ||
  192. new URL(prefixInstall.registry).href !== distribution.registry
  193. ) {
  194. throw new Error('MCode npm prefix ownership does not match the installed package.');
  195. }
  196. return {
  197. executable: prefixInstall.executable,
  198. args: [
  199. 'install',
  200. '--global',
  201. '--prefix',
  202. prefixInstall.prefix,
  203. target,
  204. ...npmInstallArgs,
  205. ...registryArgs,
  206. ],
  207. display:
  208. `${prefixInstall.executable} install --global --prefix ${prefixInstall.prefix} ` +
  209. `${target} ${npmInstallDisplay} ${registryDisplay}`,
  210. };
  211. }
  212. case 'npm-global':
  213. return {
  214. executable: platform === 'win32' ? 'npm.cmd' : 'npm',
  215. args: ['install', '--global', target, ...npmInstallArgs, ...registryArgs],
  216. display: `npm install --global ${target} ${npmInstallDisplay} ${registryDisplay}`,
  217. };
  218. case 'pnpm-global':
  219. return {
  220. executable: platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
  221. args: ['add', '--global', target, ...registryArgs],
  222. display: `pnpm add --global ${target} ${registryDisplay}`,
  223. };
  224. case 'yarn-global':
  225. return {
  226. executable: platform === 'win32' ? 'yarn.cmd' : 'yarn',
  227. args: ['global', 'add', target, ...registryArgs],
  228. display: `yarn global add ${target} ${registryDisplay}`,
  229. };
  230. case 'bun-global':
  231. return {
  232. executable: platform === 'win32' ? 'bun.exe' : 'bun',
  233. args: ['add', '--global', target, ...registryArgs],
  234. display: `bun add --global ${target} ${registryDisplay}`,
  235. };
  236. }
  237. }
  238. export async function resolveLatestMcodeRegistryVersion(
  239. tag: McodeNpmDistTag,
  240. dependencies: Partial<ResolveLatestMcodeRegistryVersionDependencies> = {},
  241. ): Promise<string> {
  242. const platform = dependencies.platform ?? process.platform;
  243. const distribution = dependencies.distribution ?? resolveMcodeNpmDistribution();
  244. const run =
  245. dependencies.run ??
  246. ((executable, args) => {
  247. const command = { executable, args, display: executable };
  248. const bound = dependencies.runtimeExecutable
  249. ? bindMcodeNpmCommandToRuntime(command, dependencies.runtimeExecutable)
  250. : command;
  251. return runText(bound.executable, bound.args, dependencies.environment);
  252. });
  253. const npmExecutable = dependencies.npmExecutable ?? (platform === 'win32' ? 'npm.cmd' : 'npm');
  254. const output = await run(npmExecutable, [
  255. 'view',
  256. `${distribution.packageName}@${tag}`,
  257. 'version',
  258. '--json',
  259. '--registry',
  260. distribution.registry,
  261. '--fetch-timeout',
  262. String(REGISTRY_FETCH_TIMEOUT_MS),
  263. ]);
  264. let version: unknown;
  265. try {
  266. version = JSON.parse(output);
  267. } catch {
  268. version = output.trim();
  269. }
  270. if (Array.isArray(version)) {
  271. if (version.length !== 1) {
  272. throw new Error('MCode registry returned an invalid latest version.');
  273. }
  274. version = version[0];
  275. }
  276. if (typeof version !== 'string') {
  277. throw new Error('MCode registry returned an invalid latest version.');
  278. }
  279. const parsed = parseMcodeVersion(version);
  280. if (tag === 'latest' && parsed.includes('-')) {
  281. throw new Error('MCode latest must resolve to a stable semantic version.');
  282. }
  283. return parsed;
  284. }
  285. function readEmbeddedTuiBuildEnvironment(): TuiBuildEnvironment | undefined {
  286. if (typeof __TUI_BUILD_ENV__ === 'undefined') return undefined;
  287. return __TUI_BUILD_ENV__;
  288. }
  289. function readEmbeddedTuiNpmDistTag(): McodeNpmDistTag | undefined {
  290. if (typeof __TUI_NPM_DIST_TAG__ === 'undefined') return undefined;
  291. return __TUI_NPM_DIST_TAG__;
  292. }
  293. export function bindMcodeNpmCommandToRuntime(
  294. command: McodePackageManagerCommand,
  295. runtimeExecutable: string,
  296. ): McodePackageManagerCommand {
  297. const npmExecutable = realpathSync(command.executable);
  298. const npmDirectory = path.dirname(npmExecutable);
  299. // Unix npm is normally a symlink to npm-cli.js. Windows npm.cmd prefers its
  300. // adjacent node.exe over PATH, so bypass that shim and invoke the JS entry.
  301. const candidates = [
  302. ...(path.basename(npmExecutable) === 'npm-cli.js' ? [npmExecutable] : []),
  303. path.join(npmDirectory, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
  304. path.join(npmDirectory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
  305. ];
  306. const npmCli =
  307. candidates.find((file) => existsSync(file) && statSync(file).isFile()) ??
  308. resolvePnpmNpmShim(npmExecutable);
  309. if (!npmCli)
  310. throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${command.executable}`);
  311. return { ...command, executable: runtimeExecutable, args: [npmCli, ...command.args] };
  312. }
  313. function resolvePnpmNpmShim(npmExecutable: string): string | undefined {
  314. // pnpm env places npm behind a shell shim in PNPM_HOME. Read only its literal
  315. // versioned CLI target; never execute/source the shim or search other runtimes.
  316. try {
  317. const metadata = statSync(npmExecutable);
  318. if (!metadata.isFile() || metadata.size > 64 * 1024) return undefined;
  319. const lines = readFileSync(npmExecutable, 'utf8').split(/\r?\n/u);
  320. if (lines[0] !== '#!/bin/sh') return undefined;
  321. const commands = lines.map((line) => line.trim()).filter((line) => /^exec\s/u.test(line));
  322. if (commands.length === 0) return undefined;
  323. const targets = commands.map((line) =>
  324. /^exec (?:"\$basedir\/node"|node) "\$basedir\/(nodejs\/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\/lib\/node_modules\/npm\/bin\/npm-cli\.js)" "\$@"$/u.exec(line)?.[1],
  325. );
  326. const target = targets[0];
  327. if (!target || targets.some((candidate) => candidate !== target)) return undefined;
  328. const npmDirectory = path.dirname(npmExecutable);
  329. const versionRoot = path.join(npmDirectory, ...target.split('/').slice(0, 2));
  330. const cli = realpathSync(path.join(npmDirectory, target));
  331. // Reject symlinks that redirect the target outside this pnpm Node version.
  332. if (!isResolvedPathInside(versionRoot, cli, path) || !statSync(cli).isFile()) return undefined;
  333. return cli;
  334. } catch {
  335. return undefined;
  336. }
  337. }
  338. export function createMcodeNpmRuntimeEnvironment(
  339. environment: NodeJS.ProcessEnv,
  340. runtimeExecutable: string,
  341. platform: NodeJS.Platform = process.platform,
  342. ): NodeJS.ProcessEnv {
  343. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  344. const result = { ...environment };
  345. // Windows environment keys are case-insensitive. Keep only one PATH key so Node and
  346. // cross-spawn cannot choose a different inherited spelling.
  347. const pathKeys = Object.keys(result)
  348. .filter((key) => (platform === 'win32' ? key.toLowerCase() === 'path' : key === 'PATH'))
  349. .sort();
  350. const inheritedPath = result[pathKeys[0] ?? 'PATH'];
  351. for (const key of pathKeys) delete result[key];
  352. result.PATH = [platformPath.dirname(runtimeExecutable), inheritedPath]
  353. .filter(Boolean)
  354. .join(platformPath.delimiter);
  355. return result;
  356. }
  357. export function runMcodePackageManagerCommand(
  358. command: McodePackageManagerCommand,
  359. environment: NodeJS.ProcessEnv = process.env,
  360. options: McodePackageManagerRunOptions = {},
  361. ): Promise<void> {
  362. return new Promise((resolve, reject) => {
  363. let settled = false;
  364. const child = spawn(command.executable, [...command.args], {
  365. env: environment,
  366. shell: false,
  367. stdio: ['ignore', 'pipe', 'pipe'],
  368. windowsHide: true,
  369. });
  370. const stdout: Buffer[] = [];
  371. const stderr: Buffer[] = [];
  372. child.stdout?.on('data', (chunk: Buffer) => {
  373. stdout.push(chunk);
  374. notifyPackageManagerOutput(options, chunk);
  375. });
  376. child.stderr?.on('data', (chunk: Buffer) => {
  377. stderr.push(chunk);
  378. notifyPackageManagerOutput(options, chunk);
  379. });
  380. child.once('error', (error) => {
  381. if (settled) return;
  382. settled = true;
  383. reject(error);
  384. });
  385. child.once('exit', (code, signal) => {
  386. if (settled) return;
  387. settled = true;
  388. if (code === 0) {
  389. resolve();
  390. return;
  391. }
  392. const details = Buffer.concat([...stderr, ...stdout])
  393. .toString('utf8')
  394. .trim();
  395. reject(
  396. new Error(
  397. `${command.executable} failed (${
  398. signal ? `signal ${signal}` : `exit ${String(code)}`
  399. })${details ? `: ${details}` : ''}`,
  400. ),
  401. );
  402. });
  403. });
  404. }
  405. function notifyPackageManagerOutput(options: McodePackageManagerRunOptions, chunk: Buffer): void {
  406. try {
  407. options.onOutput?.(chunk.toString('utf8'));
  408. } catch {
  409. // Progress rendering must never change the package-manager result.
  410. }
  411. }
  412. export function resolveMcodePackageName(
  413. entryFile = process.argv[1],
  414. ): McodeNpmPackageName | undefined {
  415. return resolveMcodePackageIdentity(entryFile)?.packageName;
  416. }
  417. export function isInternalMcodePackageName(packageName: string | undefined): boolean {
  418. return packageName === mcodePackageName(MCODE_INTERNAL_SCOPE);
  419. }
  420. export function resolveInstalledMcodePackageVersion(
  421. entryFile = process.argv[1],
  422. ): string | undefined {
  423. return resolveMcodePackageIdentity(entryFile)?.version;
  424. }
  425. export function resolveMcodeNpmPrefixInstall(
  426. entryFile = process.argv[1],
  427. platform: NodeJS.Platform = process.platform,
  428. nodeExecutable = process.execPath,
  429. ): McodeNpmPrefixInstall | undefined {
  430. const identity = resolveMcodePackageIdentity(entryFile);
  431. if (!identity) return undefined;
  432. const platformPath = platform === 'win32' ? path.win32 : path.posix;
  433. const nodeModules = platformPath.dirname(platformPath.dirname(identity.packageRoot));
  434. if (platformPath.basename(nodeModules).toLocaleLowerCase() !== 'node_modules') return undefined;
  435. const nodeModulesParent = platformPath.dirname(nodeModules);
  436. const packagePrefix =
  437. platform !== 'win32' && platformPath.basename(nodeModulesParent) === 'lib'
  438. ? platformPath.dirname(nodeModulesParent)
  439. : nodeModulesParent;
  440. const receipt = findNpmPrefixReceipt(packagePrefix, identity.packageRoot, platform, platformPath);
  441. if (receipt) {
  442. if (receipt.packageName !== identity.packageName) return undefined;
  443. return receipt;
  444. }
  445. if (platformPath.basename(packagePrefix).toLocaleLowerCase() !== '.minimax-code')
  446. return undefined;
  447. const adjacentNpm = platformPath.join(
  448. platformPath.dirname(nodeExecutable),
  449. platform === 'win32' ? 'npm.cmd' : 'npm',
  450. );
  451. if (!existsSync(adjacentNpm)) return undefined;
  452. const distribution = resolveMcodeNpmDistribution(identity.packageName);
  453. return {
  454. executable: adjacentNpm,
  455. packageName: identity.packageName,
  456. prefix: packagePrefix,
  457. registry: distribution.registry,
  458. };
  459. }
  460. function resolveMcodePackageRoot(entryFile = process.argv[1]): string | undefined {
  461. return resolveMcodePackageIdentity(entryFile)?.packageRoot;
  462. }
  463. function resolveMcodePackageIdentity(
  464. entryFile: string | undefined,
  465. ): { packageName: McodeNpmPackageName; packageRoot: string; version?: string } | undefined {
  466. if (!entryFile) return undefined;
  467. let current: string;
  468. try {
  469. const resolved = realpathSync(entryFile);
  470. current = statSync(resolved).isDirectory() ? resolved : path.dirname(resolved);
  471. } catch {
  472. return undefined;
  473. }
  474. for (;;) {
  475. const manifestFile = path.join(current, 'package.json');
  476. if (existsSync(manifestFile)) {
  477. try {
  478. const manifest = JSON.parse(readFileSync(manifestFile, 'utf8')) as {
  479. name?: unknown;
  480. version?: unknown;
  481. };
  482. const packageName = parseMcodePackageName(manifest.name);
  483. if (packageName) {
  484. return {
  485. packageName,
  486. packageRoot: current,
  487. ...(typeof manifest.version === 'string' ? { version: manifest.version } : {}),
  488. };
  489. }
  490. } catch {
  491. return undefined;
  492. }
  493. }
  494. const parent = path.dirname(current);
  495. if (parent === current) return undefined;
  496. current = parent;
  497. }
  498. }
  499. function findNpmPrefixReceipt(
  500. packagePrefix: string,
  501. packageRoot: string,
  502. platform: NodeJS.Platform,
  503. platformPath: typeof path.posix | typeof path.win32,
  504. ): McodeNpmPrefixInstall | undefined {
  505. let candidate = packagePrefix;
  506. for (let depth = 0; depth < 3; depth += 1) {
  507. const receipt = readNpmPrefixReceipt(
  508. candidate,
  509. packagePrefix,
  510. packageRoot,
  511. platform,
  512. platformPath,
  513. );
  514. if (receipt) return receipt;
  515. const parent = platformPath.dirname(candidate);
  516. if (parent === candidate) break;
  517. candidate = parent;
  518. }
  519. return undefined;
  520. }
  521. function readNpmPrefixReceipt(
  522. prefix: string,
  523. packagePrefix: string,
  524. packageRoot: string,
  525. platform: NodeJS.Platform,
  526. platformPath: typeof path.posix | typeof path.win32,
  527. ): McodeNpmPrefixInstall | undefined {
  528. try {
  529. const raw = readFileSync(platformPath.join(prefix, 'install.json'), 'utf8').replace(
  530. /^\uFEFF/u,
  531. '',
  532. );
  533. const value = JSON.parse(raw) as {
  534. schemaVersion?: unknown;
  535. product?: unknown;
  536. updateOwner?: unknown;
  537. packageManager?: unknown;
  538. packageName?: unknown;
  539. registry?: unknown;
  540. distTag?: unknown;
  541. prefix?: unknown;
  542. npmExecutable?: unknown;
  543. layoutVersion?: unknown;
  544. releasesDirectory?: unknown;
  545. currentFile?: unknown;
  546. };
  547. const packageName = parseMcodePackageName(value.packageName);
  548. const legacyLayout = value.schemaVersion === 1 && value.layoutVersion === undefined;
  549. const versionedLayout =
  550. value.schemaVersion === 2 &&
  551. value.layoutVersion === 2 &&
  552. value.releasesDirectory === 'releases' &&
  553. value.currentFile === 'current';
  554. if (
  555. (!legacyLayout && !versionedLayout) ||
  556. value.product !== 'minimax-code' ||
  557. value.updateOwner !== 'npm-prefix' ||
  558. value.packageManager !== 'npm' ||
  559. !packageName ||
  560. typeof value.registry !== 'string' ||
  561. value.distTag !== 'latest' ||
  562. typeof value.prefix !== 'string' ||
  563. typeof value.npmExecutable !== 'string'
  564. ) {
  565. return undefined;
  566. }
  567. const distribution = resolveMcodeNpmDistribution(packageName, value.registry);
  568. if (
  569. normalizeResolvedPath(value.prefix, platform) !== normalizeResolvedPath(prefix, platform) ||
  570. new URL(value.registry).href !== distribution.registry ||
  571. !existsSync(value.npmExecutable)
  572. ) {
  573. return undefined;
  574. }
  575. if (
  576. legacyLayout &&
  577. normalizeResolvedPath(packagePrefix, platform) !== normalizeResolvedPath(prefix, platform)
  578. ) {
  579. return undefined;
  580. }
  581. if (versionedLayout) {
  582. const expectedReleasesRoot = platformPath.join(prefix, 'releases');
  583. const relativeRelease = platformPath.relative(expectedReleasesRoot, packagePrefix);
  584. if (
  585. !relativeRelease ||
  586. relativeRelease.startsWith('..') ||
  587. platformPath.isAbsolute(relativeRelease) ||
  588. relativeRelease.includes(platformPath.sep) ||
  589. !/^[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(relativeRelease) ||
  590. !isResolvedPathInside(packagePrefix, packageRoot, platformPath)
  591. ) {
  592. return undefined;
  593. }
  594. }
  595. return {
  596. executable: value.npmExecutable,
  597. packageName,
  598. prefix,
  599. registry: distribution.registry,
  600. };
  601. } catch {
  602. return undefined;
  603. }
  604. }
  605. function isResolvedPathInside(
  606. root: string,
  607. candidate: string,
  608. platformPath: typeof path.posix | typeof path.win32,
  609. ): boolean {
  610. const relative = platformPath.relative(
  611. platformPath.resolve(root),
  612. platformPath.resolve(candidate),
  613. );
  614. return relative !== '' && !relative.startsWith('..') && !platformPath.isAbsolute(relative);
  615. }
  616. function parseMcodePackageName(value: unknown): McodeNpmPackageName | undefined {
  617. if (value === mcodePackageName(MCODE_INTERNAL_SCOPE)) return value as McodeNpmPackageName;
  618. if (value === mcodePackageName(MCODE_PUBLIC_SCOPE)) return value as McodeNpmPackageName;
  619. return undefined;
  620. }
  621. function mcodePackageName(scope: string): McodeNpmPackageName {
  622. return `${scope}/${MCODE_PACKAGE_BASENAME}` as McodeNpmPackageName;
  623. }
  624. function mcodePackageNameFromPath(packageRoot: string): McodeNpmPackageName | undefined {
  625. const normalized = packageRoot.replaceAll('\\', '/');
  626. const segments = normalized.split('/');
  627. if (segments.at(-1) !== MCODE_PACKAGE_BASENAME) return undefined;
  628. return parseMcodePackageName(`${segments.at(-2)}/${MCODE_PACKAGE_BASENAME}`);
  629. }
  630. function normalizeResolvedPath(value: string, platform: NodeJS.Platform): string {
  631. let resolved: string;
  632. try {
  633. resolved = realpathSync(value);
  634. } catch {
  635. resolved = (platform === 'win32' ? path.win32 : path.posix).resolve(value);
  636. }
  637. return platform === 'win32' ? resolved.toLocaleLowerCase() : resolved;
  638. }
  639. function runText(
  640. command: string,
  641. args: readonly string[],
  642. environment: NodeJS.ProcessEnv = process.env,
  643. ): Promise<string> {
  644. return new Promise((resolve, reject) => {
  645. let settled = false;
  646. const child = spawn(command, [...args], {
  647. env: environment,
  648. shell: false,
  649. stdio: ['ignore', 'pipe', 'pipe'],
  650. windowsHide: true,
  651. });
  652. const stdout: Buffer[] = [];
  653. const stderr: Buffer[] = [];
  654. child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk));
  655. child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk));
  656. child.once('error', (error) => {
  657. if (settled) return;
  658. settled = true;
  659. reject(error);
  660. });
  661. child.once('exit', (code, signal) => {
  662. if (settled) return;
  663. settled = true;
  664. if (code === 0) {
  665. resolve(Buffer.concat(stdout).toString('utf8').trim());
  666. return;
  667. }
  668. const details = Buffer.concat([...stderr, ...stdout])
  669. .toString('utf8')
  670. .trim();
  671. reject(
  672. new Error(
  673. `${command} failed (${
  674. signal ? `signal ${signal}` : `exit ${String(code)}`
  675. })${details ? `: ${details}` : ''}`,
  676. ),
  677. );
  678. });
  679. });
  680. }