build-common.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Modified by MiniMax for MCode Sandbox Runtime.
  2. import { spawnSync } from 'node:child_process'
  3. import { mkdirSync } from 'node:fs'
  4. import { dirname, join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. const nodeArchToDir: Record<string, string> = { x64: 'x64', arm64: 'arm64' }
  7. /**
  8. * Common preamble for `vendor/<helper>/build.ts` scripts: platform
  9. * guard, arch resolution, derive `SRC` (sibling source dir under
  10. * `vendor/`) and `OUT` (per-arch output dir next to the build script),
  11. * and create `OUT`. Exits the process on a guard failure.
  12. */
  13. export function setup(opts: {
  14. /** `import.meta.url` of the calling build script. */
  15. importMetaUrl: string
  16. /** Only run on this platform; bail with a clear error otherwise. */
  17. requirePlatform: NodeJS.Platform
  18. /** Sibling directory under `vendor/` holding the source to build. */
  19. srcDirName: string
  20. /** Permit an explicit SRT_BUILD_ARCH cross-build on another host platform. */
  21. allowCrossPlatform?: boolean
  22. }): { SRC: string; OUT: string; arch: string } {
  23. if (
  24. process.platform !== opts.requirePlatform &&
  25. !(opts.allowCrossPlatform && process.env.SRT_BUILD_ARCH)
  26. ) {
  27. console.error(
  28. `${opts.srcDirName} build: ${opts.requirePlatform} only ` +
  29. `(running on ${process.platform})`,
  30. )
  31. process.exit(1)
  32. }
  33. const arch = process.env.SRT_BUILD_ARCH ?? nodeArchToDir[process.arch]
  34. if (!arch || !Object.values(nodeArchToDir).includes(arch)) {
  35. console.error(`${opts.srcDirName} build: unsupported arch ${process.arch}`)
  36. process.exit(1)
  37. }
  38. const here = dirname(fileURLToPath(opts.importMetaUrl))
  39. const SRC = join(here, '..', opts.srcDirName)
  40. const OUT = join(here, arch)
  41. mkdirSync(OUT, { recursive: true })
  42. return { SRC, OUT, arch }
  43. }
  44. /**
  45. * Spawn `argv` synchronously with inherited stdio. Exits the process
  46. * on spawn failure (`r.error`) or non-zero exit / signal termination.
  47. */
  48. export function run(argv: string[]): void {
  49. const [cmd, ...args] = argv
  50. const r = spawnSync(cmd, args, { stdio: 'inherit' })
  51. if (r.error) {
  52. console.error(`${argv.join(' ')} failed to spawn: ${r.error.message}`)
  53. process.exit(1)
  54. }
  55. if (r.status !== 0) {
  56. console.error(`${argv.join(' ')} exited ${r.status ?? r.signal}`)
  57. process.exit(1)
  58. }
  59. }