signal-desktop/preload.wrapper.ts

78 lines
2 KiB
TypeScript
Raw Normal View History

// Copyright 2024 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2024-09-08 16:26:12 -07:00
import { readFileSync, writeFileSync } from 'node:fs';
2025-04-14 14:29:02 -07:00
import { join, dirname, basename } from 'node:path';
import { Script, constants } from 'node:vm';
2024-09-08 16:26:12 -07:00
import { ipcRenderer } from 'electron';
const srcPath = join(__dirname, 'preload.bundle.js');
const cachePath = join(__dirname, 'preload.bundle.cache');
let cachedData: Buffer | undefined;
try {
2025-04-14 14:29:02 -07:00
if (!process.env.GENERATE_PRELOAD_CACHE) {
cachedData = readFileSync(cachePath);
}
} catch (error) {
// No cache - no big deal
if (error.code !== 'ENOENT') {
throw error;
}
}
2025-04-14 14:29:02 -07:00
const source = readFileSync(srcPath);
2025-04-14 14:29:02 -07:00
window.preloadCompileStartTime = Date.now();
2025-04-16 09:38:40 -07:00
// `filename` is used for:
//
// - Annotating stack traces
// - Resolving dynamic `import()` calls
//
// When it is not an absolute path `import()` is resolved relative to the `cwd`.
//
// Since filename gets written into the `preload.bundle.cache` we need to use a
// path-independent value for reproducibility, and otherwise use full absolute
// path in the packaged app.
const filename = process.env.GENERATE_PRELOAD_CACHE
? 'preload.bundle.js'
: srcPath;
2025-04-14 14:29:02 -07:00
const script = new Script(
`(function(require, __dirname){${source.toString()}})`,
{
2025-04-16 09:38:40 -07:00
filename,
lineOffset: 0,
cachedData,
importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
2025-04-14 14:29:02 -07:00
}
);
2025-04-14 14:29:02 -07:00
const { cachedDataRejected } = script;
2025-04-14 14:29:02 -07:00
const fn = script.runInThisContext({
2025-04-16 09:38:40 -07:00
filename,
2025-04-14 14:29:02 -07:00
lineOffset: 0,
columnOffset: 0,
displayErrors: true,
importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
});
2025-04-03 15:24:35 -07:00
2024-09-08 16:26:12 -07:00
// See `ts/scripts/generate-preload-cache.ts`
2025-04-14 14:29:02 -07:00
if (process.env.GENERATE_PRELOAD_CACHE) {
2024-09-08 16:26:12 -07:00
writeFileSync(cachePath, script.createCachedData());
ipcRenderer.send('shutdown');
2025-04-14 14:29:02 -07:00
} else {
fn(require, __dirname);
window.SignalCI?.setPreloadCacheHit(
cachedData != null && !cachedDataRejected
);
2024-09-08 16:26:12 -07:00
}
2025-04-16 09:38:40 -07:00
if (cachedDataRejected) {
console.log('preload cache rejected');
} else {
console.log('preload cache hit');
}