2022-04-15 15:19:05 +00:00
|
|
|
import { pathToFileURL } from 'node:url'
|
|
|
|
import { existsSync } from 'node:fs'
|
|
|
|
import { builtinModules } from 'node:module'
|
2022-07-27 09:01:25 +00:00
|
|
|
import { isAbsolute, normalize, resolve } from 'pathe'
|
2022-12-11 21:44:52 +00:00
|
|
|
import type * as vite from 'vite'
|
|
|
|
import type { isExternal } from 'externality'
|
2022-02-07 13:45:47 +00:00
|
|
|
import { genDynamicImport, genObjectFromRawEntries } from 'knitwork'
|
2022-07-27 09:01:25 +00:00
|
|
|
import fse from 'fs-extra'
|
|
|
|
import { debounce } from 'perfect-debounce'
|
|
|
|
import { isIgnored, logger } from '@nuxt/kit'
|
|
|
|
import { hashId, isCSS, uniq } from './utils'
|
|
|
|
import { createIsExternal } from './utils/external'
|
|
|
|
import { writeManifest } from './manifest'
|
2022-12-11 21:44:52 +00:00
|
|
|
import type { ViteBuildContext } from './vite'
|
2021-10-05 14:18:03 +00:00
|
|
|
|
2023-06-27 09:38:40 +00:00
|
|
|
interface TransformChunk {
|
2021-10-05 14:18:03 +00:00
|
|
|
id: string,
|
|
|
|
code: string,
|
|
|
|
deps: string[],
|
|
|
|
parents: string[]
|
|
|
|
}
|
|
|
|
|
2023-06-27 09:38:40 +00:00
|
|
|
interface SSRTransformResult {
|
2021-10-05 14:18:03 +00:00
|
|
|
code: string,
|
|
|
|
map: object,
|
|
|
|
deps: string[]
|
|
|
|
dynamicDeps: string[]
|
|
|
|
}
|
|
|
|
|
2023-06-27 09:38:40 +00:00
|
|
|
interface TransformOptions {
|
2021-10-12 01:38:30 +00:00
|
|
|
viteServer: vite.ViteDevServer
|
2022-07-27 09:01:25 +00:00
|
|
|
isExternal(id: string): ReturnType<typeof isExternal>
|
2021-10-12 01:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function transformRequest (opts: TransformOptions, id: string) {
|
2021-10-05 14:18:03 +00:00
|
|
|
// Virtual modules start with `\0`
|
|
|
|
if (id && id.startsWith('/@id/__x00__')) {
|
|
|
|
id = '\0' + id.slice('/@id/__x00__'.length)
|
|
|
|
}
|
|
|
|
if (id && id.startsWith('/@id/')) {
|
|
|
|
id = id.slice('/@id/'.length)
|
|
|
|
}
|
2022-08-04 15:24:35 +00:00
|
|
|
if (id && !id.startsWith('/@fs/') && id.startsWith('/')) {
|
2021-10-20 09:50:29 +00:00
|
|
|
// Relative to the root directory
|
2021-11-04 11:25:46 +00:00
|
|
|
const resolvedPath = resolve(opts.viteServer.config.root, '.' + id)
|
|
|
|
if (existsSync(resolvedPath)) {
|
|
|
|
id = resolvedPath
|
|
|
|
}
|
2021-10-12 01:38:30 +00:00
|
|
|
}
|
2021-10-05 14:18:03 +00:00
|
|
|
|
2022-08-04 15:24:35 +00:00
|
|
|
// On Windows, we prefix absolute paths with `/@fs/` to skip node resolution algorithm
|
|
|
|
id = id.replace(/^\/?(?=\w:)/, '/@fs/')
|
|
|
|
|
2022-08-11 17:39:02 +00:00
|
|
|
// Remove query and @fs/ for external modules
|
|
|
|
const externalId = id.replace(/\?v=\w+$|^\/@fs/, '')
|
|
|
|
|
|
|
|
if (await opts.isExternal(externalId)) {
|
2022-08-15 13:40:06 +00:00
|
|
|
const path = builtinModules.includes(externalId.split('node:').pop()!)
|
2022-08-11 17:39:02 +00:00
|
|
|
? externalId
|
|
|
|
: isAbsolute(externalId) ? pathToFileURL(externalId).href : externalId
|
2021-10-05 14:18:03 +00:00
|
|
|
return {
|
2022-04-15 07:57:36 +00:00
|
|
|
code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
|
2022-04-15 07:40:40 +00:00
|
|
|
${genDynamicImport(path, { wrapper: false })}
|
|
|
|
.then(r => {
|
|
|
|
if (r.default && r.default.__esModule)
|
|
|
|
r = r.default
|
|
|
|
exports.default = r.default
|
|
|
|
ssrExportAll(r)
|
|
|
|
})
|
|
|
|
.catch(e => {
|
|
|
|
console.error(e)
|
|
|
|
throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
|
|
|
|
})`,
|
2021-10-05 14:18:03 +00:00
|
|
|
deps: [],
|
|
|
|
dynamicDeps: []
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Transform
|
2021-10-12 01:38:30 +00:00
|
|
|
const res: SSRTransformResult = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
|
2021-12-17 09:08:09 +00:00
|
|
|
console.warn(`[SSR] Error transforming ${id}:`, err)
|
2021-10-05 14:18:03 +00:00
|
|
|
// console.error(err)
|
|
|
|
}) as SSRTransformResult || { code: '', map: {}, deps: [], dynamicDeps: [] }
|
|
|
|
|
|
|
|
// Wrap into a vite module
|
2022-04-15 07:57:36 +00:00
|
|
|
const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
|
2021-10-05 14:18:03 +00:00
|
|
|
${res.code || '/* empty */'};
|
|
|
|
}`
|
|
|
|
return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] }
|
|
|
|
}
|
|
|
|
|
2022-08-15 13:40:06 +00:00
|
|
|
async function transformRequestRecursive (opts: TransformOptions, id: string, parent = '<entry>', chunks: Record<string, TransformChunk> = {}) {
|
2021-10-05 14:18:03 +00:00
|
|
|
if (chunks[id]) {
|
|
|
|
chunks[id].parents.push(parent)
|
|
|
|
return
|
|
|
|
}
|
2021-10-12 01:38:30 +00:00
|
|
|
const res = await transformRequest(opts, id)
|
2021-11-30 14:37:01 +00:00
|
|
|
const deps = uniq([...res.deps, ...res.dynamicDeps])
|
2021-10-05 14:18:03 +00:00
|
|
|
|
2021-11-30 14:37:01 +00:00
|
|
|
chunks[id] = {
|
2021-10-05 14:18:03 +00:00
|
|
|
id,
|
|
|
|
code: res.code,
|
2021-11-30 14:37:01 +00:00
|
|
|
deps,
|
2021-10-05 14:18:03 +00:00
|
|
|
parents: [parent]
|
2021-11-30 14:37:01 +00:00
|
|
|
} as TransformChunk
|
|
|
|
for (const dep of deps) {
|
|
|
|
await transformRequestRecursive(opts, dep, id, chunks)
|
2021-10-05 14:18:03 +00:00
|
|
|
}
|
|
|
|
return Object.values(chunks)
|
|
|
|
}
|
|
|
|
|
2023-06-27 09:38:40 +00:00
|
|
|
async function bundleRequest (opts: TransformOptions, entryURL: string) {
|
2022-08-15 13:40:06 +00:00
|
|
|
const chunks = (await transformRequestRecursive(opts, entryURL))!
|
2021-10-05 14:18:03 +00:00
|
|
|
|
2021-10-11 12:29:35 +00:00
|
|
|
const listIds = (ids: string[]) => ids.map(id => `// - ${id} (${hashId(id)})`).join('\n')
|
2021-10-05 14:18:03 +00:00
|
|
|
const chunksCode = chunks.map(chunk => `
|
|
|
|
// --------------------
|
|
|
|
// Request: ${chunk.id}
|
|
|
|
// Parents: \n${listIds(chunk.parents)}
|
|
|
|
// Dependencies: \n${listIds(chunk.deps)}
|
|
|
|
// --------------------
|
2022-07-21 10:44:33 +00:00
|
|
|
const ${hashId(chunk.id + '-' + chunk.code)} = ${chunk.code}
|
2021-10-05 14:18:03 +00:00
|
|
|
`).join('\n')
|
|
|
|
|
2022-02-07 13:45:47 +00:00
|
|
|
const manifestCode = `const __modules__ = ${
|
2022-07-21 10:44:33 +00:00
|
|
|
genObjectFromRawEntries(chunks.map(chunk => [chunk.id, hashId(chunk.id + '-' + chunk.code)]))
|
2022-02-07 13:45:47 +00:00
|
|
|
}`
|
2021-10-05 14:18:03 +00:00
|
|
|
|
|
|
|
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/ssr/ssrModuleLoader.ts
|
|
|
|
const ssrModuleLoader = `
|
|
|
|
const __pendingModules__ = new Map()
|
|
|
|
const __pendingImports__ = new Map()
|
2021-10-26 12:59:05 +00:00
|
|
|
const __ssrContext__ = { global: globalThis }
|
2021-10-05 14:18:03 +00:00
|
|
|
|
|
|
|
function __ssrLoadModule__(url, urlStack = []) {
|
|
|
|
const pendingModule = __pendingModules__.get(url)
|
|
|
|
if (pendingModule) { return pendingModule }
|
|
|
|
const modulePromise = __instantiateModule__(url, urlStack)
|
|
|
|
__pendingModules__.set(url, modulePromise)
|
|
|
|
modulePromise.catch(() => { __pendingModules__.delete(url) })
|
|
|
|
.finally(() => { __pendingModules__.delete(url) })
|
|
|
|
return modulePromise
|
|
|
|
}
|
|
|
|
|
|
|
|
async function __instantiateModule__(url, urlStack) {
|
|
|
|
const mod = __modules__[url]
|
|
|
|
if (mod.stubModule) { return mod.stubModule }
|
|
|
|
const stubModule = { [Symbol.toStringTag]: 'Module' }
|
|
|
|
Object.defineProperty(stubModule, '__esModule', { value: true })
|
|
|
|
mod.stubModule = stubModule
|
2021-10-27 11:32:26 +00:00
|
|
|
// https://vitejs.dev/guide/api-hmr.html
|
|
|
|
const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
|
2021-10-05 14:18:03 +00:00
|
|
|
urlStack = urlStack.concat(url)
|
|
|
|
const isCircular = url => urlStack.includes(url)
|
|
|
|
const pendingDeps = []
|
|
|
|
const ssrImport = async (dep) => {
|
|
|
|
// TODO: Handle externals if dep[0] !== '.' | '/'
|
|
|
|
if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
|
|
|
|
pendingDeps.push(dep)
|
|
|
|
if (pendingDeps.length === 1) {
|
|
|
|
__pendingImports__.set(url, pendingDeps)
|
|
|
|
}
|
|
|
|
await __ssrLoadModule__(dep, urlStack)
|
|
|
|
if (pendingDeps.length === 1) {
|
|
|
|
__pendingImports__.delete(url)
|
|
|
|
} else {
|
|
|
|
pendingDeps.splice(pendingDeps.indexOf(dep), 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return __modules__[dep].stubModule
|
|
|
|
}
|
|
|
|
function ssrDynamicImport (dep) {
|
|
|
|
// TODO: Handle dynamic import starting with . relative to url
|
|
|
|
return ssrImport(dep)
|
|
|
|
}
|
|
|
|
|
|
|
|
function ssrExportAll(sourceModule) {
|
|
|
|
for (const key in sourceModule) {
|
|
|
|
if (key !== 'default') {
|
|
|
|
try {
|
|
|
|
Object.defineProperty(stubModule, key, {
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
get() { return sourceModule[key] }
|
|
|
|
})
|
|
|
|
} catch (_err) { }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-15 07:57:36 +00:00
|
|
|
const cjsModule = {
|
|
|
|
get exports () {
|
|
|
|
return stubModule.default
|
|
|
|
},
|
|
|
|
set exports (v) {
|
|
|
|
stubModule.default = v
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2021-10-05 14:18:03 +00:00
|
|
|
await mod(
|
|
|
|
__ssrContext__.global,
|
2022-04-15 07:57:36 +00:00
|
|
|
cjsModule,
|
|
|
|
stubModule.default,
|
2021-10-05 14:18:03 +00:00
|
|
|
stubModule,
|
|
|
|
importMeta,
|
|
|
|
ssrImport,
|
|
|
|
ssrDynamicImport,
|
|
|
|
ssrExportAll
|
|
|
|
)
|
|
|
|
|
|
|
|
return stubModule
|
|
|
|
}
|
|
|
|
`
|
|
|
|
|
|
|
|
const code = [
|
|
|
|
chunksCode,
|
|
|
|
manifestCode,
|
|
|
|
ssrModuleLoader,
|
2022-02-07 13:45:47 +00:00
|
|
|
`export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
|
2021-10-05 14:18:03 +00:00
|
|
|
].join('\n\n')
|
|
|
|
|
2021-10-12 14:05:20 +00:00
|
|
|
return {
|
|
|
|
code,
|
2021-11-30 14:37:01 +00:00
|
|
|
ids: chunks.map(i => i.id)
|
2021-10-12 14:05:20 +00:00
|
|
|
}
|
2021-10-05 14:18:03 +00:00
|
|
|
}
|
2022-07-27 09:01:25 +00:00
|
|
|
|
|
|
|
export async function initViteDevBundler (ctx: ViteBuildContext, onBuild: () => Promise<any>) {
|
2022-08-15 13:40:06 +00:00
|
|
|
const viteServer = ctx.ssrServer!
|
2022-07-27 09:01:25 +00:00
|
|
|
const options: TransformOptions = {
|
|
|
|
viteServer,
|
|
|
|
isExternal: createIsExternal(viteServer, ctx.nuxt.options.rootDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Build and watch
|
|
|
|
const _doBuild = async () => {
|
|
|
|
const start = Date.now()
|
2022-08-04 15:24:35 +00:00
|
|
|
const { code, ids } = await bundleRequest(options, ctx.entry)
|
2022-07-27 09:01:25 +00:00
|
|
|
await fse.writeFile(resolve(ctx.nuxt.options.buildDir, 'dist/server/server.mjs'), code, 'utf-8')
|
|
|
|
// Have CSS in the manifest to prevent FOUC on dev SSR
|
|
|
|
await writeManifest(ctx, ids.filter(isCSS).map(i => i.slice(1)))
|
|
|
|
const time = (Date.now() - start)
|
|
|
|
logger.success(`Vite server built in ${time}ms`)
|
|
|
|
await onBuild()
|
|
|
|
}
|
|
|
|
const doBuild = debounce(_doBuild)
|
|
|
|
|
|
|
|
// Initial build
|
|
|
|
await _doBuild()
|
|
|
|
|
|
|
|
// Watch
|
|
|
|
viteServer.watcher.on('all', (_event, file) => {
|
|
|
|
file = normalize(file) // Fix windows paths
|
|
|
|
if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnored(file)) { return }
|
|
|
|
doBuild()
|
|
|
|
})
|
|
|
|
// ctx.nuxt.hook('builder:watch', () => doBuild())
|
|
|
|
ctx.nuxt.hook('app:templatesGenerated', () => doBuild())
|
|
|
|
}
|