build-exe-for-python-sdk.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /**
  2. * Build the SDK runtime executables and Python node carrier. The fixed
  3. * `@yao-pkg/pkg --sea` route, deploy flags, and artifact layout are owned by
  4. * .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.
  5. * The staged closure is symlink-free, and whole-tree assets cover Cordis's
  6. * runtime imports that pkg cannot discover statically.
  7. */
  8. import { spawn } from 'node:child_process'
  9. import { existsSync, statSync } from 'node:fs'
  10. import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
  11. import { basename, dirname, join, resolve, sep } from 'node:path'
  12. import { parseArgs } from 'node:util'
  13. import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. /** The closure manifest whose dependencies define the executable. */
  16. const DEPLOY_ROOT_PACKAGE = 'dsh-sdk-python-runtime-closure'
  17. /** The closed-runtime app entry inside the deployed closure. */
  18. const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js'
  19. /** Stable Python-visible executable basename; rename with the later Python runtime migration. */
  20. const OUTPUT_BASENAME = 'dsh-jsonrpc-agent-pkg'
  21. /** Default Node major; SEA mode requires at least Node 22. */
  22. const DEFAULT_NODE_RANGE = 'node24'
  23. /** Pinned for reproducible builds. */
  24. const PKG_SPEC = '@yao-pkg/pkg@6.21.0'
  25. const OUT_DIR = 'dist-exe'
  26. /** Python package destination; created when absent. */
  27. const PYTHON_RUNTIME_DIR = 'python/sdk-runtime/src/deepseek_harness_runtime/runtime'
  28. /** The deployed closure doubles as the node-mode carrier. */
  29. const PYTHON_NODE_SUBDIR = 'node'
  30. /** Legacy deploy may hoist peer-specialized workspace packages back here. */
  31. const DEPLOY_SOURCE_NODE_MODULES = 'python/sdk-runtime/node_modules'
  32. /** Documentation excluded from the generated runtime directory. */
  33. const DEPLOY_ONLY_DOCS = ['README.md', 'README.zh.md', 'README.i18n.yaml']
  34. /**
  35. * Whole-tree assets cover Cordis's runtime bare-package imports, which pkg's
  36. * static analysis cannot see. Package manifests are explicit because bare-name
  37. * resolution depends on them.
  38. */
  39. const ASSET_GLOBS = [
  40. 'package.json',
  41. 'node_modules/**/*.js',
  42. 'node_modules/**/*.cjs',
  43. 'node_modules/**/*.mjs',
  44. 'node_modules/**/package.json',
  45. 'node_modules/**/*.json',
  46. 'node_modules/**/*.node',
  47. 'node_modules/**/*.wasm',
  48. ]
  49. const PLATFORMS = ['linux', 'macos'] as const
  50. const ARCHES = ['x64', 'arm64'] as const
  51. type Platform = (typeof PLATFORMS)[number]
  52. type Arch = (typeof ARCHES)[number]
  53. function isPlatform(value: string): value is Platform {
  54. return (PLATFORMS as readonly string[]).includes(value)
  55. }
  56. function isArch(value: string): value is Arch {
  57. return (ARCHES as readonly string[]).includes(value)
  58. }
  59. /**
  60. * A parsed pkg target triple, constructed from `--targets` or the host.
  61. */
  62. class Target {
  63. private constructor(
  64. /** pkg Node range (`node<major>`). */
  65. readonly nodeRange: string,
  66. /**
  67. * pkg platform tag. Windows is a documented non-goal
  68. * (.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md).
  69. */
  70. readonly platform: Platform,
  71. /** pkg CPU tag. */
  72. readonly arch: Arch,
  73. ) {}
  74. /** The pkg `--targets` spec string `<nodeRange>-<platform>-<arch>`. */
  75. get spec(): string {
  76. return `${this.nodeRange}-${this.platform}-${this.arch}`
  77. }
  78. /**
  79. * Parse one target spec, rejecting malformed triples and unsupported platform or architecture.
  80. * @param spec - the raw triple, e.g. `node24-linux-x64`.
  81. * @returns the parsed target.
  82. */
  83. static parse(spec: string): Target {
  84. const parts = spec.split('-')
  85. const [nodeRange, platform, arch] = parts
  86. if (parts.length !== 3 || nodeRange === undefined || platform === undefined || arch === undefined) {
  87. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)} must be <nodeRange>-<platform>-<arch>, e.g. node24-linux-x64.`)
  88. }
  89. if (!/^node\d+$/.test(nodeRange)) {
  90. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: node range must look like node24, got ${JSON.stringify(nodeRange)}.`)
  91. }
  92. if (!isPlatform(platform)) {
  93. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: platform must be one of ${PLATFORMS.join(', ')}, got ${JSON.stringify(platform)}.`)
  94. }
  95. if (!isArch(arch)) {
  96. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: arch must be one of ${ARCHES.join(', ')}, got ${JSON.stringify(arch)}.`)
  97. }
  98. return new Target(nodeRange, platform, arch)
  99. }
  100. /**
  101. * Resolve the host-platform default on Node 24.
  102. * @returns the host target; throws on an unsupported host platform or arch.
  103. */
  104. static host(): Target {
  105. const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : undefined
  106. if (platform === undefined) {
  107. throw new Error(`build-exe-for-python-sdk: unsupported host platform ${process.platform}; pass --targets explicitly.`)
  108. }
  109. const arch = process.arch === 'x64' || process.arch === 'arm64' ? process.arch : undefined
  110. if (arch === undefined) {
  111. throw new Error(`build-exe-for-python-sdk: unsupported host arch ${process.arch}; pass --targets explicitly.`)
  112. }
  113. return new Target(DEFAULT_NODE_RANGE, platform, arch)
  114. }
  115. }
  116. /**
  117. * Validated CLI configuration; construction owns help and parse-error exits.
  118. */
  119. class BuildCli {
  120. private constructor(
  121. /** Build targets; defaults to the host platform only. */
  122. readonly targets: readonly Target[],
  123. /** Skip step 1 (`pnpm run build`); lib/ artifacts must already exist. */
  124. readonly skipBuild: boolean,
  125. /** Print every command and config patch instead of executing. */
  126. readonly dryRun: boolean,
  127. ) {}
  128. /**
  129. * Parse argv. Help exits 0; malformed flags exit 1; invalid or colliding
  130. * targets throw.
  131. * @param argv - the raw arguments (`process.argv.slice(2)`).
  132. * @returns the parsed, validated configuration.
  133. */
  134. static parse(argv: string[]): BuildCli {
  135. let values: ReturnType<typeof BuildCli.parseRaw>
  136. try {
  137. values = BuildCli.parseRaw(argv)
  138. } catch (error) {
  139. console.error(`build-exe-for-python-sdk: ${error instanceof Error ? error.message : String(error)}\n`)
  140. console.error(BuildCli.usage())
  141. process.exit(1)
  142. }
  143. if (values.help) {
  144. console.log(BuildCli.usage())
  145. process.exit(0)
  146. }
  147. const targets = values.targets === undefined
  148. ? [Target.host()]
  149. : values.targets.split(',').map(part => part.trim()).filter(part => part !== '').map(spec => Target.parse(spec))
  150. if (targets.length === 0) throw new Error('build-exe-for-python-sdk: --targets is empty.')
  151. const seen = new Set<string>()
  152. for (const target of targets) {
  153. const key = `${target.platform}-${target.arch}`
  154. if (seen.has(key)) {
  155. throw new Error(`build-exe-for-python-sdk: duplicate platform-arch ${key} in --targets; canonical product names would collide.`)
  156. }
  157. seen.add(key)
  158. }
  159. return new BuildCli(targets, values['skip-build'], values['dry-run'])
  160. }
  161. private static parseRaw(argv: string[]) {
  162. return parseArgs({
  163. args: argv,
  164. options: {
  165. 'targets': { type: 'string' },
  166. 'skip-build': { type: 'boolean', default: false },
  167. 'dry-run': { type: 'boolean', default: false },
  168. 'help': { type: 'boolean', default: false },
  169. },
  170. }).values
  171. }
  172. private static usage(): string {
  173. return [
  174. 'Usage: pnpm exec tsx scripts/build-exe-for-python-sdk.ts [flags]',
  175. '',
  176. ' --targets=<t1,t2,...> pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64.',
  177. ' Default: the host platform only (on node24).',
  178. ' --skip-build skip `pnpm run build` (lib/ artifacts must already exist).',
  179. ' --dry-run print every command and config patch without executing.',
  180. ' --help print this help.',
  181. '',
  182. `Build route: ${PKG_SPEC} --sea; see .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.`,
  183. `Stages the node carrier in ${PYTHON_RUNTIME_DIR}/${PYTHON_NODE_SUBDIR} and writes executables to ${OUT_DIR}/.`,
  184. ].join('\n')
  185. }
  186. }
  187. function pnpmBin(): string {
  188. return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
  189. }
  190. /**
  191. * Render a command for logs and errors, quoting arguments with spaces.
  192. * @param command - the executable.
  193. * @param args - its arguments.
  194. * @returns the printable command line.
  195. */
  196. function formatCommand(command: string, args: string[]): string {
  197. return [command, ...args].map(part => (part.includes(' ') ? JSON.stringify(part) : part)).join(' ')
  198. }
  199. /**
  200. * Sequential build pipeline. Subprocesses inherit stdio and errors include
  201. * the command; dry runs print commands and filesystem changes.
  202. */
  203. class SingleExeBuild {
  204. /**
  205. * The cleared deploy target, pkg input, and Python node-mode carrier. The
  206. * checked-in default `cordis.yml` remains in its parent directory.
  207. */
  208. readonly staging = resolve(root, PYTHON_RUNTIME_DIR, PYTHON_NODE_SUBDIR)
  209. private readonly outDir = resolve(root, OUT_DIR)
  210. constructor(private readonly cli: BuildCli) {}
  211. /** Verify the closure before compiling or packaging. */
  212. async verifyClosure(): Promise<void> {
  213. await this.run('runtime dependency closure', pnpmBin(), ['run', 'verify-runtime-closure'])
  214. }
  215. /** Build all package artifacts unless `--skip-build` was passed. */
  216. async build(): Promise<void> {
  217. if (this.cli.skipBuild) {
  218. console.log('build-exe-for-python-sdk: skipping pnpm run build (--skip-build)')
  219. return
  220. }
  221. await this.run('build', pnpmBin(), ['run', 'build'])
  222. }
  223. /** Clear and deploy the runtime closure into the node carrier. */
  224. async deployStaging(): Promise<void> {
  225. if (this.staging === root || root.startsWith(this.staging + sep)) {
  226. throw new Error(`build-exe-for-python-sdk: refusing to clear staging dir ${this.staging}: it contains the repo root.`)
  227. }
  228. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${this.staging}`)
  229. else await rm(this.staging, { recursive: true, force: true })
  230. await this.run('deploy', pnpmBin(), [
  231. '--filter',
  232. DEPLOY_ROOT_PACKAGE,
  233. 'deploy',
  234. '--legacy',
  235. '--prod',
  236. '--config.node-linker=hoisted',
  237. '--config.auto-install-peers=false',
  238. '--config.link-workspace-packages=true',
  239. this.staging,
  240. ])
  241. await this.restoreLegacyHoists()
  242. await this.materializeStagedLinks()
  243. if (this.cli.dryRun) {
  244. for (const name of DEPLOY_ONLY_DOCS) console.log(`build-exe-for-python-sdk: [dry-run] rm -f ${join(this.staging, name)}`)
  245. } else {
  246. await Promise.all(DEPLOY_ONLY_DOCS.map(name => rm(join(this.staging, name), { force: true })))
  247. }
  248. }
  249. /**
  250. * Restore direct packages that pnpm's legacy hoister places beside the deploy
  251. * source instead of in the target. The runtime manifest supplies every peer,
  252. * so package-local node_modules trees are omitted to preserve one flat Cordis
  253. * instance and a symlink-free packaged payload.
  254. */
  255. private async restoreLegacyHoists(): Promise<void> {
  256. if (this.cli.dryRun) {
  257. console.log('build-exe-for-python-sdk: [dry-run] restore direct dependencies omitted by legacy deploy')
  258. return
  259. }
  260. const manifestPath = join(this.staging, 'package.json')
  261. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as {
  262. dependencies?: Record<string, string>
  263. }
  264. const sourceNodeModules = resolve(root, DEPLOY_SOURCE_NODE_MODULES)
  265. const restored: string[] = []
  266. for (const dependency of Object.keys(manifest.dependencies ?? {}).sort()) {
  267. const destination = join(this.staging, 'node_modules', dependency)
  268. if (existsSync(destination)) continue
  269. const source = join(sourceNodeModules, dependency)
  270. if (!existsSync(source)) {
  271. throw new Error(
  272. `build-exe-for-python-sdk: deployed dependency ${dependency} is absent from both ${destination} and ${source}.`,
  273. )
  274. }
  275. await mkdir(dirname(destination), { recursive: true })
  276. const nestedNodeModules = join(source, 'node_modules')
  277. await cp(source, destination, {
  278. recursive: true,
  279. dereference: true,
  280. filter: path => path !== nestedNodeModules && !path.startsWith(nestedNodeModules + sep),
  281. })
  282. restored.push(dependency)
  283. }
  284. const stillMissing = Object.keys(manifest.dependencies ?? {})
  285. .filter(dependency => !existsSync(join(this.staging, 'node_modules', dependency)))
  286. if (stillMissing.length > 0) {
  287. throw new Error(`build-exe-for-python-sdk: staged dependencies remain missing: ${stillMissing.join(', ')}.`)
  288. }
  289. if (restored.length > 0) {
  290. console.log(`build-exe-for-python-sdk: restored legacy deploy hoists: ${restored.join(', ')}`)
  291. }
  292. }
  293. /** Replace deploy-time package links with files and reject any remaining link. */
  294. private async materializeStagedLinks(): Promise<void> {
  295. if (this.cli.dryRun) {
  296. console.log('build-exe-for-python-sdk: [dry-run] materialize staged package links')
  297. return
  298. }
  299. const nodeModules = join(this.staging, 'node_modules')
  300. let remaining = await this.findSymlink(nodeModules)
  301. while (remaining !== undefined) {
  302. const segments = remaining.slice(nodeModules.length + 1).split(sep)
  303. const binIndex = segments.lastIndexOf('.bin')
  304. if (binIndex >= 0) {
  305. await rm(join(nodeModules, ...segments.slice(0, binIndex + 1)), { recursive: true, force: true })
  306. remaining = await this.findSymlink(nodeModules)
  307. continue
  308. }
  309. const destination = remaining
  310. const source = await realpath(destination)
  311. const nestedNodeModules = join(source, 'node_modules')
  312. await rm(destination, { recursive: true, force: true })
  313. await cp(source, destination, {
  314. recursive: true,
  315. dereference: true,
  316. filter: path => path !== nestedNodeModules && !path.startsWith(nestedNodeModules + sep),
  317. })
  318. remaining = await this.findSymlink(nodeModules)
  319. }
  320. }
  321. /** Return the first symbolic link below a directory, if one exists. */
  322. private async findSymlink(directory: string): Promise<string | undefined> {
  323. for (const entry of await readdir(directory, { withFileTypes: true })) {
  324. const path = join(directory, entry.name)
  325. const metadata = await lstat(path)
  326. if (metadata.isSymbolicLink()) return path
  327. if (metadata.isDirectory()) {
  328. const nested = await this.findSymlink(path)
  329. if (nested !== undefined) return nested
  330. }
  331. }
  332. return undefined
  333. }
  334. /** Add the executable entry and pkg assets to the staged manifest. */
  335. async injectPkgConfig(): Promise<void> {
  336. const patch = { bin: ENTRY_BIN, pkg: { assets: ASSET_GLOBS } }
  337. const manifestPath = join(this.staging, 'package.json')
  338. if (this.cli.dryRun) {
  339. console.log(`build-exe-for-python-sdk: [dry-run] patch ${manifestPath} with ${JSON.stringify(patch)}`)
  340. return
  341. }
  342. if (!existsSync(manifestPath)) {
  343. throw new Error(`build-exe-for-python-sdk: ${manifestPath} missing — pnpm deploy did not produce a staged package.`)
  344. }
  345. if (!existsSync(join(this.staging, ENTRY_BIN))) {
  346. throw new Error(`build-exe-for-python-sdk: ${join(this.staging, ENTRY_BIN)} missing — run without --skip-build so lib/ artifacts exist.`)
  347. }
  348. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
  349. await writeFile(manifestPath, `${JSON.stringify({ ...manifest, ...patch }, null, 2)}\n`)
  350. console.log(`build-exe-for-python-sdk: injected pkg config into ${manifestPath}`)
  351. }
  352. /**
  353. * Package one target; SEA mode accepts one target per invocation.
  354. * @param target - the pkg target triple to build.
  355. * @returns the executable and ripgrep sidecar paths, plus the macOS spawn helper path when required.
  356. */
  357. async pack(target: Target): Promise<string[]> {
  358. const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`)
  359. await this.prepareNativePty(target)
  360. if (!this.cli.dryRun) await mkdir(this.outDir, { recursive: true })
  361. await this.run(`pkg ${target.spec}`, pnpmBin(), [
  362. 'dlx',
  363. PKG_SPEC,
  364. this.staging,
  365. '--sea',
  366. '--targets',
  367. target.spec,
  368. '--output',
  369. product,
  370. ])
  371. if (!this.cli.dryRun && !existsSync(product)) {
  372. throw new Error(`build-exe-for-python-sdk: product ${product} is missing after the pkg run; inspect ${this.outDir}.`)
  373. }
  374. const ripgrep = await this.copyRipgrepSidecar(target, product)
  375. if (target.platform !== 'macos') return [product, ripgrep]
  376. const spawnHelper = `${product}-spawn-helper`
  377. const source = join(this.staging, 'node_modules', 'node-pty', 'prebuilds', `darwin-${target.arch}`, 'spawn-helper')
  378. if (this.cli.dryRun) {
  379. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${spawnHelper}`)
  380. } else {
  381. await copyFile(source, spawnHelper)
  382. await chmod(spawnHelper, 0o755)
  383. }
  384. return [product, ripgrep, spawnHelper]
  385. }
  386. /** Copy the target ripgrep binary beside the executable so Node can spawn it outside pkg's virtual filesystem. */
  387. private async copyRipgrepSidecar(target: Target, product: string): Promise<string> {
  388. const platform = target.platform === 'macos' ? 'darwin' : target.platform
  389. const source = join(
  390. this.staging,
  391. 'node_modules',
  392. '@vscode',
  393. `ripgrep-${platform}-${target.arch}`,
  394. 'bin',
  395. 'rg',
  396. )
  397. const destination = `${product}-rg`
  398. if (this.cli.dryRun) {
  399. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
  400. return destination
  401. }
  402. if (!existsSync(source)) {
  403. throw new Error(`build-exe-for-python-sdk: target ripgrep binary is missing at ${source}.`)
  404. }
  405. await copyFile(source, destination)
  406. await chmod(destination, 0o755)
  407. return destination
  408. }
  409. /**
  410. * Put the target node-pty addon in the staged closure. The release workflow
  411. * provides a manylinux build; ordinary installs use node-pty's target prebuild.
  412. * @param target - the pkg target whose native addon is being staged.
  413. */
  414. private async prepareNativePty(target: Target): Promise<void> {
  415. const stagedBuild = join(this.staging, 'node_modules', 'node-pty', 'build')
  416. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${stagedBuild}`)
  417. else await rm(stagedBuild, { recursive: true, force: true })
  418. if (target.platform !== 'linux') return
  419. const packageDirectory = join(
  420. root,
  421. 'packages',
  422. 'subprocess',
  423. 'subprocess-local',
  424. 'node_modules',
  425. 'node-pty',
  426. )
  427. const destination = join(stagedBuild, 'Release', 'pty.node')
  428. const source = resolveLinuxNodePtyAddon(packageDirectory, target.arch)
  429. if (this.cli.dryRun) {
  430. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
  431. return
  432. }
  433. const host = Target.host()
  434. if (target.platform !== host.platform || target.arch !== host.arch) {
  435. throw new Error(
  436. 'build-exe-for-python-sdk: build the Linux runtime on its target architecture; '
  437. + `target ${target.platform}-${target.arch} does not match host ${host.platform}-${host.arch}.`,
  438. )
  439. }
  440. await mkdir(dirname(destination), { recursive: true })
  441. await copyFile(source, destination)
  442. }
  443. /**
  444. * Print each product path and, outside dry-run mode, its size.
  445. * @param products - the product paths returned by {@link pack}.
  446. */
  447. printProducts(products: string[]): void {
  448. console.log(this.cli.dryRun ? 'build-exe-for-python-sdk: [dry-run] would produce:' : 'build-exe-for-python-sdk: products:')
  449. for (const path of products) {
  450. if (this.cli.dryRun) {
  451. console.log(` ${path}`)
  452. continue
  453. }
  454. const megabytes = statSync(path).size / (1024 * 1024)
  455. console.log(` ${path} (${megabytes.toFixed(1)} MB)`)
  456. }
  457. }
  458. /**
  459. * Copy each product into the Python runtime package. The deployed node
  460. * carrier is already in place, and `dist-exe/` retains upload copies.
  461. * @param products - the product paths returned by {@link pack}.
  462. */
  463. async syncToPythonRuntime(products: string[]): Promise<void> {
  464. const destDir = resolve(root, PYTHON_RUNTIME_DIR)
  465. if (this.cli.dryRun) {
  466. for (const path of products) {
  467. console.log(`build-exe-for-python-sdk: [dry-run] cp ${path} ${join(destDir, basename(path))}`)
  468. }
  469. return
  470. }
  471. await mkdir(destDir, { recursive: true })
  472. for (const path of products) {
  473. const destination = join(destDir, basename(path))
  474. await copyFile(path, destination)
  475. await chmod(destination, statSync(path).mode & 0o777)
  476. console.log(`build-exe-for-python-sdk: synced ${destination}`)
  477. }
  478. }
  479. /**
  480. * Run one subprocess with inherited stdio. Spawn and non-zero-exit errors
  481. * include the command; dry runs only print it.
  482. * @param label - the step name used in logs and error messages.
  483. * @param command - the executable.
  484. * @param args - its arguments.
  485. */
  486. private async run(label: string, command: string, args: string[]): Promise<void> {
  487. const printable = formatCommand(command, args)
  488. if (this.cli.dryRun) {
  489. console.log(`build-exe-for-python-sdk: [dry-run] ${printable}`)
  490. return
  491. }
  492. console.log(`build-exe-for-python-sdk: ${label}: ${printable}`)
  493. await new Promise<void>((resolvePromise, reject) => {
  494. const child = spawn(command, args, {
  495. cwd: root,
  496. stdio: 'inherit',
  497. // Artifact builds must not mutate or validate a developer's Git hooks.
  498. env: { ...process.env, CI: 'true' },
  499. })
  500. child.once('error', (error) => {
  501. reject(new Error(`build-exe-for-python-sdk: ${label} failed to spawn: ${error.message} (${printable})`))
  502. })
  503. child.once('exit', (code, signal) => {
  504. if (code === 0) {
  505. resolvePromise()
  506. return
  507. }
  508. const cause = code === null ? `signal ${signal ?? 'unknown'}` : `exit code ${code}`
  509. reject(new Error(`build-exe-for-python-sdk: ${label} failed (${cause}): ${printable}`))
  510. })
  511. })
  512. }
  513. }
  514. async function main(): Promise<void> {
  515. const cli = BuildCli.parse(process.argv.slice(2))
  516. const pipeline = new SingleExeBuild(cli)
  517. console.log(`build-exe-for-python-sdk: targets: ${cli.targets.map(target => target.spec).join(', ')}`)
  518. console.log(`build-exe-for-python-sdk: staging: ${pipeline.staging}`)
  519. await pipeline.verifyClosure()
  520. await pipeline.build()
  521. await pipeline.deployStaging()
  522. await pipeline.injectPkgConfig()
  523. const products: string[] = []
  524. for (const target of cli.targets) products.push(...await pipeline.pack(target))
  525. pipeline.printProducts(products)
  526. await pipeline.syncToPythonRuntime(products)
  527. }
  528. await main()