-
Notifications
You must be signed in to change notification settings - Fork 834
Expand file tree
/
Copy pathrollup.config.mjs
More file actions
659 lines (622 loc) · 16.8 KB
/
Copy pathrollup.config.mjs
File metadata and controls
659 lines (622 loc) · 16.8 KB
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import { spawn } from 'child_process';
import fs from 'fs';
import { mkdir, writeFile } from 'fs/promises';
import path from 'path';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import nodeResolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import builtinModules from 'builtin-modules';
import electron from 'electron';
import copy from 'rollup-plugin-copy';
import appManifest from './package.json' with { type: 'json' };
const NODE_ENV = process.env.NODE_ENV || 'development';
const canRun =
process.env.ROLLUP_WATCH === 'true' && process.env.NO_RUN !== 'true';
// Single shared controller across all bundle configs. Because `rollup -c -w`
// rebuilds multiple bundles on one file save, the restart is debounced so the
// whole save-batch finishes writing, then the app restarts exactly once.
const DEV_INSPECT_PORT = 9339;
const GRACEFUL_QUIT_REQUEST_TIMEOUT_MS = 2000;
// OS signals don't reach Electron's app.quit() on macOS (SIGTERM is a no-op
// there), so a graceful shutdown has to go through the Node inspector
// protocol instead. Bounded by its own timeout so a hung fetch/WebSocket
// handshake can't block killProc() from ever reaching its SIGKILL fallback.
// Resolves true once app.quit() was acknowledged by the process.
const requestGracefulQuit = () =>
new Promise((resolve) => {
let settled = false;
let ws;
let timer;
const finish = (result) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
ws?.close();
resolve(result);
};
timer = setTimeout(() => finish(false), GRACEFUL_QUIT_REQUEST_TIMEOUT_MS);
(async () => {
try {
const res = await fetch(
`http://127.0.0.1:${DEV_INSPECT_PORT}/json/list`
);
const [{ webSocketDebuggerUrl }] = await res.json();
ws = new WebSocket(webSocketDebuggerUrl);
ws.onerror = () => finish(false);
ws.onopen = () => {
ws.send(
JSON.stringify({
id: 1,
method: 'Runtime.evaluate',
params: {
expression: "process.mainModule.require('electron').app.quit()",
},
})
);
};
ws.onmessage = () => finish(true);
} catch {
finish(false); // inspector unreachable — process likely never finished booting
}
})();
});
const electronRunner = (() => {
let proc = null;
let restartTimer = null;
let starting = false;
let hasStarted = false;
const killProc = async () => {
if (!proc) {
return;
}
const current = proc;
proc = null;
const closed = new Promise((resolve) => current.once('close', resolve));
// Try a graceful app.quit() first so Electron closes windows through its
// normal lifecycle. Skipping straight to SIGKILL leaves a stale
// composited frame on screen — the OS window compositor never gets the
// close/orderOut call, so the old window appears frozen/white while the
// new one is either hidden behind it or never gets focus.
if (await requestGracefulQuit()) {
const result = await Promise.race([
closed.then(() => 'closed'),
new Promise((resolve) => setTimeout(() => resolve('timeout'), 2500)),
]);
if (result === 'closed') {
return;
}
}
current.kill('SIGKILL'); // fallback: never hang the watcher
await Promise.race([
closed,
new Promise((resolve) => setTimeout(resolve, 3000)), // never hang the watcher
]);
};
const start = async () => {
if (starting) {
return;
}
starting = true;
try {
await killProc();
console.log(
hasStarted ? 'Restarting main process...' : 'Starting main process...'
);
hasStarted = true;
const electronArgs = [`--inspect=${DEV_INSPECT_PORT}`, '.'];
// Extra Chromium/Electron switches for dev tooling, e.g.
// ELECTRON_EXTRA_LAUNCH_ARGS='--remote-debugging-port=9222' yarn start
// Shell-style tokenization: quoted segments (including embedded quotes,
// e.g. --js-flags="--a --b") stay single args, quotes stripped.
const extraArgs = (
(process.env.ELECTRON_EXTRA_LAUNCH_ARGS ?? '').match(
/(?:[^\s"']+|"[^"]*"|'[^']*')+/g
) ?? []
).map((token) =>
token.replace(/"([^"]*)"|'([^']*)'/g, (_, dq, sq) => dq ?? sq)
);
electronArgs.unshift(...extraArgs);
// Linux-specific flags for development
if (process.platform === 'linux') {
electronArgs.push('--no-sandbox');
}
const child = spawn(electron, electronArgs, { stdio: 'inherit' });
proc = child;
// Guard against a stale `close` from a process that hit the kill timeout
// firing after a newer child has already been assigned to `proc`.
child.once('close', () => {
if (proc === child) {
proc = null;
}
});
} finally {
starting = false;
}
};
return {
schedule: () => {
if (restartTimer) {
clearTimeout(restartTimer);
}
restartTimer = setTimeout(() => {
restartTimer = null;
start().catch((err) => console.error('Electron restart failed:', err));
}, 300); // debounce: coalesce a multi-bundle rebuild batch into one restart
},
};
})();
const run = () => {
if (!canRun) {
return { name: 'run-electron-noop' };
}
return {
name: 'run-electron',
writeBundle() {
electronRunner.schedule();
},
};
};
const downloadSupportedVersions = () => {
const apiUrl =
'https://releases.rocket.chat/v2/server/supportedVersions?source=desktop';
return {
writeBundle: async () => {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(
`Failed to fetch supported versions from ${apiUrl}: ${response.status} ${response.statusText}`
);
}
const json = await response.json();
const signedContent = json?.signed;
if (!signedContent) {
throw new Error(
'JSON response does not contain the expected "signed" field.'
);
}
await mkdir('./app', { recursive: true });
await writeFile('./app/supportedVersions.jwt', signedContent);
console.info('Downloaded supported versions.');
},
};
};
// rollup-plugin-copy only adds/overwrites files, it never deletes, so an
// asset removed from src/public would otherwise linger in app/ forever
// (stale tray icons surviving in dev and even packaged builds). It also
// doesn't register src/public with rollup's watcher, so regenerated
// PNG/ICO assets never trigger a rebuild/relaunch on their own. This plugin
// watches src/public directly and mirrors it into app/, purging anything
// under a mirrored subtree that no longer has a source counterpart.
const syncPublicAssets = () => {
const srcDir = path.resolve('src/public');
const destDir = path.resolve('app');
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...walk(fullPath));
} else if (entry.isFile()) {
files.push(fullPath);
}
}
return files;
};
return {
name: 'sync-public-assets',
buildStart() {
for (const filePath of walk(srcDir)) {
this.addWatchFile(filePath);
}
},
writeBundle() {
const srcFiles = walk(srcDir);
// Mirror: copy every source file to its destination, creating
// directories as needed.
for (const srcFile of srcFiles) {
const relPath = path.relative(srcDir, srcFile);
const destFile = path.join(destDir, relPath);
fs.mkdirSync(path.dirname(destFile), { recursive: true });
fs.copyFileSync(srcFile, destFile);
}
// Purge: only within subtrees mirrored from src/public (currently
// just images/), remove destination files with no source
// counterpart, then remove directories left empty.
const srcSubdirs = fs
.readdirSync(srcDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
const srcRelSet = new Set(
srcFiles.map((srcFile) => path.relative(srcDir, srcFile))
);
const purgeDir = (destSubDir) => {
if (!fs.existsSync(destSubDir)) {
return;
}
const entries = fs.readdirSync(destSubDir, { withFileTypes: true });
for (const entry of entries) {
const destPath = path.join(destSubDir, entry.name);
if (entry.isDirectory()) {
purgeDir(destPath);
if (fs.readdirSync(destPath).length === 0) {
fs.rmdirSync(destPath);
}
} else if (entry.isFile()) {
const relPath = path.relative(destDir, destPath);
if (!srcRelSet.has(relPath)) {
fs.unlinkSync(destPath);
}
}
}
};
for (const subdir of srcSubdirs) {
const destSubDir = path.join(destDir, subdir);
purgeDir(destSubDir);
}
},
};
};
const extensions = ['.js', '.ts', '.tsx'];
// Match dependency subpaths (e.g. `react-dom/client`) as external too. An
// exact-name list leaves subpath entrypoints to be bundled at build-time
// NODE_ENV while the base package resolves from the asar at runtime, which
// can mix development and production React internals and crash the renderer.
const makeExternal = (bundledModules = []) => {
const externalModules = [
...builtinModules,
...Object.keys(appManifest.dependencies),
...Object.keys(appManifest.devDependencies),
].filter((moduleName) => !bundledModules.includes(moduleName));
return (id) =>
externalModules.some(
(moduleName) => id === moduleName || id.startsWith(`${moduleName}/`)
);
};
export default [
{
external: makeExternal(['@bugsnag/js']),
input: 'src/videoCallWindow/video-call-window.ts',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/logViewerWindow/log-viewer-window.tsx',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/downloadsWindow/downloads-window.tsx',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/settingsWindow/settings-window.tsx',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/documentViewerWindow/document-viewer-window.tsx',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/screenSharing/screen-picker-window.tsx',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/videoCallWindow/preload/index.ts',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app/preload',
entryFileNames: 'preload.js',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
external: makeExternal([
'@bugsnag/js',
'marked',
'marked-highlight',
'highlight.js',
'dompurify',
]),
input: 'src/rootWindow.ts',
preserveEntrySignatures: 'strict',
plugins: [
json(),
replace({
'process.env.BUGSNAG_API_KEY': JSON.stringify(
process.env.BUGSNAG_API_KEY
),
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: {
dir: 'app',
format: 'cjs',
sourcemap: true,
interop: 'auto',
},
},
{
external: makeExternal(['@bugsnag/js']),
input: 'src/preload.ts',
plugins: [
json(),
replace({
'process.env.BUGSNAG_API_KEY': JSON.stringify(
process.env.BUGSNAG_API_KEY
),
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
],
},
{
input: 'src/injected.ts',
plugins: [
json(),
replace({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({
browser: true,
extensions,
}),
commonjs(),
run(),
],
output: [
{
dir: 'app',
format: 'iife',
sourcemap: 'inline',
},
],
},
{
external: makeExternal(),
input: 'src/main.ts',
plugins: [
copy({
targets: [
{ src: 'node_modules/@rocket.chat/icons/dist/*', dest: 'app/icons' },
],
}),
syncPublicAssets(),
downloadSupportedVersions(),
json(),
replace({
'process.env.BUGSNAG_API_KEY': JSON.stringify(
process.env.BUGSNAG_API_KEY
),
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
'preventAssignment': true,
}),
babel({
babelHelpers: 'bundled',
extensions,
}),
nodeResolve({ extensions }),
commonjs(),
run(),
],
output: {
dir: 'app',
format: 'cjs',
sourcemap: 'inline',
interop: 'auto',
},
},
];