signal-desktop/preload.wrapper.ts

64 lines
1.6 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-14 14:29:02 -07:00
const script = new Script(
`(function(require, __dirname){${source.toString()}})`,
{
filename: 'preload.bundle.js',
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
if (cachedDataRejected) {
console.log('preload cache rejected');
} else {
console.log('preload cache hit');
}
2025-04-14 14:29:02 -07:00
const fn = script.runInThisContext({
filename: 'preload.bundle.js',
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
}