vite.config.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import { readFile, writeFile } from 'node:fs/promises'
  2. import { fileURLToPath } from 'node:url'
  3. import { defineConfig } from 'vite'
  4. import type { Plugin } from 'vite'
  5. import react from '@vitejs/plugin-react'
  6. import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts'
  7. const src = (rel: string): string => fileURLToPath(new URL(rel, import.meta.url))
  8. const STANDALONE_ERROR = 'apps/web is not a standalone application: bare Vite cannot inject window.__DSH_BOOT__. '
  9. + 'From a repository checkout, run `pnpm dsh web`; an installed package uses `dsh web`. '
  10. + 'For client-plugin HMR, run `pnpm dsh web` together with `pnpm run dev:web`.'
  11. const DEFAULT_CLIENT_TITLE = 'DSH Local Build'
  12. /** Escape build-time text before placing it in the HTML title element. */
  13. function escapeHtmlText(value: string): string {
  14. return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  15. }
  16. /** Project the public build title into the initial HTML document. */
  17. function clientDocumentTitle(): Plugin {
  18. const title = escapeHtmlText(process.env.DSH_CLIENT_TITLE ?? DEFAULT_CLIENT_TITLE)
  19. return {
  20. name: 'dsh-client-document-title',
  21. transformIndexHtml(html) {
  22. return html.replace('<title>DSH Local Build</title>', `<title>${title}</title>`)
  23. },
  24. }
  25. }
  26. /** Fail before a Vite dev or preview server can expose the boot-manifest-free shell. */
  27. function rejectStandaloneServe(): Plugin {
  28. return {
  29. name: 'dsh-reject-standalone-web-serve',
  30. config(_config, env) {
  31. if (env.command === 'serve') throw new Error(STANDALONE_ERROR)
  32. },
  33. }
  34. }
  35. /**
  36. * Emit preview.html beside index.html: the built index page with one module
  37. * script — the worker bootstrap entry — spliced ahead of its entry tag. Both
  38. * pages share every chunk; the extra tag is the only difference, so the
  39. * static worker deployment ships the served page verbatim plus its
  40. * bootstrap.
  41. */
  42. function emitPreviewPage(): Plugin {
  43. let bootstrapFile: string | undefined
  44. let write = true
  45. return {
  46. name: 'dsh-emit-preview-page',
  47. configResolved(config) {
  48. write = config.build.write
  49. },
  50. generateBundle(_options, bundle) {
  51. if (!write) return
  52. for (const item of Object.values(bundle)) {
  53. if (item.type === 'chunk' && item.isEntry && item.name === 'bootstrap') bootstrapFile = item.fileName
  54. }
  55. if (bootstrapFile === undefined) throw new Error('vite: preview bootstrap entry missing from the bundle')
  56. },
  57. async closeBundle() {
  58. if (!write) return
  59. // A build that failed before generateBundle has no page to splice.
  60. if (bootstrapFile === undefined) return
  61. const page = await readFile(src('./dist/index.html'), 'utf8')
  62. const anchor = page.indexOf('<script type="module"')
  63. if (anchor === -1) throw new Error('vite: built index.html lost its module entry tag')
  64. const tag = `<script type="module" crossorigin src="./${bootstrapFile}"></script>`
  65. await writeFile(src('./dist/preview.html'), `${page.slice(0, anchor)}${tag}${page.slice(anchor)}`)
  66. },
  67. }
  68. }
  69. /**
  70. * Vendor-chunk membership, by exact npm package name — the heavy render
  71. * families (math, highlight, markdown) that change only on dependency bumps.
  72. * Only packages workspace code imports DIRECTLY need listing: their private
  73. * transitive dependencies (oniguruma machinery, character tables, …) are
  74. * imported solely by these and rollup's chunk coloring pulls them into
  75. * vendor automatically. A dependency shared with index-side code falls back
  76. * to index — a few kB of dilution, never a correctness problem. Anything not
  77. * listed (react family, the vendored cordis workspace, tiny helpers like
  78. * anser/clsx, all workspace code) stays in the default `index` chunk, so
  79. * editing shell code re-hashes only index and returning clients keep the
  80. * cached vendor chunk.
  81. *
  82. * Every member must be React-free. A package that
  83. * imports react/jsx-runtime must never be listed — rollup folds a module
  84. * shared between the entry and a manual chunk into the manual chunk, so one
  85. * react-importing member would drag the single shared react copy into
  86. * vendor. The React side of markdown/math rendering is workspace code and
  87. * rides index.
  88. */
  89. const VENDOR_PACKAGES: ReadonlySet<string> = new Set([
  90. // math
  91. 'katex',
  92. // syntax highlight (@shikijs/langs is handled separately below —
  93. // lazy grammars must not land here)
  94. 'shiki',
  95. // markdown parse pipeline (micromark/mdast; the incremental React renderer
  96. // over it is workspace code)
  97. 'mdast-util-from-markdown',
  98. 'mdast-util-gfm',
  99. 'mdast-util-math',
  100. 'micromark-core-commonmark',
  101. 'micromark-extension-gfm',
  102. 'micromark-extension-math',
  103. 'micromark-factory-space',
  104. 'micromark-util-character',
  105. 'micromark-util-classify-character',
  106. 'micromark-util-sanitize-uri',
  107. 'micromark-util-symbol',
  108. 'micromark-util-types',
  109. ])
  110. /**
  111. * Boot grammars statically imported by ui-primitives' highlight.ts
  112. * (`@shikijs/langs/typescript` → `dist/typescript.mjs`, etc.). They live in
  113. * the same package as the lazy read-card grammars, but unlike those they are
  114. * part of the initial load and belong in the vendor chunk; the lazy ones must
  115. * stay unassigned so each keeps its own on-demand chunk.
  116. */
  117. const BOOT_GRAMMAR_FILES: readonly string[] = [
  118. 'dist/typescript.mjs',
  119. 'dist/shellscript.mjs',
  120. 'dist/json.mjs',
  121. ]
  122. /** Font asset extensions routed to assets/fonts/ (KaTeX's woff2/woff/ttf faces). */
  123. const FONT_EXTENSIONS: readonly string[] = ['.woff2', '.woff', '.ttf']
  124. /**
  125. * npm package name of a resolved module id: the segment after the last
  126. * `node_modules/`. pnpm nests the real package under an inner node_modules.
  127. */
  128. function npmPackageOf(id: string): string | undefined {
  129. const parts = id.split('/node_modules/')
  130. if (parts.length === 1) return undefined
  131. const [first, second] = parts[parts.length - 1].split('/')
  132. if (first.startsWith('.')) return undefined // .pnpm store segment, not a package
  133. if (first.startsWith('@')) return second === undefined ? undefined : `${first}/${second}`
  134. return first
  135. }
  136. export default defineConfig({
  137. // Relative asset URLs: preview.html mounts the same output under any base
  138. // directory, and the served index resolves identically from the site root.
  139. base: './',
  140. plugins: [rejectStandaloneServe(), clientDocumentTitle(), react(), emitPreviewPage()],
  141. build: {
  142. // The worker bootstrap holds its page at top-level await; Vite's default
  143. // `modules` target (es2020-era) rejects that syntax.
  144. target: 'es2022',
  145. sourcemap: true,
  146. rollupOptions: {
  147. input: {
  148. index: src('./index.html'),
  149. // Standalone entry, not an index.html script tag: Vite folds every
  150. // module tag of one page into a single synthetic entry, and only a
  151. // separate input keeps the shared page chunks bootstrap-free.
  152. bootstrap: src('./src/preview.ts'),
  153. },
  154. output: {
  155. // The worker-preview surface groups under dist/preview/ (the page
  156. // itself stays at dist/preview.html), so the published payload can
  157. // exclude it as one directory.
  158. entryFileNames(chunk): string {
  159. return chunk.name === 'bootstrap' ? 'preview/[name]-[hash].js' : 'assets/[name]-[hash].js'
  160. },
  161. // Output layout: the two main chunks stay at assets/ root; lazy
  162. // @shikijs/langs grammar chunks group under assets/langs/; fonts
  163. // (all KaTeX faces referenced by vendor.css) group under
  164. // assets/fonts/. Sourcemaps need no arrangement: rollup writes each
  165. // .map next to its js and references it by bare relative filename.
  166. chunkFileNames(chunk): string {
  167. // Grammar chunks are recognized by their member modules, not the
  168. // facade: shared embedded-grammar chunks (e.g. html+javascript,
  169. // split out because php/ruby/mdx embed them) have no facade at all.
  170. // index and vendor are excluded by name — vendor legitimately
  171. // carries the three boot grammars.
  172. if (chunk.name === 'index' || chunk.name === 'vendor') return 'assets/[name]-[hash].js'
  173. const isLangChunk = chunk.moduleIds.some(id => id.includes('/node_modules/@shikijs/langs/'))
  174. return isLangChunk ? 'assets/langs/[name]-[hash].js' : 'assets/[name]-[hash].js'
  175. },
  176. assetFileNames(asset): string {
  177. const fileName = asset.names[0] ?? ''
  178. const isFont = FONT_EXTENSIONS.some(ext => fileName.endsWith(ext))
  179. return isFont ? 'assets/fonts/[name]-[hash][extname]' : 'assets/[name]-[hash][extname]'
  180. },
  181. manualChunks(id: string): string | undefined {
  182. const pkg = npmPackageOf(id)
  183. if (pkg === undefined) return undefined // workspace + vendored cordis: index
  184. if (pkg === '@shikijs/langs') {
  185. return BOOT_GRAMMAR_FILES.some(file => id.endsWith(`/${file}`)) ? 'vendor' : undefined
  186. }
  187. return VENDOR_PACKAGES.has(pkg) ? 'vendor' : undefined
  188. },
  189. },
  190. },
  191. },
  192. worker: {
  193. // The preview worker rides dist/preview/ with the rest of that surface.
  194. rollupOptions: { output: { entryFileNames: 'preview/[name]-[hash].js' } },
  195. },
  196. resolve: {
  197. // One instance per shared npm identity: a bare specifier otherwise resolves
  198. // from the importer's directory, so a diverging range ships a second React
  199. // and splits hook and element identity. Entries are package ids — they cover
  200. // react/jsx-runtime and react-dom/client — and resolve from this package's
  201. // node_modules, so react must stay a devDependency here and any watcher must
  202. // run vite from this directory (scripts/dev-web.ts). Workspace packages need
  203. // no entry: pnpm links each of them to a single directory.
  204. dedupe: ['react', 'react-dom'],
  205. // Workspace packages are consumed as built lib products: each resolves
  206. // through its own package.json exports from the importer's directory, and
  207. // CSS still rides Vite's pipeline because the client build preset emits it
  208. // beside the bundle. Plugin packages never enter this graph; they arrive as
  209. // runtime bundles through the client module system. The remaining alias
  210. // browserizes the vendored Cordis Loader's only Node import.
  211. alias: [
  212. { find: /^node:module$/, replacement: src('./src/node-module-stub.ts') },
  213. ],
  214. },
  215. define: {
  216. ...clientBuildEnvironmentDefines(process.env),
  217. // vendored loader internal.ts: fromInternal() probes the Node major —
  218. // "0.0.0" takes neither branch, returning undefined (exactly the empty
  219. // internal slot the shell boot fills with the client module loader).
  220. 'process.versions.node': '"0.0.0"',
  221. 'process.execArgv': '[]',
  222. // vendored loader index.ts: envData falls to its default branch.
  223. 'process.env.CORDIS_SHARED': 'undefined',
  224. },
  225. })