vite.config.ts 11 KB

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