-
Notifications
You must be signed in to change notification settings - Fork 509
/
firebase.ts
91 lines (84 loc) · 2.6 KB
/
firebase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { createRequire } from 'module'
import { join, relative, resolve } from 'pathe'
import fse from 'fs-extra'
import { globby } from 'globby'
import { readPackageJSON } from 'pkg-types'
import { writeFile } from '../utils'
import { defineNitroPreset } from '../preset'
import type { Nitro } from '../types'
export const firebase = defineNitroPreset({
entry: '#nitro/entries/firebase',
externals: true,
commands: {
deploy: 'npx firebase deploy'
},
hooks: {
async 'nitro:compiled' (ctx) {
await writeRoutes(ctx)
}
}
})
async function writeRoutes (nitro: Nitro) {
if (!fse.existsSync(join(nitro.options.rootDir, 'firebase.json'))) {
const firebase = {
functions: {
source: relative(nitro.options.rootDir, nitro.options.srcDir)
},
hosting: [
{
site: '<your_project_id>',
public: relative(nitro.options.rootDir, nitro.options.output.publicDir),
cleanUrls: true,
rewrites: [
{
source: '**',
function: 'server'
}
]
}
]
}
await writeFile(resolve(nitro.options.rootDir, 'firebase.json'), JSON.stringify(firebase))
}
const _require = createRequire(import.meta.url)
const jsons = await globby(`${nitro.options.srcDir}/node_modules/**/package.json`)
const prefixLength = `${nitro.options.srcDir}/node_modules/`.length
const suffixLength = '/package.json'.length
const dependencies = jsons.reduce((obj, packageJson) => {
const dirname = packageJson.slice(prefixLength, -suffixLength)
if (!dirname.includes('node_modules')) {
obj[dirname] = _require(packageJson).version
}
return obj
}, {} as Record<string, string>)
let nodeVersion = '14'
try {
const currentNodeVersion = fse.readJSONSync(join(nitro.options.rootDir, 'package.json')).engines.node
if (['16', '14'].includes(currentNodeVersion)) {
nodeVersion = currentNodeVersion
}
} catch { }
const getPackageVersion = async (id) => {
const pkg = await readPackageJSON(id, { url: nitro.options.nodeModulesDirs })
return pkg.version
}
await writeFile(
resolve(nitro.options.srcDir, 'package.json'),
JSON.stringify(
{
private: true,
type: 'module',
main: './index.mjs',
dependencies,
devDependencies: {
'firebase-functions-test': 'latest',
'firebase-admin': await getPackageVersion('firebase-admin'),
'firebase-functions': await getPackageVersion('firebase-functions')
},
engines: { node: nodeVersion }
},
null,
2
)
)
}