refactor: rebrand to nitro

This commit is contained in:
Pooya Parsa 2021-01-22 20:55:59 +01:00
parent 41951c8862
commit 5248905dd7
19 changed files with 177 additions and 177 deletions

View File

@ -6,19 +6,19 @@ import { readFile, emptyDir, copy } from 'fs-extra'
import { printFSTree } from './utils/tree' import { printFSTree } from './utils/tree'
import { getRollupConfig } from './rollup/config' import { getRollupConfig } from './rollup/config'
import { hl, prettyPath, serializeTemplate, writeFile, isDirectory } from './utils' import { hl, prettyPath, serializeTemplate, writeFile, isDirectory } from './utils'
import { SigmaContext } from './context' import { NitroContext } from './context'
export async function prepare (sigmaContext: SigmaContext) { export async function prepare (nitroContext: NitroContext) {
consola.info(`Sigma preset is ${hl(sigmaContext.preset)}`) consola.info(`Nitro preset is ${hl(nitroContext.preset)}`)
await cleanupDir(sigmaContext.output.dir) await cleanupDir(nitroContext.output.dir)
if (!sigmaContext.output.publicDir.startsWith(sigmaContext.output.dir)) { if (!nitroContext.output.publicDir.startsWith(nitroContext.output.dir)) {
await cleanupDir(sigmaContext.output.publicDir) await cleanupDir(nitroContext.output.publicDir)
} }
if (!sigmaContext.output.serverDir.startsWith(sigmaContext.output.dir)) { if (!nitroContext.output.serverDir.startsWith(nitroContext.output.dir)) {
await cleanupDir(sigmaContext.output.serverDir) await cleanupDir(nitroContext.output.serverDir)
} }
} }
@ -27,63 +27,63 @@ async function cleanupDir (dir: string) {
await emptyDir(dir) await emptyDir(dir)
} }
export async function generate (sigmaContext: SigmaContext) { export async function generate (nitroContext: NitroContext) {
const spinner = ora() const spinner = ora()
spinner.start('Generating public...') spinner.start('Generating public...')
const clientDist = resolve(sigmaContext._nuxt.buildDir, 'dist/client') const clientDist = resolve(nitroContext._nuxt.buildDir, 'dist/client')
if (await isDirectory(clientDist)) { if (await isDirectory(clientDist)) {
await copy(clientDist, join(sigmaContext.output.publicDir, sigmaContext._nuxt.publicPath)) await copy(clientDist, join(nitroContext.output.publicDir, nitroContext._nuxt.publicPath))
} }
const staticDir = resolve(sigmaContext._nuxt.srcDir, sigmaContext._nuxt.staticDir) const staticDir = resolve(nitroContext._nuxt.srcDir, nitroContext._nuxt.staticDir)
if (await isDirectory(staticDir)) { if (await isDirectory(staticDir)) {
await copy(staticDir, sigmaContext.output.publicDir) await copy(staticDir, nitroContext.output.publicDir)
} }
spinner.succeed('Generated public ' + prettyPath(sigmaContext.output.publicDir)) spinner.succeed('Generated public ' + prettyPath(nitroContext.output.publicDir))
} }
export async function build (sigmaContext: SigmaContext) { export async function build (nitroContext: NitroContext) {
// Compile html template // Compile html template
const htmlSrc = resolve(sigmaContext._nuxt.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`) const htmlSrc = resolve(nitroContext._nuxt.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`)
const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' } const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' }
htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.') htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.')
htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8') htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8')
htmlTemplate.compiled = 'module.exports = ' + serializeTemplate(htmlTemplate.contents) htmlTemplate.compiled = 'module.exports = ' + serializeTemplate(htmlTemplate.contents)
await sigmaContext._internal.hooks.callHook('sigma:template:document', htmlTemplate) await nitroContext._internal.hooks.callHook('nitro:template:document', htmlTemplate)
await writeFile(htmlTemplate.dst, htmlTemplate.compiled) await writeFile(htmlTemplate.dst, htmlTemplate.compiled)
sigmaContext.rollupConfig = getRollupConfig(sigmaContext) nitroContext.rollupConfig = getRollupConfig(nitroContext)
await sigmaContext._internal.hooks.callHook('sigma:rollup:before', sigmaContext) await nitroContext._internal.hooks.callHook('nitro:rollup:before', nitroContext)
return sigmaContext._nuxt.dev ? _watch(sigmaContext) : _build(sigmaContext) return nitroContext._nuxt.dev ? _watch(nitroContext) : _build(nitroContext)
} }
async function _build (sigmaContext: SigmaContext) { async function _build (nitroContext: NitroContext) {
const spinner = ora() const spinner = ora()
spinner.start('Building server...') spinner.start('Building server...')
const build = await rollup(sigmaContext.rollupConfig).catch((error) => { const build = await rollup(nitroContext.rollupConfig).catch((error) => {
spinner.fail('Rollup error: ' + error.message) spinner.fail('Rollup error: ' + error.message)
throw error throw error
}) })
spinner.start('Writing server bundle...') spinner.start('Writing server bundle...')
await build.write(sigmaContext.rollupConfig.output) await build.write(nitroContext.rollupConfig.output)
spinner.succeed('Server built') spinner.succeed('Server built')
await printFSTree(sigmaContext.output.serverDir) await printFSTree(nitroContext.output.serverDir)
await sigmaContext._internal.hooks.callHook('sigma:compiled', sigmaContext) await nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext)
return { return {
entry: resolve(sigmaContext.rollupConfig.output.dir, sigmaContext.rollupConfig.output.entryFileNames) entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames)
} }
} }
function _watch (sigmaContext: SigmaContext) { function _watch (nitroContext: NitroContext) {
const spinner = ora() const spinner = ora()
const watcher = rollupWatch(sigmaContext.rollupConfig) const watcher = rollupWatch(nitroContext.rollupConfig)
let start let start
@ -96,13 +96,13 @@ function _watch (sigmaContext: SigmaContext) {
// Building an individual bundle // Building an individual bundle
case 'BUNDLE_START': case 'BUNDLE_START':
start = Date.now() start = Date.now()
spinner.start('Building Sigma...') spinner.start('Building Nitro...')
return return
// Finished building all bundles // Finished building all bundles
case 'END': case 'END':
sigmaContext._internal.hooks.callHook('sigma:compiled', sigmaContext) nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext)
return spinner.succeed(`Sigma built in ${Date.now() - start} ms`) return spinner.succeed(`Nitro built in ${Date.now() - start} ms`)
// Encountered an error while bundling // Encountered an error while bundling
case 'ERROR': case 'ERROR':

View File

@ -1,7 +1,7 @@
import fetch from 'node-fetch' import fetch from 'node-fetch'
import { resolve } from 'upath' import { resolve } from 'upath'
import { build, generate, prepare } from './build' import { build, generate, prepare } from './build'
import { getSigmaContext, SigmaContext } from './context' import { getNitroContext, NitroContext } from './context'
import { createDevServer } from './server' import { createDevServer } from './server'
import { wpfs } from './utils/wpfs' import { wpfs } from './utils/wpfs'
import { resolveMiddleware } from './middleware' import { resolveMiddleware } from './middleware'
@ -14,20 +14,20 @@ export default function nuxt2CompatModule () {
nuxt.options.build.indicator = false nuxt.options.build.indicator = false
// Create contexts // Create contexts
const sigmaContext = getSigmaContext(nuxt.options, nuxt.options.sigma || {}) const nitroContext = getNitroContext(nuxt.options, nuxt.options.nitro || {})
const sigmaDevContext = getSigmaContext(nuxt.options, { preset: 'local' }) const nitroDevContext = getNitroContext(nuxt.options, { preset: 'local' })
// Connect hooks // Connect hooks
nuxt.addHooks(sigmaContext.nuxtHooks) nuxt.addHooks(nitroContext.nuxtHooks)
nuxt.hook('close', () => sigmaContext._internal.hooks.callHook('close')) nuxt.hook('close', () => nitroContext._internal.hooks.callHook('close'))
nuxt.addHooks(sigmaDevContext.nuxtHooks) nuxt.addHooks(nitroDevContext.nuxtHooks)
nuxt.hook('close', () => sigmaDevContext._internal.hooks.callHook('close')) nuxt.hook('close', () => nitroDevContext._internal.hooks.callHook('close'))
sigmaDevContext._internal.hooks.hook('renderLoading', nitroDevContext._internal.hooks.hook('renderLoading',
(req, res) => nuxt.callHook('server:nuxt:renderLoading', req, res)) (req, res) => nuxt.callHook('server:nuxt:renderLoading', req, res))
// Expose process.env.SIGMA_PRESET // Expose process.env.NITRO_PRESET
nuxt.options.env.SIGMA_PRESET = sigmaContext.preset nuxt.options.env.NITRO_PRESET = nitroContext.preset
// .ts is supported for serverMiddleware // .ts is supported for serverMiddleware
nuxt.options.extensions.push('ts') nuxt.options.extensions.push('ts')
@ -35,13 +35,13 @@ export default function nuxt2CompatModule () {
// Replace nuxt server // Replace nuxt server
if (nuxt.server) { if (nuxt.server) {
nuxt.server.__closed = true nuxt.server.__closed = true
nuxt.server = createNuxt2DevServer(sigmaDevContext) nuxt.server = createNuxt2DevServer(nitroDevContext)
} }
// Sigma client plugin // Nitro client plugin
this.addPlugin({ this.addPlugin({
fileName: 'sigma.client.js', fileName: 'nitro.client.js',
src: resolve(sigmaContext._internal.runtimeDir, 'app/sigma.client.js') src: resolve(nitroContext._internal.runtimeDir, 'app/nitro.client.js')
}) })
// Resolve middleware // Resolve middleware
@ -49,8 +49,8 @@ export default function nuxt2CompatModule () {
const { middleware, legacyMiddleware } = const { middleware, legacyMiddleware } =
resolveMiddleware(nuxt.options.serverMiddleware, nuxt.resolver.resolvePath) resolveMiddleware(nuxt.options.serverMiddleware, nuxt.resolver.resolvePath)
nuxt.server.setLegacyMiddleware(legacyMiddleware) nuxt.server.setLegacyMiddleware(legacyMiddleware)
sigmaContext.middleware.push(...middleware) nitroContext.middleware.push(...middleware)
sigmaDevContext.middleware.push(...middleware) nitroDevContext.middleware.push(...middleware)
}) })
// nuxt build/dev // nuxt build/dev
@ -58,47 +58,47 @@ export default function nuxt2CompatModule () {
nuxt.options.build.standalone = false nuxt.options.build.standalone = false
nuxt.hook('build:done', async () => { nuxt.hook('build:done', async () => {
if (nuxt.options.dev) { if (nuxt.options.dev) {
await build(sigmaDevContext) await build(nitroDevContext)
} else if (!sigmaContext._nuxt.isStatic) { } else if (!nitroContext._nuxt.isStatic) {
await prepare(sigmaContext) await prepare(nitroContext)
await generate(sigmaContext) await generate(nitroContext)
await build(sigmaContext) await build(nitroContext)
} }
}) })
// nude dev // nude dev
if (nuxt.options.dev) { if (nuxt.options.dev) {
sigmaDevContext._internal.hooks.hook('sigma:compiled', () => { nuxt.server.watch() }) nitroDevContext._internal.hooks.hook('nitro:compiled', () => { nuxt.server.watch() })
nuxt.hook('build:compile', ({ compiler }) => { compiler.outputFileSystem = wpfs }) nuxt.hook('build:compile', ({ compiler }) => { compiler.outputFileSystem = wpfs })
nuxt.hook('server:devMiddleware', (m) => { nuxt.server.setDevMiddleware(m) }) nuxt.hook('server:devMiddleware', (m) => { nuxt.server.setDevMiddleware(m) })
} }
// nuxt generate // nuxt generate
nuxt.options.generate.dir = sigmaContext.output.publicDir nuxt.options.generate.dir = nitroContext.output.publicDir
nuxt.options.generate.manifest = false nuxt.options.generate.manifest = false
nuxt.hook('generate:cache:ignore', (ignore: string[]) => { nuxt.hook('generate:cache:ignore', (ignore: string[]) => {
ignore.push(sigmaContext.output.dir) ignore.push(nitroContext.output.dir)
ignore.push(sigmaContext.output.serverDir) ignore.push(nitroContext.output.serverDir)
if (sigmaContext.output.publicDir) { if (nitroContext.output.publicDir) {
ignore.push(sigmaContext.output.publicDir) ignore.push(nitroContext.output.publicDir)
} }
ignore.push(...sigmaContext.ignore) ignore.push(...nitroContext.ignore)
}) })
nuxt.hook('generate:before', async () => { nuxt.hook('generate:before', async () => {
await prepare(sigmaContext) await prepare(nitroContext)
}) })
nuxt.hook('generate:extendRoutes', async () => { nuxt.hook('generate:extendRoutes', async () => {
await build(sigmaDevContext) await build(nitroDevContext)
await nuxt.server.reload() await nuxt.server.reload()
}) })
nuxt.hook('generate:done', async () => { nuxt.hook('generate:done', async () => {
await nuxt.server.close() await nuxt.server.close()
await build(sigmaContext) await build(nitroContext)
}) })
} }
function createNuxt2DevServer (sigmaContext: SigmaContext) { function createNuxt2DevServer (nitroContext: NitroContext) {
const server = createDevServer(sigmaContext) const server = createDevServer(nitroContext)
const listeners = [] const listeners = []
async function listen (port) { async function listen (port) {

View File

@ -14,7 +14,7 @@ export interface ServerMiddleware {
promisify?: boolean // Default is true promisify?: boolean // Default is true
} }
export interface SigmaContext { export interface NitroContext {
timing: boolean timing: boolean
inlineChunks: boolean inlineChunks: boolean
minify: boolean minify: boolean
@ -60,12 +60,12 @@ export interface SigmaContext {
type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> } type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> }
export interface SigmaInput extends DeepPartial<SigmaContext> {} export interface NitroInput extends DeepPartial<NitroContext> {}
export type SigmaPreset = SigmaInput | ((input: SigmaInput) => SigmaInput) export type NitroPreset = NitroInput | ((input: NitroInput) => NitroInput)
export function getSigmaContext (nuxtOptions: NuxtOptions, input: SigmaInput): SigmaContext { export function getNitroContext (nuxtOptions: NuxtOptions, input: NitroInput): NitroContext {
const defaults: SigmaContext = { const defaults: NitroContext = {
timing: true, timing: true,
inlineChunks: true, inlineChunks: true,
minify: true, minify: true,
@ -113,7 +113,7 @@ export function getSigmaContext (nuxtOptions: NuxtOptions, input: SigmaInput): S
} }
} }
defaults.preset = input.preset || process.env.SIGMA_PRESET || detectTarget() || 'server' defaults.preset = input.preset || process.env.NITRO_PRESET || detectTarget() || 'server'
let presetDefaults = PRESETS[defaults.preset] || tryImport(nuxtOptions.rootDir, defaults.preset) let presetDefaults = PRESETS[defaults.preset] || tryImport(nuxtOptions.rootDir, defaults.preset)
if (!presetDefaults) { if (!presetDefaults) {
throw new Error('Cannot resolve preset: ' + defaults.preset) throw new Error('Cannot resolve preset: ' + defaults.preset)
@ -123,16 +123,16 @@ export function getSigmaContext (nuxtOptions: NuxtOptions, input: SigmaInput): S
const _presetInput = defu(input, defaults) const _presetInput = defu(input, defaults)
// @ts-ignore // @ts-ignore
const _preset = extendPreset(input, presetDefaults)(_presetInput) const _preset = extendPreset(input, presetDefaults)(_presetInput)
const sigmaContext: SigmaContext = defu(input, _preset, defaults) as any const nitroContext: NitroContext = defu(input, _preset, defaults) as any
sigmaContext.output.dir = resolvePath(sigmaContext, sigmaContext.output.dir) nitroContext.output.dir = resolvePath(nitroContext, nitroContext.output.dir)
sigmaContext.output.publicDir = resolvePath(sigmaContext, sigmaContext.output.publicDir) nitroContext.output.publicDir = resolvePath(nitroContext, nitroContext.output.publicDir)
sigmaContext.output.serverDir = resolvePath(sigmaContext, sigmaContext.output.serverDir) nitroContext.output.serverDir = resolvePath(nitroContext, nitroContext.output.serverDir)
sigmaContext._internal.hooks.addHooks(sigmaContext.hooks) nitroContext._internal.hooks.addHooks(nitroContext.hooks)
// console.log(sigmaContext) // console.log(nitroContext)
// process.exit(1) // process.exit(1)
return sigmaContext return nitroContext
} }

View File

@ -3,14 +3,14 @@ import consola from 'consola'
import { createWriteStream } from 'fs-extra' import { createWriteStream } from 'fs-extra'
import { join, resolve } from 'upath' import { join, resolve } from 'upath'
import { prettyPath, writeFile } from '../utils' import { prettyPath, writeFile } from '../utils'
import { SigmaPreset, SigmaContext } from '../context' import { NitroPreset, NitroContext } from '../context'
export const azure: SigmaPreset = { export const azure: NitroPreset = {
inlineChunks: false, inlineChunks: false,
serveStatic: true, serveStatic: true,
entry: '{{ _internal.runtimeDir }}/entries/azure', entry: '{{ _internal.runtimeDir }}/entries/azure',
hooks: { hooks: {
async 'sigma:compiled' (ctx: SigmaContext) { async 'nitro:compiled' (ctx: NitroContext) {
await writeRoutes(ctx) await writeRoutes(ctx)
} }
} }
@ -31,7 +31,7 @@ function zipDirectory (dir: string, outfile: string): Promise<undefined> {
}) })
} }
async function writeRoutes ({ output: { dir, serverDir } }: SigmaContext) { async function writeRoutes ({ output: { dir, serverDir } }: NitroContext) {
const host = { const host = {
version: '2.0', version: '2.0',
extensions: { http: { routePrefix: '' } } extensions: { http: { routePrefix: '' } }

View File

@ -2,10 +2,10 @@ import { writeFile } from 'fs-extra'
import { resolve } from 'upath' import { resolve } from 'upath'
import consola from 'consola' import consola from 'consola'
import { extendPreset, prettyPath } from '../utils' import { extendPreset, prettyPath } from '../utils'
import { SigmaPreset, SigmaContext, SigmaInput } from '../context' import { NitroPreset, NitroContext, NitroInput } from '../context'
import { worker } from './worker' import { worker } from './worker'
export const browser: SigmaPreset = extendPreset(worker, (input: SigmaInput) => { export const browser: NitroPreset = extendPreset(worker, (input: NitroInput) => {
const routerBase = input._nuxt.routerBase const routerBase = input._nuxt.routerBase
const script = `<script> const script = `<script>
@ -47,7 +47,7 @@ if ('serviceWorker' in navigator) {
</html>` </html>`
return <SigmaInput> { return <NitroInput> {
entry: '{{ _internal.runtimeDir }}/entries/service-worker', entry: '{{ _internal.runtimeDir }}/entries/service-worker',
output: { output: {
serverDir: '{{ output.dir }}/public/_server' serverDir: '{{ output.dir }}/public/_server'
@ -61,10 +61,10 @@ if ('serviceWorker' in navigator) {
} }
}, },
hooks: { hooks: {
'sigma:template:document' (tmpl) { 'nitro:template:document' (tmpl) {
tmpl.compiled = tmpl.compiled.replace('</body>', script + '</body>') tmpl.compiled = tmpl.compiled.replace('</body>', script + '</body>')
}, },
async 'sigma:compiled' ({ output }: SigmaContext) { async 'nitro:compiled' ({ output }: NitroContext) {
await writeFile(resolve(output.publicDir, 'sw.js'), `self.importScripts('${input._nuxt.routerBase}_server/index.js');`) await writeFile(resolve(output.publicDir, 'sw.js'), `self.importScripts('${input._nuxt.routerBase}_server/index.js');`)
// Temp fix // Temp fix

View File

@ -1,14 +1,14 @@
import consola from 'consola' import consola from 'consola'
import { extendPreset, prettyPath } from '../utils' import { extendPreset, prettyPath } from '../utils'
import { SigmaPreset, SigmaContext } from '../context' import { NitroPreset, NitroContext } from '../context'
import { node } from './node' import { node } from './node'
export const cli: SigmaPreset = extendPreset(node, { export const cli: NitroPreset = extendPreset(node, {
entry: '{{ _internal.runtimeDir }}/entries/cli', entry: '{{ _internal.runtimeDir }}/entries/cli',
externals: true, externals: true,
inlineChunks: true, inlineChunks: true,
hooks: { hooks: {
'sigma:compiled' ({ output }: SigmaContext) { 'nitro:compiled' ({ output }: NitroContext) {
consola.info('Run with `node ' + prettyPath(output.serverDir) + ' [route]`') consola.info('Run with `node ' + prettyPath(output.serverDir) + ' [route]`')
} }
} }

View File

@ -1,16 +1,16 @@
import { resolve } from 'upath' import { resolve } from 'upath'
import consola from 'consola' import consola from 'consola'
import { extendPreset, writeFile, prettyPath } from '../utils' import { extendPreset, writeFile, prettyPath } from '../utils'
import { SigmaContext, SigmaPreset } from '../context' import { NitroContext, NitroPreset } from '../context'
import { worker } from './worker' import { worker } from './worker'
export const cloudflare: SigmaPreset = extendPreset(worker, { export const cloudflare: NitroPreset = extendPreset(worker, {
entry: '{{ _internal.runtimeDir }}/entries/cloudflare', entry: '{{ _internal.runtimeDir }}/entries/cloudflare',
ignore: [ ignore: [
'wrangler.toml' 'wrangler.toml'
], ],
hooks: { hooks: {
async 'sigma:compiled' ({ output, _nuxt }: SigmaContext) { async 'nitro:compiled' ({ output, _nuxt }: NitroContext) {
await writeFile(resolve(output.dir, 'package.json'), JSON.stringify({ private: true, main: './server/index.js' }, null, 2)) await writeFile(resolve(output.dir, 'package.json'), JSON.stringify({ private: true, main: './server/index.js' }, null, 2))
await writeFile(resolve(output.dir, 'package-lock.json'), JSON.stringify({ lockfileVersion: 1 }, null, 2)) await writeFile(resolve(output.dir, 'package-lock.json'), JSON.stringify({ lockfileVersion: 1 }, null, 2))
let inDir = prettyPath(_nuxt.rootDir) let inDir = prettyPath(_nuxt.rootDir)

View File

@ -1,7 +1,7 @@
import { SigmaPreset } from '../context' import { NitroPreset } from '../context'
export const lambda: SigmaPreset = { export const lambda: NitroPreset = {
entry: '{{ _internal.runtimeDir }}/entries/lambda', entry: '{{ _internal.runtimeDir }}/entries/lambda',
inlineChunks: false inlineChunks: false
} }

View File

@ -1,11 +1,11 @@
import { extendPreset } from '../utils' import { extendPreset } from '../utils'
import { SigmaPreset } from '../context' import { NitroPreset } from '../context'
import { node } from './node' import { node } from './node'
export const local: SigmaPreset = extendPreset(node, { export const local: NitroPreset = extendPreset(node, {
entry: '{{ _internal.runtimeDir }}/entries/local', entry: '{{ _internal.runtimeDir }}/entries/local',
output: { output: {
serverDir: '{{ _nuxt.buildDir }}/sigma' serverDir: '{{ _nuxt.buildDir }}/nitro'
}, },
minify: false, minify: false,
externals: { externals: {

View File

@ -1,8 +1,8 @@
import { extendPreset } from '../utils' import { extendPreset } from '../utils'
import { SigmaPreset } from '../context' import { NitroPreset } from '../context'
import { lambda } from './lambda' import { lambda } from './lambda'
export const netlify: SigmaPreset = extendPreset(lambda, { export const netlify: NitroPreset = extendPreset(lambda, {
// @ts-ignore // @ts-ignore
output: { output: {
publicDir: '{{ _nuxt.rootDir }}/dist' publicDir: '{{ _nuxt.rootDir }}/dist'

View File

@ -1,6 +1,6 @@
import { SigmaPreset } from '../context' import { NitroPreset } from '../context'
export const node: SigmaPreset = { export const node: NitroPreset = {
entry: '{{ _internal.runtimeDir }}/entries/node', entry: '{{ _internal.runtimeDir }}/entries/node',
inlineChunks: false inlineChunks: false
} }

View File

@ -1,16 +1,16 @@
import consola from 'consola' import consola from 'consola'
import { extendPreset, hl, prettyPath } from '../utils' import { extendPreset, hl, prettyPath } from '../utils'
import { SigmaPreset, SigmaContext } from '../context' import { NitroPreset, NitroContext } from '../context'
import { node } from './node' import { node } from './node'
export const server: SigmaPreset = extendPreset(node, { export const server: NitroPreset = extendPreset(node, {
entry: '{{ _internal.runtimeDir }}/entries/server', entry: '{{ _internal.runtimeDir }}/entries/server',
externals: false, externals: false,
inlineChunks: false, inlineChunks: false,
serveStatic: true, serveStatic: true,
minify: false, minify: false,
hooks: { hooks: {
'sigma:compiled' ({ output }: SigmaContext) { 'nitro:compiled' ({ output }: NitroContext) {
consola.success('Ready to run', hl('node ' + prettyPath(output.serverDir))) consola.success('Ready to run', hl('node ' + prettyPath(output.serverDir)))
} }
} }

View File

@ -1,9 +1,9 @@
import { resolve } from 'upath' import { resolve } from 'upath'
import { extendPreset, writeFile } from '../utils' import { extendPreset, writeFile } from '../utils'
import { SigmaPreset, SigmaContext } from '../context' import { NitroPreset, NitroContext } from '../context'
import { node } from './node' import { node } from './node'
export const vercel: SigmaPreset = extendPreset(node, { export const vercel: NitroPreset = extendPreset(node, {
entry: '{{ _internal.runtimeDir }}/entries/vercel', entry: '{{ _internal.runtimeDir }}/entries/vercel',
output: { output: {
dir: '{{ _nuxt.rootDir }}/.vercel_build_output', dir: '{{ _nuxt.rootDir }}/.vercel_build_output',
@ -14,13 +14,13 @@ export const vercel: SigmaPreset = extendPreset(node, {
'vercel.json' 'vercel.json'
], ],
hooks: { hooks: {
async 'sigma:compiled' (ctx: SigmaContext) { async 'nitro:compiled' (ctx: NitroContext) {
await writeRoutes(ctx) await writeRoutes(ctx)
} }
} }
}) })
async function writeRoutes ({ output }: SigmaContext) { async function writeRoutes ({ output }: NitroContext) {
const routes = [ const routes = [
{ {
src: '/sw.js', src: '/sw.js',

View File

@ -1,10 +1,10 @@
import { SigmaPreset, SigmaContext } from '../context' import { NitroPreset, NitroContext } from '../context'
export const worker: SigmaPreset = { export const worker: NitroPreset = {
entry: null, // Abstract entry: null, // Abstract
node: false, node: false,
hooks: { hooks: {
'sigma:rollup:before' ({ rollupConfig }: SigmaContext) { 'nitro:rollup:before' ({ rollupConfig }: NitroContext) {
rollupConfig.output.format = 'iife' rollupConfig.output.format = 'iife'
} }
} }

View File

@ -13,7 +13,7 @@ import analyze from 'rollup-plugin-analyzer'
import type { Preset } from '@nuxt/un' import type { Preset } from '@nuxt/un'
import * as un from '@nuxt/un' import * as un from '@nuxt/un'
import { SigmaContext } from '../context' import { NitroContext } from '../context'
import { resolvePath, MODULE_DIR } from '../utils' import { resolvePath, MODULE_DIR } from '../utils'
import { dynamicRequire } from './plugins/dynamic-require' import { dynamicRequire } from './plugins/dynamic-require'
@ -26,10 +26,10 @@ import { esbuild } from './plugins/esbuild'
export type RollupConfig = InputOptions & { output: OutputOptions } export type RollupConfig = InputOptions & { output: OutputOptions }
export const getRollupConfig = (sigmaContext: SigmaContext) => { export const getRollupConfig = (nitroContext: NitroContext) => {
const extensions: string[] = ['.ts', '.mjs', '.js', '.json', '.node'] const extensions: string[] = ['.ts', '.mjs', '.js', '.json', '.node']
const nodePreset = sigmaContext.node === false ? un.nodeless : un.node const nodePreset = nitroContext.node === false ? un.nodeless : un.node
const builtinPreset: Preset = { const builtinPreset: Preset = {
alias: { alias: {
@ -50,21 +50,21 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
} }
} }
const env = un.env(nodePreset, builtinPreset, sigmaContext.env) const env = un.env(nodePreset, builtinPreset, nitroContext.env)
delete env.alias['node-fetch'] // FIX ME delete env.alias['node-fetch'] // FIX ME
if (sigmaContext.sourceMap) { if (nitroContext.sourceMap) {
env.polyfill.push('source-map-support/register') env.polyfill.push('source-map-support/register')
} }
const buildServerDir = join(sigmaContext._nuxt.buildDir, 'dist/server') const buildServerDir = join(nitroContext._nuxt.buildDir, 'dist/server')
const runtimeAppDir = join(sigmaContext._internal.runtimeDir, 'app') const runtimeAppDir = join(nitroContext._internal.runtimeDir, 'app')
const rollupConfig: RollupConfig = { const rollupConfig: RollupConfig = {
input: resolvePath(sigmaContext, sigmaContext.entry), input: resolvePath(nitroContext, nitroContext.entry),
output: { output: {
dir: sigmaContext.output.serverDir, dir: nitroContext.output.serverDir,
entryFileNames: 'index.js', entryFileNames: 'index.js',
chunkFileNames (chunkInfo) { chunkFileNames (chunkInfo) {
let prefix = '' let prefix = ''
@ -74,22 +74,22 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
prefix = join('app', relative(buildServerDir, dirname(lastModule))) prefix = join('app', relative(buildServerDir, dirname(lastModule)))
} else if (lastModule.startsWith(runtimeAppDir)) { } else if (lastModule.startsWith(runtimeAppDir)) {
prefix = 'app' prefix = 'app'
} else if (lastModule.startsWith(sigmaContext._nuxt.buildDir)) { } else if (lastModule.startsWith(nitroContext._nuxt.buildDir)) {
prefix = 'nuxt' prefix = 'nuxt'
} else if (lastModule.startsWith(sigmaContext._internal.runtimeDir)) { } else if (lastModule.startsWith(nitroContext._internal.runtimeDir)) {
prefix = 'sigma' prefix = 'nitro'
} else if (!prefix && sigmaContext.middleware.find(m => lastModule.startsWith(m.handle))) { } else if (!prefix && nitroContext.middleware.find(m => lastModule.startsWith(m.handle))) {
prefix = 'middleware' prefix = 'middleware'
} }
return join('chunks', prefix, '[name].js') return join('chunks', prefix, '[name].js')
}, },
inlineDynamicImports: sigmaContext.inlineChunks, inlineDynamicImports: nitroContext.inlineChunks,
format: 'cjs', format: 'cjs',
exports: 'auto', exports: 'auto',
intro: '', intro: '',
outro: '', outro: '',
preferConst: true, preferConst: true,
sourcemap: sigmaContext.sourceMap, sourcemap: nitroContext.sourceMap,
sourcemapExcludeSources: true, sourcemapExcludeSources: true,
sourcemapPathTransform (relativePath, sourcemapPath) { sourcemapPathTransform (relativePath, sourcemapPath) {
return resolve(dirname(sourcemapPath), relativePath) return resolve(dirname(sourcemapPath), relativePath)
@ -104,23 +104,23 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
} }
} }
if (sigmaContext.timing) { if (nitroContext.timing) {
rollupConfig.plugins.push(timing()) rollupConfig.plugins.push(timing())
} }
// https://github.com/rollup/plugins/tree/master/packages/replace // https://github.com/rollup/plugins/tree/master/packages/replace
rollupConfig.plugins.push(replace({ rollupConfig.plugins.push(replace({
values: { values: {
'process.env.NODE_ENV': sigmaContext._nuxt.dev ? '"development"' : '"production"', 'process.env.NODE_ENV': nitroContext._nuxt.dev ? '"development"' : '"production"',
'typeof window': '"undefined"', 'typeof window': '"undefined"',
'process.env.ROUTER_BASE': JSON.stringify(sigmaContext._nuxt.routerBase), 'process.env.ROUTER_BASE': JSON.stringify(nitroContext._nuxt.routerBase),
'process.env.PUBLIC_PATH': JSON.stringify(sigmaContext._nuxt.publicPath), 'process.env.PUBLIC_PATH': JSON.stringify(nitroContext._nuxt.publicPath),
'process.env.NUXT_STATIC_BASE': JSON.stringify(sigmaContext._nuxt.staticAssets.base), 'process.env.NUXT_STATIC_BASE': JSON.stringify(nitroContext._nuxt.staticAssets.base),
'process.env.NUXT_STATIC_VERSION': JSON.stringify(sigmaContext._nuxt.staticAssets.version), 'process.env.NUXT_STATIC_VERSION': JSON.stringify(nitroContext._nuxt.staticAssets.version),
'process.env.NUXT_FULL_STATIC': sigmaContext._nuxt.fullStatic as unknown as string, 'process.env.NUXT_FULL_STATIC': nitroContext._nuxt.fullStatic as unknown as string,
'process.env.SIGMA_PRESET': JSON.stringify(sigmaContext.preset), 'process.env.NITRO_PRESET': JSON.stringify(nitroContext.preset),
'process.env.RUNTIME_CONFIG': JSON.stringify(sigmaContext._nuxt.runtimeConfig), 'process.env.RUNTIME_CONFIG': JSON.stringify(nitroContext._nuxt.runtimeConfig),
'process.env.DEBUG': JSON.stringify(sigmaContext._nuxt.dev) 'process.env.DEBUG': JSON.stringify(nitroContext._nuxt.dev)
} }
})) }))
@ -131,8 +131,8 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
// Dynamic Require Support // Dynamic Require Support
rollupConfig.plugins.push(dynamicRequire({ rollupConfig.plugins.push(dynamicRequire({
dir: resolve(sigmaContext._nuxt.buildDir, 'dist/server'), dir: resolve(nitroContext._nuxt.buildDir, 'dist/server'),
inline: sigmaContext.node === false || sigmaContext.inlineChunks, inline: nitroContext.node === false || nitroContext.inlineChunks,
globbyOptions: { globbyOptions: {
ignore: [ ignore: [
'server.js' 'server.js'
@ -141,14 +141,14 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
})) }))
// Static // Static
if (sigmaContext.serveStatic) { if (nitroContext.serveStatic) {
rollupConfig.plugins.push(dirnames()) rollupConfig.plugins.push(dirnames())
rollupConfig.plugins.push(staticAssets(sigmaContext)) rollupConfig.plugins.push(staticAssets(nitroContext))
} }
// Middleware // Middleware
const _middleware = [...sigmaContext.middleware] const _middleware = [...nitroContext.middleware]
if (sigmaContext.serveStatic) { if (nitroContext.serveStatic) {
_middleware.unshift({ route: '/', handle: '~runtime/server/static' }) _middleware.unshift({ route: '/', handle: '~runtime/server/static' })
} }
rollupConfig.plugins.push(middleware(_middleware)) rollupConfig.plugins.push(middleware(_middleware))
@ -159,37 +159,37 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
})) }))
// https://github.com/rollup/plugins/tree/master/packages/alias // https://github.com/rollup/plugins/tree/master/packages/alias
const renderer = sigmaContext.renderer || (sigmaContext._nuxt.majorVersion === 3 ? 'vue3' : 'vue2') const renderer = nitroContext.renderer || (nitroContext._nuxt.majorVersion === 3 ? 'vue3' : 'vue2')
const vue2ServerRenderer = 'vue-server-renderer/' + (sigmaContext._nuxt.dev ? 'build.dev.js' : 'build.prod.js') const vue2ServerRenderer = 'vue-server-renderer/' + (nitroContext._nuxt.dev ? 'build.dev.js' : 'build.prod.js')
rollupConfig.plugins.push(alias({ rollupConfig.plugins.push(alias({
entries: { entries: {
'~runtime': sigmaContext._internal.runtimeDir, '~runtime': nitroContext._internal.runtimeDir,
'~renderer': require.resolve(resolve(sigmaContext._internal.runtimeDir, 'app', renderer)), '~renderer': require.resolve(resolve(nitroContext._internal.runtimeDir, 'app', renderer)),
'~vueServerRenderer': vue2ServerRenderer, '~vueServerRenderer': vue2ServerRenderer,
'~build': sigmaContext._nuxt.buildDir, '~build': nitroContext._nuxt.buildDir,
...env.alias ...env.alias
} }
})) }))
const moduleDirectories = [ const moduleDirectories = [
resolve(sigmaContext._nuxt.rootDir, 'node_modules'), resolve(nitroContext._nuxt.rootDir, 'node_modules'),
resolve(MODULE_DIR, 'node_modules'), resolve(MODULE_DIR, 'node_modules'),
resolve(MODULE_DIR, '../node_modules'), resolve(MODULE_DIR, '../node_modules'),
'node_modules' 'node_modules'
] ]
// Externals Plugin // Externals Plugin
if (sigmaContext.externals) { if (nitroContext.externals) {
rollupConfig.plugins.push(externals(defu(sigmaContext.externals as any, { rollupConfig.plugins.push(externals(defu(nitroContext.externals as any, {
outDir: sigmaContext.output.serverDir, outDir: nitroContext.output.serverDir,
moduleDirectories, moduleDirectories,
ignore: [ ignore: [
sigmaContext._internal.runtimeDir, nitroContext._internal.runtimeDir,
...(sigmaContext._nuxt.dev ? [] : [sigmaContext._nuxt.buildDir]), ...(nitroContext._nuxt.dev ? [] : [nitroContext._nuxt.buildDir]),
...sigmaContext.middleware.map(m => m.handle) ...nitroContext.middleware.map(m => m.handle)
], ],
traceOptions: { traceOptions: {
base: sigmaContext._nuxt.rootDir base: nitroContext._nuxt.rootDir
} }
}))) })))
} }
@ -198,7 +198,7 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
rollupConfig.plugins.push(nodeResolve({ rollupConfig.plugins.push(nodeResolve({
extensions, extensions,
preferBuiltins: true, preferBuiltins: true,
rootDir: sigmaContext._nuxt.rootDir, rootDir: nitroContext._nuxt.rootDir,
moduleDirectories, moduleDirectories,
mainFields: ['main'] // Force resolve CJS (@vue/runtime-core ssrUtils) mainFields: ['main'] // Force resolve CJS (@vue/runtime-core ssrUtils)
})) }))
@ -217,14 +217,14 @@ export const getRollupConfig = (sigmaContext: SigmaContext) => {
// https://github.com/rollup/plugins/tree/master/packages/inject // https://github.com/rollup/plugins/tree/master/packages/inject
rollupConfig.plugins.push(inject(env.inject)) rollupConfig.plugins.push(inject(env.inject))
if (sigmaContext.analyze) { if (nitroContext.analyze) {
// https://github.com/doesdev/rollup-plugin-analyzer // https://github.com/doesdev/rollup-plugin-analyzer
rollupConfig.plugins.push(analyze()) rollupConfig.plugins.push(analyze())
} }
// https://github.com/TrySound/rollup-plugin-terser // https://github.com/TrySound/rollup-plugin-terser
// https://github.com/terser/terser#minify-sigmaContext // https://github.com/terser/terser#minify-nitroContext
if (sigmaContext.minify) { if (nitroContext.minify) {
rollupConfig.plugins.push(terser({ rollupConfig.plugins.push(terser({
mangle: { mangle: {
keep_fnames: true, keep_fnames: true,

View File

@ -5,9 +5,9 @@ import { relative, resolve } from 'upath'
import virtual from '@rollup/plugin-virtual' import virtual from '@rollup/plugin-virtual'
import globby from 'globby' import globby from 'globby'
import type { Plugin } from 'rollup' import type { Plugin } from 'rollup'
import type { SigmaContext } from '../../context' import type { NitroContext } from '../../context'
export function staticAssets (context: SigmaContext) { export function staticAssets (context: NitroContext) {
const assets: Record<string, { type: string, etag: string, mtime: string, path: string }> = {} const assets: Record<string, { type: string, etag: string, mtime: string, path: string }> = {}
const files = globby.sync('**/*.*', { cwd: context.output.publicDir, absolute: false }) const files = globby.sync('**/*.*', { cwd: context.output.publicDir, absolute: false })

View File

@ -8,11 +8,11 @@ import serveStatic from 'serve-static'
import servePlaceholder from 'serve-placeholder' import servePlaceholder from 'serve-placeholder'
import { createProxy } from 'http-proxy' import { createProxy } from 'http-proxy'
import { stat } from 'fs-extra' import { stat } from 'fs-extra'
import type { SigmaContext } from './context' import type { NitroContext } from './context'
export function createDevServer (sigmaContext: SigmaContext) { export function createDevServer (nitroContext: NitroContext) {
// Worker // Worker
const workerEntry = resolve(sigmaContext.output.dir, sigmaContext.output.serverDir, 'index.js') const workerEntry = resolve(nitroContext.output.dir, nitroContext.output.serverDir, 'index.js')
let pendingWorker: Worker let pendingWorker: Worker
let activeWorker: Worker let activeWorker: Worker
let workerAddress: string let workerAddress: string
@ -51,8 +51,8 @@ export function createDevServer (sigmaContext: SigmaContext) {
const app = createApp() const app = createApp()
// _nuxt and static // _nuxt and static
app.use(sigmaContext._nuxt.publicPath, serveStatic(resolve(sigmaContext._nuxt.buildDir, 'dist/client'))) app.use(nitroContext._nuxt.publicPath, serveStatic(resolve(nitroContext._nuxt.buildDir, 'dist/client')))
app.use(sigmaContext._nuxt.routerBase, serveStatic(resolve(sigmaContext._nuxt.staticDir))) app.use(nitroContext._nuxt.routerBase, serveStatic(resolve(nitroContext._nuxt.staticDir)))
// Dynamic Middlwware // Dynamic Middlwware
const legacyMiddleware = createDynamicMiddleware() const legacyMiddleware = createDynamicMiddleware()
@ -61,8 +61,8 @@ export function createDevServer (sigmaContext: SigmaContext) {
app.use(devMiddleware.middleware) app.use(devMiddleware.middleware)
// serve placeholder 404 assets instead of hitting SSR // serve placeholder 404 assets instead of hitting SSR
app.use(sigmaContext._nuxt.publicPath, servePlaceholder()) app.use(nitroContext._nuxt.publicPath, servePlaceholder())
app.use(sigmaContext._nuxt.routerBase, servePlaceholder({ skipUnknown: true })) app.use(nitroContext._nuxt.routerBase, servePlaceholder({ skipUnknown: true }))
// SSR Proxy // SSR Proxy
const proxy = createProxy() const proxy = createProxy()
@ -92,8 +92,8 @@ export function createDevServer (sigmaContext: SigmaContext) {
if (watcher) { return } if (watcher) { return }
const dReload = debounce(() => reload().catch(console.warn), 200, true) const dReload = debounce(() => reload().catch(console.warn), 200, true)
watcher = chokidar.watch([ watcher = chokidar.watch([
resolve(sigmaContext.output.serverDir, pattern), resolve(nitroContext.output.serverDir, pattern),
resolve(sigmaContext._nuxt.buildDir, 'dist/server', pattern) resolve(nitroContext._nuxt.buildDir, 'dist/server', pattern)
]).on('all', event => events.includes(event) && dReload()) ]).on('all', event => events.includes(event) && dReload())
} }
@ -111,7 +111,7 @@ export function createDevServer (sigmaContext: SigmaContext) {
await Promise.all(listeners.map(l => l.close())) await Promise.all(listeners.map(l => l.close()))
listeners = [] listeners = []
} }
sigmaContext._internal.hooks.hook('close', close) nitroContext._internal.hooks.hook('close', close)
return { return {
reload, reload,

View File

@ -6,7 +6,7 @@ import Hookable from 'hookable'
import consola from 'consola' import consola from 'consola'
import chalk from 'chalk' import chalk from 'chalk'
import { get } from 'dot-prop' import { get } from 'dot-prop'
import type { SigmaPreset, SigmaInput } from '../context' import type { NitroPreset, NitroInput } from '../context'
export const MODULE_DIR = resolve(__dirname, '..') export const MODULE_DIR = resolve(__dirname, '..')
@ -52,16 +52,16 @@ export async function writeFile (file, contents, log = false) {
} }
} }
export function resolvePath (sigmaContext: SigmaInput, path: string | ((sigmaContext) => string), resolveBase: string = ''): string { export function resolvePath (nitroContext: NitroInput, path: string | ((nitroContext) => string), resolveBase: string = ''): string {
if (typeof path === 'function') { if (typeof path === 'function') {
path = path(sigmaContext) path = path(nitroContext)
} }
if (typeof path !== 'string') { if (typeof path !== 'string') {
throw new TypeError('Invalid path: ' + path) throw new TypeError('Invalid path: ' + path)
} }
path = compileTemplate(path)(sigmaContext) path = compileTemplate(path)(nitroContext)
return resolve(resolveBase, path) return resolve(resolveBase, path)
} }
@ -84,8 +84,8 @@ export async function isDirectory (path: string) {
} }
} }
export function extendPreset (base: SigmaPreset, preset: SigmaPreset): SigmaPreset { export function extendPreset (base: NitroPreset, preset: NitroPreset): NitroPreset {
return (config: SigmaInput) => { return (config: NitroInput) => {
if (typeof preset === 'function') { if (typeof preset === 'function') {
preset = preset(config) preset = preset(config)
} }