import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function caseNativeAddonAbiAndRebuildCheck() {
const nodeAbi = Number(process.versions.modules);
const electronTargetAbi = 130;
const needsRebuild = nodeAbi !== electronTargetAbi;
const resolvedAddonPath = path.resolve('/app', 'build', 'Release', 'native.node');
const actual = {
hasNodeAbi: Number.isInteger(nodeAbi) && nodeAbi > 0,
needsRebuildWhenAbiDiffers: needsRebuild || electronTargetAbi === nodeAbi,
addonExt: path.extname(resolvedAddonPath),
isAbsoluteAddonPath: path.isAbsolute(resolvedAddonPath),
hasPlatformAndArch: Boolean(process.platform) && Boolean(process.arch),
};
const expected = {
hasNodeAbi: true,
needsRebuildWhenAbiDiffers: true,
addonExt: '.node',
isAbsoluteAddonPath: true,
hasPlatformAndArch: true,
};
return { name: 'native_addon_abi_and_rebuild_check', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseSystemIntegrationContracts() {
const themeState = { shouldUseDarkColors: false, changes: 0 };
const toggleTheme = (dark) => {
themeState.shouldUseDarkColors = dark;
themeState.changes += 1;
};
toggleTheme(true);
const blockers = new Map();
let nextId = 1;
const powerSaveBlocker = {
start: (type) => {
const id = nextId++;
blockers.set(id, type);
return id;
},
stop: (id) => blockers.delete(id),
isStarted: (id) => blockers.has(id),
};
const blockerId = powerSaveBlocker.start('prevent-display-sleep');
const activeWhileRunning = powerSaveBlocker.isStarted(blockerId);
powerSaveBlocker.stop(blockerId);
const activeAfterStop = powerSaveBlocker.isStarted(blockerId);
const primaryDisplay = { size: { width: 1920, height: 1080 }, scaleFactor: 1.5 };
const idleSeconds = 320;
const shouldAutoLock = idleSeconds >= 300;
const actual = {
darkAfterUpdate: themeState.shouldUseDarkColors,
themeChanges: themeState.changes,
activeWhileRunning,
activeAfterStop,
displayWidth: primaryDisplay.size.width,
shouldAutoLock,
};
const expected = {
darkAfterUpdate: true,
themeChanges: 1,
activeWhileRunning: true,
activeAfterStop: false,
displayWidth: 1920,
shouldAutoLock: true,
};
return { name: 'system_integration_contracts', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
async function caseI18nDynamicLocaleLoading() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-i18n-'));
try {
const localesDir = path.join(tmpDir, 'locales');
await fs.mkdir(localesDir);
await fs.writeFile(path.join(localesDir, 'en.json'), JSON.stringify({ hello: 'Hello', save: 'Save' }), 'utf8');
await fs.writeFile(path.join(localesDir, 'zh.json'), JSON.stringify({ hello: '你好', save: '保存' }), 'utf8');
const loadedResources = {};
let currentLng = 'en';
const loadLocale = async (lang) => {
if (!loadedResources[lang]) {
const raw = await fs.readFile(path.join(localesDir, `${lang}.json`), 'utf8');
loadedResources[lang] = JSON.parse(raw);
}
currentLng = lang;
};
const t = (key) => loadedResources[currentLng]?.[key] ?? key;
await loadLocale('en');
const enHello = t('hello');
const loadedBeforeSwitch = Object.keys(loadedResources);
await loadLocale('zh');
const zhHello = t('hello');
const loadedAfterSwitch = Object.keys(loadedResources).sort();
const actual = {
enHello,
loadedBeforeSwitch,
zhHello,
loadedAfterSwitch,
};
const expected = {
enHello: 'Hello',
loadedBeforeSwitch: ['en'],
zhHello: '你好',
loadedAfterSwitch: ['en', 'zh'],
};
return { name: 'i18n_dynamic_locale_loading', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
}
function parseDeepLink(rawUrl, allowedScheme = 'myapp') {
try {
const parsed = new URL(rawUrl);
if (parsed.protocol !== `${allowedScheme}:`) return { valid: false, reason: 'bad_scheme' };
const resource = parsed.hostname;
const segments = parsed.pathname.split('/').filter(Boolean);
if (segments.some((s) => s === '..' || s.includes('\\')) || rawUrl.includes('..')) {
return { valid: false, reason: 'path_traversal' };
}
return { valid: true, resource, id: segments[0] ?? null };
} catch {
return { valid: false, reason: 'invalid_url' };
}
}
function caseCustomProtocolAndDeepLinkSecurity() {
const validNote = parseDeepLink('myapp://note/123');
const winArgv = ['MyApp.exe', '--flag', 'myapp://note/456'];
const winUrl = winArgv.find((arg) => arg.startsWith('myapp://'));
const winParsed = parseDeepLink(winUrl);
const badTraversal = parseDeepLink('myapp://note/../../etc/passwd');
const badScheme = parseDeepLink('file:///C:/Windows/win.ini');
const actual = {
validResource: validNote.resource,
validId: validNote.id,
winArgvMatchedId: winParsed.id,
traversalReason: badTraversal.reason,
badSchemeReason: badScheme.reason,
macPlistKey: 'CFBundleURLTypes',
};
const expected = {
validResource: 'note',
validId: '123',
winArgvMatchedId: '456',
traversalReason: 'path_traversal',
badSchemeReason: 'bad_scheme',
macPlistKey: 'CFBundleURLTypes',
};
return { name: 'custom_protocol_and_deep_link_security', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseNativeAddonAbiAndRebuildCheck(),
caseSystemIntegrationContracts(),
await caseI18nDynamicLocaleLoading(),
caseCustomProtocolAndDeepLinkSecurity(),
];
console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/electron-advanced-lab/explore-advanced.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-advanced.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1078.zip