import ora from 'ora' ; import path from 'path' ; import fs from 'fs-extra' ; import { slash } from '../utils/slash' ; import { APP_PATH } from '../alias' ; import { SiteConfig } from '../config' ; import { RollupOutput } from 'rollup' ; import { build , BuildOptions , UserConfig as ViteUserConfig } from 'vite' ; import { createVitePressPlugin } from '../plugin' ; import { buildMPAClient } from './buildMPAClient' ; export const okMark = '\x1b[32m✓\x1b[0m' ; export const failMark = '\x1b[31m✖\x1b[0m' ; export async function bundle ( config , options ) { const { root , srcDir } = config ; const pageToHashMap = Object . create ( null ) ; const clientJSMap = Object . create ( null ) ; const input = { app : path . resolve ( APP_PATH , 'index.js' ) } ; config . pages . forEach ( ( file ) => { input [ slash ( file ) . replace ( /\//g , '_' ) ] = path . resolve ( srcDir , file ) ; } ) ; const { rollupOptions } = options ; const resolveViteConfig = ( ssr ) : ViteUserConfig => ( { root : srcDir , base : config . site . base , logLevel : 'warn' , plugins : createVitePressPlugin ( root , config , ssr , pageToHashMap , clientJSMap ) , ssr : { noExternal : [ 'vitepress' ] } , build : { ... options , emptyOutDir : true , ssr , outDir : ssr ? config . tempDir : config . outDir , cssCodeSplit : false , rollupOptions : { ... rollupOptions , input , preserveEntrySignatures : 'allow-extension' , output : { ... rollupOptions ?. output , ... ( ssr ? { } : { chunkFileNames ( chunk ) { if ( ! chunk . isEntry && /runtime/ . test ( chunk . name ) ) { return `assets/framework.[hash].js` ; } return adComponentRE . test ( chunk . name ) ? `assets/ui-custom.[hash].js` : `assets/[name].[hash].js` ; } } ) } } , minify : ssr ? ( config . mpa ? 'esbuild' : false ) : ! process . env . DEBUG } } ) ; let clientResult ; let serverResult ; const spinner = ora ( ) ; spinner . start ( 'building client + server bundles...' ) ; try { ; [ clientResult , serverResult ] = await ( Promise . all ( [ config . mpa ? null : build ( resolveViteConfig ( false ) ) , build ( resolveViteConfig ( true ) ) ] ) as Promise < [ RollupOutput , RollupOutput ] > ) ; } catch ( e ) { spinner . stopAndPersist ( { symbol : failMark } ) ; throw e ; } spinner . stopAndPersist ( { symbol : okMark } ) ; if ( config . mpa ) { for ( const chunk of serverResult . output ) { if ( ! chunk . fileName . endsWith ( '.js' ) ) { const tempPath = path . resolve ( config . tempDir , chunk . fileName ) ; const outPath = path . resolve ( config . outDir , chunk . fileName ) ; await fs . copy ( tempPath , outPath ) ; } } const publicDir = path . resolve ( config . srcDir , 'public' ) ; if ( fs . existsSync ( publicDir ) ) { await fs . copy ( publicDir , config . outDir ) ; } if ( Object . keys ( clientJSMap ) . length ) { clientResult = ( await buildMPAClient ( clientJSMap , config ) ) as RollupOutput ; } } return { clientResult , serverResult , pageToHashMap } ; } const adComponentRE = /(?:Carbon|BuySell)Ads/ ;