-
Notifications
You must be signed in to change notification settings - Fork 546
/
Copy pathbuildWebapp.js
250 lines (234 loc) · 8.27 KB
/
buildWebapp.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/**
Exports the buildWebapp function that can be used for production builds.
*/
import { rollup } from "rollup"
import typescript from "@rollup/plugin-typescript"
import terser from "@rollup/plugin-terser"
import path from "node:path"
import { nodeResolve } from "@rollup/plugin-node-resolve"
import commonjs from "@rollup/plugin-commonjs"
import fs from "fs-extra"
import { bundleDependencyCheckPlugin, getChunkName, resolveLibs } from "./RollupConfig.js"
import os from "node:os"
import * as env from "./env.js"
import { createHtml } from "./createHtml.js"
import { domainConfigs } from "./DomainConfigs.js"
import { visualizer } from "rollup-plugin-visualizer"
import { rollupWasmLoader } from "@tutao/tuta-wasm-loader"
/**
* Builds the web app for production.
* @param version Version of the app. Will be used for html generation and service worker versioning.
* @param stage Deployment for which to build: 'prod' will build for the production system, 'test' for the test system, 'local' will use localhost.
* @param host If stage is left undefined, the value provided here will be used to construct the app URL for HTML creation.
* @param measure Function that returns the current elapsed build time.
* @param minify Boolean. Set to true to perform minification.
* @param projectDir Path to the tutanota root directory.
* @param app App to build, 'mail' for mail app and 'calendar' for calendar app
* @returns Nothing meaningful.
*/
export async function buildWebapp({ version, stage, host, measure, minify, projectDir, app }) {
const isCalendarApp = app === "calendar"
const tsConfig = isCalendarApp ? "tsconfig-calendar-app.json" : "tsconfig.json"
const buildDir = isCalendarApp ? "build-calendar-app" : "build"
const resolvedBuildDir = path.resolve(buildDir)
const entryFile = isCalendarApp ? "src/calendar-app/calendar-app.ts" : "src/mail-app/app.ts"
const workerFile = isCalendarApp ? "src/calendar-app/workerUtils/worker/calendar-worker.ts" : "src/mail-app/workerUtils/worker/mail-worker.ts"
const builtWorkerFile = isCalendarApp ? "calendar-worker.js" : "mail-worker.js"
console.log("Building app", app)
console.log("started cleaning", measure())
await fs.emptyDir(buildDir)
console.log("bundling polyfill", measure())
const polyfillBundle = await rollup({
input: ["src/polyfill.ts"],
plugins: [
typescript(),
minify && terser(),
// nodeResolve is for our own modules
nodeResolve({
preferBuiltins: true,
resolveOnly: [/^@tutao\/.*$/],
}),
commonjs(),
],
})
await polyfillBundle.write({
sourcemap: false,
format: "iife",
file: `${buildDir}/polyfill.js`,
})
console.log("started copying images", measure())
await fs.copy(path.join(projectDir, "/resources/images"), path.join(projectDir, `/${buildDir}/images`))
await fs.copy(path.join(projectDir, "/resources/favicon"), path.join(projectDir, `${buildDir}/images`))
await fs.copy(path.join(projectDir, "/resources/pdf"), path.join(projectDir, `${buildDir}/pdf`))
await fs.copy(path.join(projectDir, "/resources/wordlibrary.json"), path.join(projectDir, `${buildDir}/wordlibrary.json`))
await fs.copy(path.join(projectDir, "/src/braintree.html"), path.join(projectDir, `/${buildDir}/braintree.html`))
console.log("started bundling", measure())
const bundle = await rollup({
input: [entryFile, workerFile],
preserveEntrySignatures: false,
perf: true,
plugins: [
typescript({
tsconfig: tsConfig,
}),
resolveLibs(),
commonjs({
exclude: "src/**",
}),
minify && terser(),
analyzer(projectDir, buildDir),
visualizer({ filename: `${buildDir}/stats.html`, gzipSize: true }),
bundleDependencyCheckPlugin(),
nodeResolve({
preferBuiltins: true,
resolveOnly: [/^@tutao\/.*$/],
}),
rollupWasmLoader({
webassemblyLibraries: [
{
name: "liboqs.wasm",
command: "make -f Makefile_liboqs build",
workingDir: "libs/webassembly/",
outputPath: path.join(resolvedBuildDir, "wasm/liboqs.wasm"),
fallback: {
command: "make -f Makefile_liboqs fallback",
workingDir: "libs/webassembly/",
outputPath: path.join(resolvedBuildDir, "wasm/liboqs.js"),
},
},
{
name: "argon2.wasm",
command: "make -f Makefile_argon2 build fallback",
workingDir: "libs/webassembly/",
outputPath: path.join(resolvedBuildDir, "wasm/argon2.wasm"),
fallback: {
command: "make -f Makefile_argon2 fallback",
workingDir: "libs/webassembly/",
outputPath: path.join(resolvedBuildDir, "wasm/argon2.js"),
},
},
],
}),
],
})
console.log("bundling timings: ")
for (let [k, v] of Object.entries(bundle.getTimings())) {
console.log(k, v[0])
}
console.log("started writing bundles into", buildDir, measure())
const output = await bundle.write({
sourcemap: true,
format: "esm",
dir: buildDir,
manualChunks(id, { getModuleInfo, getModuleIds }) {
return getChunkName(id, { getModuleInfo })
},
chunkFileNames: (chunkInfo) => {
return "[name]-[hash].js"
},
})
const chunks = output.output.map((c) => c.fileName)
// we have to use System.import here because bootstrap is not executed until we actually import()
// unlike nollup+es format where it just runs on being loaded like you expect
await fs.promises.writeFile(
`${buildDir}/worker-bootstrap.js`,
`import "./polyfill.js"
import "./${builtWorkerFile}"`,
)
let restUrl
if (stage === "test") {
restUrl = "https://app.test.tuta.com"
} else if (stage === "prod") {
restUrl = "https://app.tuta.com"
} else if (stage === "local") {
restUrl = "http://" + os.hostname() + ":9000"
} else if (stage === "release") {
restUrl = undefined
} else {
// host
restUrl = host
}
await createHtml(
env.create({
staticUrl: stage === "release" || stage === "local" ? null : restUrl,
version,
mode: "Browser",
dist: true,
domainConfigs,
}),
app,
)
if (stage !== "release") {
await createHtml(env.create({ staticUrl: restUrl, version, mode: "App", dist: true, domainConfigs }), app)
}
await bundleServiceWorker(chunks, version, minify, buildDir)
}
async function bundleServiceWorker(bundles, version, minify, buildDir) {
const customDomainFileExclusions = ["index.html", "index.js"]
const filesToCache = ["index.js", "index.html", "polyfill.js", "worker-bootstrap.js"]
// we always include English
// we still cache native-common even though we don't need it because worker has to statically depend on it
.concat(
bundles.filter(
(it) =>
it.startsWith("translation-en") ||
(!it.startsWith("translation") && !it.startsWith("native-main") && !it.startsWith("SearchInPageOverlay")),
),
)
.concat(["images/logo-favicon.png", "images/logo-favicon-152.png", "images/logo-favicon-196.png", "images/font.ttf"])
const swBundle = await rollup({
input: ["src/common/serviceworker/sw.ts"],
plugins: [
typescript(),
minify && terser(),
{
name: "sw-banner",
banner() {
return `function filesToCache() { return ${JSON.stringify(filesToCache)} }
function version() { return "${version}" }
function customDomainCacheExclusions() { return ${JSON.stringify(customDomainFileExclusions)} }`
},
},
],
})
await swBundle.write({
sourcemap: true,
format: "iife",
file: `${buildDir}/sw.js`,
})
}
/**
* A little plugin to:
* - Print out each chunk size and contents
* - Create a graph file with chunk dependencies.
*/
function analyzer(projectDir, buildDir) {
return {
name: "analyze",
async generateBundle(outOpts, bundle) {
const prefix = projectDir
let buffer = "digraph G {\n"
buffer += "edge [dir=back]\n"
for (const [fileName, info] of Object.entries(bundle)) {
if (fileName.startsWith("translation")) continue
// https://www.rollupjs.org/plugin-development/#generatebundle
if (info.type === "asset") continue
for (const dep of info.imports) {
if (!dep.includes("translation")) {
buffer += `"${dep}" -> "${fileName}"\n`
}
}
console.log(fileName, "", info.code.length / 1024 + "K")
for (const module of Object.keys(info.modules)) {
if (module.includes("src/common/api/entities")) {
continue
}
const moduleName = module.startsWith(prefix) ? module.substring(prefix.length) : module
console.log("\t" + moduleName)
}
}
buffer += "}\n"
await fs.writeFile(`${buildDir}/bundles.dot`, buffer)
},
}
}