package-target.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /** Build one release target with matching Electron and dsh architecture. */
  2. import { spawn } from 'node:child_process'
  3. import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
  4. import { parseArgs } from 'node:util'
  5. import { join, resolve } from 'node:path'
  6. import {
  7. desktopBuildRecordFilename,
  8. resolveDesktopAutoUpdateConfig,
  9. } from './desktop-auto-update-environment.mjs'
  10. import { desktopTargetBuildPaths } from './desktop-build-paths.mjs'
  11. import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts'
  12. import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs'
  13. const APP_ROOT = resolve(import.meta.dirname, '..')
  14. const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..')
  15. const WINDOWS_SIGNING_ENV_PREFIX = 'DSH_DESKTOP_WINDOWS_'
  16. const WINDOWS_SIGNING_ENV_NAMES = [
  17. 'DSH_DESKTOP_WINDOWS_CER_FILE',
  18. 'DSH_DESKTOP_WINDOWS_KEY_CONTAINER',
  19. 'DSH_DESKTOP_WINDOWS_SIGNTOOL',
  20. 'DSH_DESKTOP_WINDOWS_TOKEN_PIN',
  21. ] as const
  22. const DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES = new Set([
  23. 'DOWNLOAD_TEST_COS_SECRET_ID',
  24. 'DOWNLOAD_TEST_COS_SECRET_KEY',
  25. 'DOWNLOAD_PROD_COS_SECRET_ID',
  26. 'DOWNLOAD_PROD_COS_SECRET_KEY',
  27. ])
  28. /** Fixed platform and architecture identifiers exposed by package scripts. */
  29. export type DesktopPackageTargetName = 'mac-arm64' | 'mac-x64' | 'win-x64'
  30. /** One supported release target and its electron-builder selectors. */
  31. export interface DesktopPackageTarget {
  32. readonly name: DesktopPackageTargetName
  33. readonly platform: 'darwin' | 'win32'
  34. readonly arch: 'arm64' | 'x64'
  35. readonly builderPlatform: '--mac' | '--win'
  36. readonly builderArch: '--arm64' | '--x64'
  37. }
  38. const TARGETS: Record<DesktopPackageTargetName, DesktopPackageTarget> = {
  39. 'mac-arm64': {
  40. name: 'mac-arm64',
  41. platform: 'darwin',
  42. arch: 'arm64',
  43. builderPlatform: '--mac',
  44. builderArch: '--arm64',
  45. },
  46. 'mac-x64': {
  47. name: 'mac-x64',
  48. platform: 'darwin',
  49. arch: 'x64',
  50. builderPlatform: '--mac',
  51. builderArch: '--x64',
  52. },
  53. 'win-x64': {
  54. name: 'win-x64',
  55. platform: 'win32',
  56. arch: 'x64',
  57. builderPlatform: '--win',
  58. builderArch: '--x64',
  59. },
  60. }
  61. /**
  62. * Remove Windows signing configuration from package preparation subprocesses.
  63. * @param environment - Packaging command environment.
  64. * @returns A copy without Windows signing fields.
  65. */
  66. export function withoutWindowsSigningEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
  67. return Object.fromEntries(Object.entries(environment)
  68. .filter(([name]) => !name.startsWith(WINDOWS_SIGNING_ENV_PREFIX)))
  69. }
  70. /**
  71. * Select signing and NSIS-compatible archive filters for electron-builder.
  72. * @param environment - Target packaging environment.
  73. * @param unsigned - Whether to create a local unsigned Windows artifact.
  74. * @returns Packaging environment without certificate inputs for unsigned builds.
  75. */
  76. export function desktopElectronBuilderEnvironment(environment: NodeJS.ProcessEnv, unsigned: boolean): NodeJS.ProcessEnv {
  77. const selected: NodeJS.ProcessEnv = { ...environment, DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0' }
  78. // The bundled NSIS decoder cannot extract 7-Zip's automatic ARM64-filtered entries.
  79. if (environment.DSH_DESKTOP_TARGET_PLATFORM === 'win32') selected.ELECTRON_BUILDER_7Z_FILTER = 'BCJ'
  80. if (!unsigned) return selected
  81. return {
  82. ...Object.fromEntries(Object.entries(withoutWindowsSigningEnvironment(selected))
  83. .filter(([name]) => !/^(?:WIN_)?CSC_/iu.test(name))),
  84. CSC_IDENTITY_AUTO_DISCOVERY: 'false',
  85. DSH_DESKTOP_UNSIGNED: '1',
  86. }
  87. }
  88. /**
  89. * Remove upload-only COS credentials from every packaging subprocess.
  90. * @param environment - Packaging command environment.
  91. * @returns A copy without Desktop upload credentials.
  92. */
  93. export function withoutDesktopUploadCredentials(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
  94. return Object.fromEntries(Object.entries(environment)
  95. .filter(([name]) => !DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES.has(name)))
  96. }
  97. function isTargetName(value: string): value is DesktopPackageTargetName {
  98. return Object.hasOwn(TARGETS, value)
  99. }
  100. function packageVersion(path: string, label: string): string {
  101. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown }
  102. if (typeof manifest.version !== 'string' || manifest.version === '') {
  103. throw new Error(`desktop package: ${label} has no version`)
  104. }
  105. return manifest.version
  106. }
  107. function writeReleaseRecord(
  108. target: DesktopPackageTarget,
  109. environment: NodeJS.ProcessEnv,
  110. artifactsRoot: string,
  111. ): void {
  112. const desktopVersion = packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')
  113. const dshVersion = packageVersion(join(REPOSITORY_ROOT, 'package.json'), 'dsh package')
  114. if (desktopVersion !== dshVersion) {
  115. throw new Error(`desktop package: desktop version ${desktopVersion} does not match dsh version ${dshVersion}`)
  116. }
  117. const update = resolveDesktopAutoUpdateConfig(environment, target.platform, target.arch)
  118. const recordPath = join(artifactsRoot, desktopBuildRecordFilename(target.name))
  119. const temporaryPath = `${recordPath}.tmp`
  120. writeFileSync(temporaryPath, `${JSON.stringify({
  121. schemaVersion: 1,
  122. target: target.name,
  123. version: dshVersion,
  124. environment: update.environment,
  125. publicUrl: update.publicUrl,
  126. }, null, 2)}\n`)
  127. renameSync(temporaryPath, recordPath)
  128. }
  129. /**
  130. * Resolve a named release target and reject hosts that cannot execute its packaged runtime.
  131. * @param name - One of the fixed Desktop release target names.
  132. * @param hostPlatform - Build-host Node.js platform.
  133. * @param hostArch - Build-host Node.js architecture.
  134. * @returns The target selectors shared by runtime preparation and electron-builder.
  135. */
  136. export function resolveDesktopPackageTarget(
  137. name: string,
  138. hostPlatform: NodeJS.Platform = process.platform,
  139. hostArch: string = process.arch,
  140. ): DesktopPackageTarget {
  141. if (!isTargetName(name)) {
  142. throw new Error(`desktop package: unsupported target ${JSON.stringify(name)}; expected ${Object.keys(TARGETS).join(', ')}`)
  143. }
  144. const target = TARGETS[name]
  145. if (target.platform === 'win32' && (hostPlatform !== 'win32' || hostArch !== 'x64')) {
  146. throw new Error('desktop package: win-x64 requires a Windows x64 build host')
  147. }
  148. if (target.platform === 'darwin' && hostPlatform !== 'darwin') {
  149. throw new Error(`desktop package: ${name} requires a macOS build host`)
  150. }
  151. if (name === 'mac-arm64' && hostArch !== 'arm64') {
  152. throw new Error('desktop package: mac-arm64 requires an Apple Silicon build host')
  153. }
  154. if (name === 'mac-x64' && hostArch !== 'arm64' && hostArch !== 'x64') {
  155. throw new Error('desktop package: mac-x64 requires an Intel Mac or Apple Silicon with Rosetta')
  156. }
  157. return target
  158. }
  159. interface DesktopPackageInvocation {
  160. readonly target: DesktopPackageTarget
  161. readonly directory: boolean
  162. readonly prepareOnly: boolean
  163. readonly unsigned: boolean
  164. readonly check: boolean
  165. }
  166. function hostTargetName(platform: NodeJS.Platform, arch: string): DesktopPackageTargetName {
  167. const name = `${platform === 'darwin' ? 'mac' : platform === 'win32' ? 'win' : platform}-${arch}`
  168. if (!isTargetName(name)) throw new Error(`desktop package: unsupported build host ${platform}-${arch}`)
  169. return name
  170. }
  171. /**
  172. * Parse the fixed-target packaging command line.
  173. * @param argv - Arguments after the script entry point.
  174. * @param hostPlatform - Build-host Node.js platform.
  175. * @param hostArch - Build-host Node.js architecture.
  176. * @returns The validated target and whether to emit an unpacked directory.
  177. */
  178. export function parseDesktopPackageInvocation(
  179. argv: readonly string[],
  180. hostPlatform: NodeJS.Platform = process.platform,
  181. hostArch: string = process.arch,
  182. ): DesktopPackageInvocation {
  183. const { values, positionals } = parseArgs({
  184. args: [...argv],
  185. allowPositionals: true,
  186. options: {
  187. dir: { type: 'boolean', default: false },
  188. 'prepare-only': { type: 'boolean', default: false },
  189. unsigned: { type: 'boolean', default: false },
  190. check: { type: 'boolean', default: false },
  191. },
  192. })
  193. if (positionals.length > 1) throw new Error('desktop package: expected at most one target')
  194. const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch)
  195. if (values.unsigned && name !== 'win-x64') throw new Error('desktop package: --unsigned requires win-x64')
  196. if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only')
  197. return {
  198. target: resolveDesktopPackageTarget(name, hostPlatform, hostArch),
  199. directory: values.dir,
  200. prepareOnly: values['prepare-only'],
  201. unsigned: values.unsigned,
  202. check: values.check,
  203. }
  204. }
  205. /**
  206. * Build the electron-builder command arguments for one validated target.
  207. * @param target - Supported release target.
  208. * @param directory - Whether to stop at an unpacked application directory.
  209. * @param artifact - Optional single artifact built from an existing signed application.
  210. * @returns Arguments that keep publishing under the separate validated upload command.
  211. */
  212. export function desktopElectronBuilderArguments(
  213. target: DesktopPackageTarget,
  214. directory: boolean,
  215. artifact?: DesktopPrepackagedArtifact,
  216. ): readonly string[] {
  217. return [
  218. 'exec',
  219. 'electron-builder',
  220. '--config',
  221. 'electron-builder.config.mjs',
  222. target.builderPlatform,
  223. ...(artifact === undefined ? [] : [artifact.format]),
  224. target.builderArch,
  225. '--publish',
  226. 'never',
  227. ...(directory ? ['--dir'] : []),
  228. ...(artifact === undefined ? [] : [
  229. ...(target.platform === 'darwin' ? ['--config.mac.notarize=false'] : []),
  230. '--prepackaged', artifact.appPath,
  231. '--config.directories.output', artifact.output,
  232. ]),
  233. ]
  234. }
  235. function runPnpm(
  236. args: readonly string[],
  237. env: NodeJS.ProcessEnv = process.env,
  238. cwd: string = APP_ROOT,
  239. ): Promise<void> {
  240. const pnpmEntry = process.env.npm_execpath
  241. if (pnpmEntry === undefined || pnpmEntry === '') {
  242. throw new Error('desktop package: invoke this script through a pnpm package command')
  243. }
  244. return new Promise((resolvePromise, reject) => {
  245. const child = spawn(process.execPath, [pnpmEntry, ...args], {
  246. cwd,
  247. env,
  248. stdio: 'inherit',
  249. })
  250. child.once('error', reject)
  251. child.once('close', (code, signal) => {
  252. if (code === 0) resolvePromise()
  253. else reject(new Error(`desktop package: pnpm ${args.join(' ')} exited with ${String(code ?? signal)}`))
  254. })
  255. })
  256. }
  257. async function main(): Promise<void> {
  258. const invocation = parseDesktopPackageInvocation(process.argv.slice(2))
  259. const { target } = invocation
  260. const environment = loadDesktopPackageEnvironment(target.platform)
  261. validateDesktopPackageEnvironment(environment, target, invocation)
  262. if (invocation.check) {
  263. process.stdout.write(`desktop package: ${target.name} local configuration valid; signing and notarization were not attempted\n`)
  264. return
  265. }
  266. const buildPaths = desktopTargetBuildPaths(target.name)
  267. const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name))
  268. if (!invocation.prepareOnly && !invocation.unsigned) {
  269. rmSync(releaseRecordPath, { force: true })
  270. rmSync(`${releaseRecordPath}.tmp`, { force: true })
  271. }
  272. const buildEnv = withoutWindowsSigningEnvironment(withoutDesktopUploadCredentials(environment))
  273. const targetEnv: NodeJS.ProcessEnv = {
  274. ...buildEnv,
  275. DSH_DESKTOP_TARGET_PLATFORM: target.platform,
  276. DSH_DESKTOP_TARGET_ARCH: target.arch,
  277. }
  278. const electronBuilderEnv = desktopElectronBuilderEnvironment(targetEnv, invocation.unsigned)
  279. for (const name of WINDOWS_SIGNING_ENV_NAMES) {
  280. if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name]
  281. }
  282. await runPnpm(['run', 'build:official'], buildEnv, REPOSITORY_ROOT)
  283. await runPnpm(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT)
  284. await runPnpm([
  285. '--dir',
  286. 'apps/desktop-host',
  287. 'pack',
  288. '--pack-destination',
  289. buildPaths.packedDsh,
  290. ], buildEnv, REPOSITORY_ROOT)
  291. await runPnpm(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor], buildEnv, REPOSITORY_ROOT)
  292. rmSync(buildPaths.packedLandlock, { recursive: true, force: true })
  293. mkdirSync(buildPaths.packedLandlock, { recursive: true })
  294. await runPnpm(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT)
  295. await runPnpm([
  296. '--dir',
  297. 'native/system/packages/entry',
  298. 'pack',
  299. '--pack-destination',
  300. buildPaths.packedLandlock,
  301. ], buildEnv, REPOSITORY_ROOT)
  302. await runPnpm(['run', 'prepare:runtime'], targetEnv)
  303. await runPnpm(['run', 'prepare:packages'], targetEnv)
  304. await runPnpm(['run', 'prepare:dsh'], targetEnv)
  305. if (invocation.prepareOnly) return
  306. if (target.platform === 'darwin' && !invocation.directory) {
  307. await runPnpm([
  308. ...desktopElectronBuilderArguments(target, true),
  309. '--config.mac.notarize=false',
  310. ], electronBuilderEnv)
  311. await packageMacOSArtifacts({
  312. arch: target.arch,
  313. version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'),
  314. artifactsRoot: buildPaths.artifacts,
  315. environment: electronBuilderEnv,
  316. }, artifact => runPnpm(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv))
  317. } else {
  318. await runPnpm(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)
  319. }
  320. if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)
  321. }
  322. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main()