client-build-environment.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import { createHash } from 'node:crypto'
  2. import { execFileSync, spawnSync } from 'node:child_process'
  3. import {
  4. existsSync,
  5. globSync,
  6. mkdirSync,
  7. readFileSync,
  8. statSync,
  9. writeFileSync,
  10. } from 'node:fs'
  11. import { dirname, resolve } from 'node:path'
  12. /** Prefix reserved for build-time values that may be embedded in browser artifacts. */
  13. const CLIENT_BUILD_ENV_PREFIX = 'DSH_CLIENT_'
  14. /** Non-public selector used by build orchestration to request a named client profile. */
  15. export const CLIENT_BUILD_PROFILE_SELECTOR = 'DSH_BUILD_CLIENT_PROFILE'
  16. /** Public client environment required by official DSH artifacts. */
  17. const OFFICIAL_CLIENT_BUILD_ENVIRONMENT = {
  18. DSH_CLIENT_BUILD_PROFILE: 'official',
  19. DSH_CLIENT_TITLE: 'DeepSeek Harness',
  20. } as const
  21. /** Public variable carrying the source commit embedded in client artifacts. */
  22. const CLIENT_COMMIT_HASH_VARIABLE = 'DSH_CLIENT_COMMIT_HASH'
  23. /** Public variable carrying the repository package version embedded in client artifacts. */
  24. const CLIENT_VERSION_VARIABLE = 'DSH_CLIENT_VERSION'
  25. /** Repository-relative path of the complete client build record. */
  26. export const CLIENT_BUILD_RECORD_PATH = '.dsh-build/client-build-environment.json'
  27. const CLIENT_BUILD_RECORD_FORMAT = 1
  28. const CLIENT_ARTIFACT_PATTERNS = [
  29. 'apps/web/dist/**/*',
  30. 'packages/*/*/lib/client.js',
  31. 'packages/*/*/lib/client.js.map',
  32. 'packages/*/*/lib/client.*.js',
  33. 'packages/*/*/lib/client.*.js.map',
  34. ] as const
  35. /** Public values embedded in one set of client artifacts. */
  36. export type ClientBuildEnvironment = Readonly<Record<string, string>>
  37. /**
  38. * Resolve the short source commit used by browser build metadata.
  39. * @param root - repository root used when no explicit value is supplied.
  40. * @param environment - environment that may already carry a commit value.
  41. * @returns lowercase 7-character Git commit prefix.
  42. */
  43. export function repositoryCommitHash(root: string, environment: NodeJS.ProcessEnv = process.env): string {
  44. const explicit = environment[CLIENT_COMMIT_HASH_VARIABLE]
  45. const value = explicit ?? execFileSync('git', ['rev-parse', 'HEAD'], {
  46. cwd: root,
  47. encoding: 'utf8',
  48. stdio: ['ignore', 'pipe', 'ignore'],
  49. }).trim()
  50. if (!/^[0-9a-f]{7,40}$/iu.test(value)) {
  51. throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} must be a Git commit hash; got ${JSON.stringify(value)}`)
  52. }
  53. return value.slice(0, 7).toLowerCase()
  54. }
  55. /**
  56. * Resolve the repository package version used by browser build metadata.
  57. * @param root - repository root containing the authoritative package.json.
  58. * @returns the repository's semver-compatible package version.
  59. */
  60. export function repositoryVersion(root: string): string {
  61. const path = resolve(root, 'package.json')
  62. let manifest: unknown
  63. try {
  64. manifest = JSON.parse(readFileSync(path, 'utf8'))
  65. } catch (error) {
  66. const detail = error instanceof Error ? error.message : String(error)
  67. throw new Error(`cannot read repository version from ${path}: ${detail}`)
  68. }
  69. if (!isObject(manifest) || typeof manifest.version !== 'string'
  70. || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.version)) {
  71. throw new Error(`repository package.json has an invalid version ${JSON.stringify(isObject(manifest) ? manifest.version : undefined)}`)
  72. }
  73. return manifest.version
  74. }
  75. /**
  76. * Read whether Git reports any staged, unstaged, untracked, or submodule change.
  77. * @param root - repository root whose worktree is inspected.
  78. * @returns true or false inside a Git worktree; undefined without Git metadata.
  79. */
  80. export function repositoryGitDirty(root: string): boolean | undefined {
  81. const probe = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], {
  82. cwd: root,
  83. encoding: 'utf8',
  84. stdio: ['ignore', 'pipe', 'ignore'],
  85. })
  86. if (probe.error !== undefined || probe.status !== 0 || probe.stdout.trim() !== 'true') return undefined
  87. const status = spawnSync('git', ['status', '--porcelain=v1', '--untracked-files=normal'], {
  88. cwd: root,
  89. encoding: 'utf8',
  90. stdio: ['ignore', 'pipe', 'pipe'],
  91. })
  92. if (status.error !== undefined) throw status.error
  93. if (status.status !== 0) {
  94. throw new Error(`git status failed in ${root}: ${status.stderr.trim() || String(status.status)}`)
  95. }
  96. return status.stdout !== ''
  97. }
  98. /**
  99. * Resolve the public environment for a complete default build from one checkout.
  100. * Repository-owned metadata replaces inherited values; other public values pass through.
  101. * @param root - repository root supplying version and Git metadata.
  102. * @param environment - caller environment supplying optional commit and public extensions.
  103. * @returns complete public client environment for the default build.
  104. */
  105. export function repositoryClientBuildEnvironment(
  106. root: string,
  107. environment: NodeJS.ProcessEnv = process.env,
  108. ): ClientBuildEnvironment {
  109. const inherited = { ...clientBuildEnvironment(environment) }
  110. delete inherited.DSH_CLIENT_COMMIT_HASH
  111. delete inherited.DSH_CLIENT_GIT_DIRTY
  112. delete inherited.DSH_CLIENT_VERSION
  113. const dirty = repositoryGitDirty(root)
  114. return {
  115. ...inherited,
  116. DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment),
  117. ...(dirty === true ? { DSH_CLIENT_GIT_DIRTY: 'true' } : {}),
  118. DSH_CLIENT_VERSION: repositoryVersion(root),
  119. }
  120. }
  121. /**
  122. * Resolve the exact public values required by an official build at one commit.
  123. * @param root - repository root whose HEAD must match the built source.
  124. * @param environment - optional explicit commit source for non-Git build environments.
  125. * @returns complete official client environment.
  126. */
  127. export function officialClientBuildEnvironment(
  128. root: string,
  129. environment: NodeJS.ProcessEnv = process.env,
  130. ): Readonly<Record<`DSH_CLIENT_${string}`, string>> {
  131. return {
  132. DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment),
  133. DSH_CLIENT_VERSION: repositoryVersion(root),
  134. ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT,
  135. }
  136. }
  137. /** Digest of every client artifact produced by the complete root build. */
  138. interface ClientArtifactDigest {
  139. /** Number of files covered by the digest. */
  140. readonly fileCount: number
  141. /** Lowercase SHA-256 digest of sorted paths and file contents. */
  142. readonly sha256: string
  143. }
  144. /** Durable description of one complete root client build. */
  145. export interface ClientBuildRecord {
  146. /** Record schema version. */
  147. readonly formatVersion: number
  148. /** Exact public environment embedded by Vite and tsdown. */
  149. readonly environment: ClientBuildEnvironment
  150. /** Digest that binds the environment to the current artifacts. */
  151. readonly artifacts: ClientArtifactDigest
  152. }
  153. /**
  154. * Collect the public client environment in deterministic key order.
  155. * @param environment - environment inherited by the build process.
  156. * @returns defined `DSH_CLIENT_*` values only.
  157. */
  158. function clientBuildEnvironment(environment: NodeJS.ProcessEnv): ClientBuildEnvironment {
  159. return Object.fromEntries(Object.entries(environment)
  160. .filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
  161. .sort(([left], [right]) => left.localeCompare(right))) as Record<string, string>
  162. }
  163. /**
  164. * Resolve the exact public environment selected for a complete client build.
  165. * @param environment - parent process environment.
  166. * @param profile - explicit profile, or the non-public selector when omitted.
  167. * @returns the inherited public values when no profile is selected, otherwise the named profile.
  168. */
  169. export function resolveClientBuildEnvironment(
  170. environment: NodeJS.ProcessEnv,
  171. profile: string | undefined = environment[CLIENT_BUILD_PROFILE_SELECTOR],
  172. ): ClientBuildEnvironment {
  173. if (profile === undefined) return clientBuildEnvironment(environment)
  174. if (profile === 'official') {
  175. const commitHash = environment[CLIENT_COMMIT_HASH_VARIABLE]
  176. const version = environment[CLIENT_VERSION_VARIABLE]
  177. if (commitHash === undefined) {
  178. throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} is required for the official client build profile`)
  179. }
  180. if (version === undefined) {
  181. throw new Error(`${CLIENT_VERSION_VARIABLE} is required for the official client build profile`)
  182. }
  183. return {
  184. DSH_CLIENT_COMMIT_HASH: commitHash,
  185. DSH_CLIENT_VERSION: version,
  186. ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT,
  187. }
  188. }
  189. throw new Error(`unknown client build profile ${JSON.stringify(profile)}; expected "official"`)
  190. }
  191. /**
  192. * Construct a subprocess environment containing exactly the selected public values.
  193. * @param environment - parent process environment.
  194. * @param clientEnvironment - complete public environment selected for the build.
  195. * @returns the parent environment with selectors and inherited public values replaced.
  196. */
  197. export function clientBuildProcessEnvironment(
  198. environment: NodeJS.ProcessEnv,
  199. clientEnvironment: ClientBuildEnvironment,
  200. ): NodeJS.ProcessEnv {
  201. const child: NodeJS.ProcessEnv = {}
  202. for (const [name, value] of Object.entries(environment)) {
  203. if (name === CLIENT_BUILD_PROFILE_SELECTOR || name.startsWith(CLIENT_BUILD_ENV_PREFIX)) continue
  204. child[name] = value
  205. }
  206. return { ...child, ...clientEnvironment }
  207. }
  208. /**
  209. * Require the public client environment to match an artifact profile exactly.
  210. *
  211. * An exact key set matters because every prefixed value is eligible for
  212. * inlining: an unexpected variable can change published bytes just as surely
  213. * as a missing or incorrect required value.
  214. *
  215. * @param environment - public environment from a build process or build record.
  216. * @param expected - complete public client environment for the artifact profile.
  217. */
  218. export function assertClientBuildEnvironment(
  219. environment: Readonly<Record<string, string | undefined>>,
  220. expected: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
  221. ): void {
  222. const actual = Object.fromEntries(Object.entries(environment)
  223. .filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
  224. .sort(([left], [right]) => left.localeCompare(right)))
  225. const normalizedExpected = Object.fromEntries(Object.entries(expected)
  226. .sort(([left], [right]) => left.localeCompare(right)))
  227. if (JSON.stringify(actual) === JSON.stringify(normalizedExpected)) return
  228. const names = [...new Set([...Object.keys(actual), ...Object.keys(normalizedExpected)])].sort()
  229. const differences = names.filter(name => actual[name] !== normalizedExpected[name])
  230. throw new Error(`client build environment differs from the required artifact profile: ${differences.join(', ')}`)
  231. }
  232. /**
  233. * Create bundler substitutions for public client build environment variables.
  234. *
  235. * The empty `process.env` fallback makes an unset static property read
  236. * evaluate to `undefined` without providing a browser `process` global.
  237. * Exact substitutions remain longer matches than that fallback. Dynamic
  238. * property reads and enumeration deliberately observe the empty object.
  239. *
  240. * @param environment - environment inherited by the build process.
  241. * @returns deterministic Vite/tsdown `define` expressions.
  242. */
  243. export function clientBuildEnvironmentDefines(
  244. environment: NodeJS.ProcessEnv,
  245. ): Record<string, string> {
  246. const defines: Record<string, string> = { 'process.env': '{}' }
  247. for (const [name, value] of Object.entries(clientBuildEnvironment(environment))) {
  248. defines[`process.env.${name}`] = JSON.stringify(value)
  249. }
  250. return defines
  251. }
  252. /**
  253. * Write the build record after a complete root build succeeds.
  254. * @param root - repository root containing the generated artifacts.
  255. * @param environment - exact public environment supplied to both bundlers.
  256. * @returns the record written to disk.
  257. */
  258. export function writeClientBuildRecord(
  259. root: string,
  260. environment: ClientBuildEnvironment,
  261. ): ClientBuildRecord {
  262. const record: ClientBuildRecord = {
  263. formatVersion: CLIENT_BUILD_RECORD_FORMAT,
  264. environment: clientBuildEnvironment(environment),
  265. artifacts: clientArtifactDigest(root),
  266. }
  267. const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
  268. mkdirSync(dirname(path), { recursive: true })
  269. writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`)
  270. return record
  271. }
  272. /**
  273. * Read a complete build record and prove it still describes the current artifacts.
  274. * @param root - repository root containing the record and generated artifacts.
  275. * @param expected - optional exact public environment required by a consumer.
  276. * @returns the parsed and artifact-verified record.
  277. */
  278. export function readClientBuildRecord(
  279. root: string,
  280. expected?: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
  281. ): ClientBuildRecord {
  282. const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
  283. if (!existsSync(path)) {
  284. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is missing; run a complete pnpm run build first`)
  285. }
  286. let parsed: unknown
  287. try {
  288. parsed = JSON.parse(readFileSync(path, 'utf8'))
  289. } catch (error) {
  290. const detail = error instanceof Error ? error.message : String(error)
  291. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is invalid JSON: ${detail}`)
  292. }
  293. const record = parseClientBuildRecord(parsed)
  294. if (expected !== undefined) assertClientBuildEnvironment(record.environment, expected)
  295. const current = clientArtifactDigest(root)
  296. if (current.fileCount !== record.artifacts.fileCount || current.sha256 !== record.artifacts.sha256) {
  297. throw new Error(
  298. `client artifacts differ from ${CLIENT_BUILD_RECORD_PATH}; run a complete pnpm run build before consuming them`,
  299. )
  300. }
  301. return record
  302. }
  303. /** Return the deterministic digest of every artifact affected by the public client environment. */
  304. function clientArtifactDigest(root: string): ClientArtifactDigest {
  305. const paths = globSync([...CLIENT_ARTIFACT_PATTERNS], { cwd: root })
  306. .map(path => path.replaceAll('\\', '/'))
  307. .filter(path => statSync(resolve(root, path)).isFile())
  308. .sort()
  309. if (paths.length === 0) throw new Error('complete client build produced no Vite or dynamic client artifacts')
  310. const digest = createHash('sha256')
  311. for (const path of paths) {
  312. const content = readFileSync(resolve(root, path))
  313. digest.update(`${Buffer.byteLength(path)}:`)
  314. digest.update(path)
  315. digest.update(`${content.byteLength}:`)
  316. digest.update(content)
  317. }
  318. return { fileCount: paths.length, sha256: digest.digest('hex') }
  319. }
  320. /** Parse and validate the persisted record before any consumer trusts it. */
  321. function parseClientBuildRecord(value: unknown): ClientBuildRecord {
  322. if (!isObject(value) || !hasExactKeys(value, ['artifacts', 'environment', 'formatVersion'])) {
  323. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid top-level schema`)
  324. }
  325. if (value.formatVersion !== CLIENT_BUILD_RECORD_FORMAT) {
  326. throw new Error(
  327. `client build record ${CLIENT_BUILD_RECORD_PATH} uses format ${String(value.formatVersion)}; expected ${String(CLIENT_BUILD_RECORD_FORMAT)}`,
  328. )
  329. }
  330. if (!isObject(value.environment)) {
  331. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment`)
  332. }
  333. const environment: Record<string, string> = {}
  334. for (const [name, entry] of Object.entries(value.environment).sort(([left], [right]) => left.localeCompare(right))) {
  335. if (!name.startsWith(CLIENT_BUILD_ENV_PREFIX) || typeof entry !== 'string') {
  336. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment entry ${name}`)
  337. }
  338. environment[name] = entry
  339. }
  340. if (!isObject(value.artifacts) || !hasExactKeys(value.artifacts, ['fileCount', 'sha256'])) {
  341. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact digest`)
  342. }
  343. if (!Number.isSafeInteger(value.artifacts.fileCount) || Number(value.artifacts.fileCount) < 1) {
  344. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact count`)
  345. }
  346. if (typeof value.artifacts.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(value.artifacts.sha256)) {
  347. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid SHA-256 digest`)
  348. }
  349. return {
  350. formatVersion: CLIENT_BUILD_RECORD_FORMAT,
  351. environment,
  352. artifacts: {
  353. fileCount: Number(value.artifacts.fileCount),
  354. sha256: value.artifacts.sha256,
  355. },
  356. }
  357. }
  358. function isObject(value: unknown): value is Record<string, unknown> {
  359. return typeof value === 'object' && value !== null && !Array.isArray(value)
  360. }
  361. function hasExactKeys(value: Record<string, unknown>, expected: readonly string[]): boolean {
  362. const actual = Object.keys(value).sort()
  363. return actual.length === expected.length && actual.every((key, index) => key === expected[index])
  364. }