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

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