Nuxt/packages/nitro/src/utils.ts

81 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-11-04 13:15:38 +00:00
import { relative, dirname, resolve } from 'path'
import { writeFile, mkdirp } from 'fs-extra'
2020-11-01 23:17:44 +00:00
import jiti from 'jiti'
import defu from 'defu'
import Hookable from 'hookable'
2020-11-06 13:46:17 +00:00
import { SLSOptions, UnresolvedPath, SLSTarget, SLSTargetFn, SLSConfig } from './config'
2020-11-01 23:17:44 +00:00
export function hl (str: string) {
return '`' + str + '`'
}
2020-11-01 23:17:44 +00:00
export function prettyPath (p: string, highlight = true) {
p = relative(process.cwd(), p)
2020-11-01 23:17:44 +00:00
return highlight ? hl(p) : p
}
export function compileTemplate (contents: string) {
return (params: Record<string, any>) => contents.replace(/{{ ?(\w+) ?}}/g, (_, match) => params[match] || '')
2020-11-03 22:14:32 +00:00
}
export function serializeTemplate (contents: string) {
2020-11-03 22:14:32 +00:00
// eslint-disable-next-line no-template-curly-in-string
return `export default (params) => \`${contents.replace(/{{ (\w+) }}/g, '${params.$1}')}\``
}
export async function writeFileP (path, contents) {
await mkdirp(dirname(path))
await writeFile(path, contents)
2020-11-03 22:14:32 +00:00
}
export function jitiImport (dir: string, path: string) {
return jiti(dir)(path)
}
export function tryImport (dir: string, path: string) {
try {
return jitiImport(dir, path)
} catch (_err) { }
}
2020-11-04 13:15:38 +00:00
export function resolvePath (options: SLSOptions, path: UnresolvedPath, resolveBase: string = '') {
if (typeof path === 'function') {
path = path(options)
}
2020-11-06 13:46:17 +00:00
if (typeof path !== 'string') {
throw new TypeError('Invalid path: ' + path)
}
path = compileTemplate(path)(options)
return resolve(resolveBase, path)
}
export function detectTarget () {
if (process.env.NETLIFY) {
return 'netlify'
}
if (process.env.VERCEL_URL) {
return 'vercel'
}
return 'node'
}
2020-11-06 13:46:17 +00:00
export function extendTarget (base: SLSTarget, target: SLSTarget): SLSTargetFn {
return (config: SLSConfig) => {
if (typeof target === 'function') {
2020-11-06 13:46:17 +00:00
target = target(config)
}
if (typeof base === 'function') {
2020-11-06 13:46:17 +00:00
base = base(config)
}
return defu({
hooks: Hookable.mergeHooks(base.hooks, target.hooks),
nuxtHooks: Hookable.mergeHooks(base.nuxtHooks as any, target.nuxtHooks as any)
}, target, base)
}
}