fix(pack): lazy-load sharp and verify unpacked natives

Avoid crashing Electron at startup when sharp is corrupt, and fail pack if asarUnpack natives look truncated.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ivan Fontosh
2026-08-07 07:47:36 +08:00
parent 4456eb0277
commit 8d5a68c71e
8 changed files with 370 additions and 7 deletions
+51
View File
@@ -0,0 +1,51 @@
/**
* Lazy `sharp` load so a corrupt/missing native install does not crash Electron at import time.
* Call only from image-processing paths; errors are recoverable for the rest of the app.
*/
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
/** @type {typeof import('sharp') | null} */
let cached = null;
/** @type {Error | null} */
let loadError = null;
/**
* @param {unknown} err
* @returns {Error}
*/
export function sharpLoadFailure(err) {
const detail = err instanceof Error ? err.message : String(err);
return new Error(
[
'Не удалось загрузить модуль обработки изображений (sharp).',
'Переустановите приложение полностью (удалите и поставьте заново)',
'или исключите папку установки из проверки антивируса.',
detail ? `Детали: ${detail}` : '',
]
.filter(Boolean)
.join(' '),
);
}
/**
* @returns {typeof import('sharp')}
*/
export function getSharp() {
if (cached) return cached;
if (loadError) throw loadError;
try {
cached = require('sharp');
return cached;
} catch (err) {
loadError = sharpLoadFailure(err);
throw loadError;
}
}
/** Reset cache (tests only). */
export function __resetSharpRuntimeForTests() {
cached = null;
loadError = null;
}