browser-bundled-externals.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /** Resolve direct third-party browser inputs through the shipping build configurations, without emitting files. */
  2. import { globSync, readFileSync } from 'node:fs'
  3. import { createRequire } from 'node:module'
  4. import { dirname, resolve } from 'node:path'
  5. import { pathToFileURL } from 'node:url'
  6. import { Rolldown, type UserConfigExport } from 'tsdown'
  7. import ts from 'typescript'
  8. interface Manifest {
  9. name: string
  10. private?: boolean
  11. dsh?: { client?: unknown }
  12. exports?: Record<string, unknown>
  13. }
  14. interface ResolveContext {
  15. resolve(source: string, importer: string, options: { skipSelf: boolean }): Promise<{ id: string } | null>
  16. }
  17. /**
  18. * Name of the installed package owning a bundler-resolved file.
  19. * @param file - Resolved module or asset id, including any loader query.
  20. * @returns Package name, or undefined for workspace and virtual modules.
  21. */
  22. export function browserPackageOfFile(file: string): string | undefined {
  23. const normalized = file.replaceAll('\\', '/')
  24. const marker = normalized.lastIndexOf('/node_modules/')
  25. if (marker < 0) return undefined
  26. const parts = normalized.slice(marker + '/node_modules/'.length).split('/')
  27. return parts[0]?.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]
  28. }
  29. function recorder(seen: Set<string>, workspaceNames: ReadonlySet<string>, followWorkspace = false) {
  30. return {
  31. name: 'dsh-browser-direct-dependencies',
  32. enforce: 'pre' as const,
  33. resolveId: {
  34. order: 'pre' as const,
  35. async handler(this: ResolveContext, source: string, importer: string | undefined) {
  36. if (importer === undefined || source.startsWith('.') || source.startsWith('/')
  37. || source.startsWith('\0') || source.startsWith('node:')) return null
  38. const parts = source.split('/')
  39. const name = source.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]
  40. if (name !== undefined && workspaceNames.has(name)) {
  41. return followWorkspace ? null : { id: source, external: true }
  42. }
  43. const resolved = await this.resolve(source, importer, { skipSelf: true })
  44. if (resolved === null) throw new Error(`browser notices: cannot resolve ${source} from ${importer}`)
  45. const owner = browserPackageOfFile(resolved.id)
  46. if (owner === undefined) return resolved
  47. if (browserPackageOfFile(importer) === undefined) seen.add(owner)
  48. // Notices disclose direct dependencies; upstream implementation imports stay in the lockfile.
  49. return { id: source, external: true }
  50. },
  51. },
  52. }
  53. }
  54. function readManifest(path: string): Manifest {
  55. return JSON.parse(readFileSync(path, 'utf8')) as Manifest
  56. }
  57. /**
  58. * Source aliases shared with the repository's source-plane TypeScript programs.
  59. * @param root - Repository root containing tsconfig.base.json.
  60. * @returns Exact and wildcard aliases for the Vite dependency walk.
  61. */
  62. export function browserSourceAliases(root: string): { find: RegExp; replacement: string }[] {
  63. const path = resolve(root, 'tsconfig.base.json')
  64. const config = ts.readConfigFile(path, file => ts.sys.readFile(file))
  65. if (config.error !== undefined) throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  66. const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root)
  67. return Object.entries(parsed.options.paths ?? {}).map(([name, targets]) => {
  68. const target = targets[0]
  69. if (target === undefined) throw new Error(`browser notices: ${name} has no source target in ${path}`)
  70. const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace('\\*', '(.*)')
  71. return { find: new RegExp(`^${escaped}$`), replacement: resolve(root, target).replace('*', '$1') }
  72. })
  73. }
  74. async function collectClientBundles(
  75. root: string,
  76. manifests: ReadonlyMap<string, Manifest>,
  77. workspaceNames: ReadonlySet<string>,
  78. seen: Set<string>,
  79. ): Promise<void> {
  80. for (const [manifestPath, manifest] of manifests) {
  81. if (manifest.private === true || manifest.dsh?.client === undefined) continue
  82. const dir = dirname(manifestPath)
  83. const loaded = await import(pathToFileURL(resolve(dir, 'tsdown.config.ts')).href) as { default: UserConfigExport }
  84. const factory = await loaded.default
  85. const configured = typeof factory === 'function' ? await factory({ env: {} }, { ci: false }) : factory
  86. const configs = Array.isArray(configured) ? configured : [configured]
  87. const client = configs.find(config => config.name === `${manifest.name}/client`)
  88. if (client === undefined) throw new Error(`browser notices: ${manifest.name} has no browser build config`)
  89. if (typeof client.inputOptions === 'function') throw new Error(`browser notices: ${manifest.name} needs resolved input options`)
  90. const bundle = await Rolldown.rolldown({
  91. ...client.inputOptions,
  92. cwd: dir,
  93. input: client.entry as Rolldown.InputOption,
  94. platform: 'browser',
  95. transform: client.define === undefined ? {} : { define: client.define },
  96. plugins: [recorder(seen, workspaceNames), client.plugins ?? []] as NonNullable<Rolldown.InputOptions['plugins']>,
  97. tsconfig: resolve(root, 'tsconfig.base.client.json'),
  98. })
  99. try {
  100. await bundle.generate({ format: 'cjs', sourcemap: false })
  101. } finally {
  102. await bundle.close()
  103. }
  104. }
  105. }
  106. interface ShellConfig {
  107. build: { rollupOptions?: { input?: string | string[] | Record<string, string> } }
  108. }
  109. interface ViteApi {
  110. resolveConfig(config: Record<string, unknown>, command: 'build'): Promise<ShellConfig>
  111. build(config: Record<string, unknown>): Promise<unknown>
  112. }
  113. async function collectShell(
  114. root: string,
  115. workspaceNames: ReadonlySet<string>,
  116. seen: Set<string>,
  117. ): Promise<void> {
  118. for (const path of globSync('apps/*/vite.config.ts', { cwd: root }).sort()) {
  119. const dir = dirname(resolve(root, path))
  120. const manifest = readManifest(resolve(dir, 'package.json'))
  121. if (manifest.private === true || manifest.exports?.['./dist/*'] === undefined) continue
  122. const vitePath = createRequire(resolve(dir, 'package.json')).resolve('vite')
  123. const vite = await import(pathToFileURL(vitePath).href) as ViteApi
  124. const config = await vite.resolveConfig({ root: dir, logLevel: 'error' }, 'build')
  125. const input = config.build.rollupOptions?.input
  126. const entries = typeof input === 'string' ? [input] : Object.values(input ?? {})
  127. const pages = entries.filter(entry => entry.endsWith('.html'))
  128. if (pages.length === 0) throw new Error(`browser notices: ${manifest.name} has no HTML build entry`)
  129. await vite.build({
  130. root: dir,
  131. logLevel: 'error',
  132. plugins: [recorder(seen, workspaceNames, true)],
  133. resolve: { alias: browserSourceAliases(root) },
  134. build: {
  135. write: false,
  136. minify: false,
  137. sourcemap: false,
  138. reportCompressedSize: false,
  139. rollupOptions: {
  140. input: pages.length === 1 ? pages[0] : pages,
  141. // Chunk coloring expects full third-party bodies; the disclosure walk stops at their imports.
  142. output: { manualChunks: () => undefined },
  143. },
  144. },
  145. })
  146. }
  147. }
  148. /**
  149. * Direct third-party packages resolved by published browser builds.
  150. * @param root - Repository root with installed build dependencies; lib/ is not required.
  151. * @returns Names of distributed browser inputs, excluding workspace packages and erased types.
  152. */
  153. export async function browserBundledExternals(root: string): Promise<Set<string>> {
  154. const manifests = new Map<string, Manifest>()
  155. for (const glob of ['packages/*/*/package.json', 'vendor/*/package.json']) {
  156. for (const path of globSync(glob, { cwd: root }).sort()) {
  157. const absolute = resolve(root, path)
  158. manifests.set(absolute, readManifest(absolute))
  159. }
  160. }
  161. const names = new Set([...manifests.values()].map(manifest => manifest.name))
  162. const seen = new Set<string>()
  163. await collectClientBundles(root, manifests, names, seen)
  164. await collectShell(root, names, seen)
  165. return seen
  166. }