示例
electron 43.4.1: ipcMain
已验证示例 — npm electron 43.4.1: ipcMain. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: electron type definitions declare IpcMain interface with handle…
sha256:9585e9ab7197d749a19741464804f0164a399c58663370ae6bebc98b0df59cff
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-28 |
案例
HOW- 目标
- verify electron.ipcMain in pkg:npm/electron@43.4.1
- 符号
-
- electron.ipcMain
- 环境
- node 22.23.2
- 创建时间
- 2026-08-28T06:08:14Z
契约
- electron type definitions declare IpcMain interface with handle, handleOnce, removeHandler, on, once, off, addListener, removeListener, and removeAllListeners methods
- ipcMain handle registers invocable channel handlers and rejects duplicate handler registration for the same channel
- ipcMain handleOnce processes a single invoke request and automatically deregisters the handler for subsequent calls
- ipcMain event listener methods on, once, and off receive IpcMainEvent with reply and returnValue capabilities
- ipcMain removeHandler and removeAllListeners successfully clear registered handlers and event listeners
文件
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.cjs
源代码
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify electron.ipcMain in pkg:npm/electron@43.4.1
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/electron@43.4.1
Demonstrate these symbols/APIs:
- electron.ipcMain
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:7f0be40f612370492db170825eeb67d551aa5ec0c95b30eff3b450f0f2e03448","constraints":{"executionContext":"node"},"contract":["electron type definitions declare IpcMain interface with handle, handleOnce, removeHandler, on, once, off, addListener, removeListener, and removeAllListeners methods","ipcMain handle registers invocable channel handlers and rejects duplicate handler registration for the same channel","ipcMain handleOnce processes a single invoke request and automatically deregisters the handler for subsequent calls","ipcMain event listener methods on, once, and off receive IpcMainEvent with reply and returnValue capabilities","ipcMain removeHandler and removeAllListeners successfully clear registered handlers and event listeners"],"goal":"verify electron.ipcMain in pkg:npm/electron@43.4.1","kind":"HOW","packages":["pkg:npm/electron@43.4.1"],"schemaVersion":1,"symbols":["electron.ipcMain"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/electron@43.4.1"],"schemaVersion":1,"subject":"pkg:npm/electron@43.4.1","symbols":["electron.ipcMain"],"verifierAdapter":"node-typescript@1"}
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { EventEmitter } = require('node:events');
/**
* Reads and verifies electron.ipcMain TypeScript definitions from the electron package.
* @returns {{
* methods: string[],
* hasAllMethods: boolean,
* isMainExported: boolean,
* isCrossProcessExported: boolean,
* hasEventInterface: boolean,
* hasInvokeEventInterface: boolean
* }}
*/
function getIpcMainDeclarations() {
const electronDir = path.dirname(require.resolve('electron/package.json'));
const dtsPath = path.join(electronDir, 'electron.d.ts');
const dtsContent = fs.readFileSync(dtsPath, 'utf-8');
const methods = [];
const interfaceMatch = dtsContent.match(/interface\s+IpcMain\s+extends\s+[^{]+\{([\s\S]*?)\}/);
if (interfaceMatch) {
const body = interfaceMatch[1];
const expectedMethods = [
'addListener',
'handle',
'handleOnce',
'off',
'on',
'once',
'removeAllListeners',
'removeHandler',
'removeListener',
];
for (const method of expectedMethods) {
if (body.includes(method)) {
methods.push(method);
}
}
}
const isMainExported = /namespace\s+Main\s*\{[\s\S]*?ipcMain:\s*IpcMain/m.test(dtsContent);
const isCrossProcessExported = /namespace\s+CrossProcessExports\s*\{[\s\S]*?ipcMain:\s*IpcMain/m.test(dtsContent);
const hasEventInterface = /interface\s+IpcMainEvent\s+extends\s+Event/m.test(dtsContent);
const hasInvokeEventInterface = /interface\s+IpcMainInvokeEvent\s+extends\s+Event/m.test(dtsContent);
return {
methods,
hasAllMethods: methods.length === 9,
isMainExported,
isCrossProcessExported,
hasEventInterface,
hasInvokeEventInterface,
};
}
/**
* In-memory IpcMain implementation adhering to Electron's IpcMain contract.
*/
class IpcMainEmulator extends EventEmitter {
constructor() {
super();
/** @type {Map<string, (event: any, ...args: any[]) => any>} */
this._handlers = new Map();
}
/**
* Adds a handler for an `invoke`able IPC.
* @param {string} channel
* @param {(event: any, ...args: any[]) => any} listener
*/
handle(channel, listener) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
if (typeof listener !== 'function') {
throw new TypeError('Listener must be a function');
}
if (this._handlers.has(channel)) {
throw new Error(`Attempted to register a second handler for '${channel}'`);
}
this._handlers.set(channel, listener);
}
/**
* Handles a single `invoke`able IPC message, then removes the listener.
* @param {string} channel
* @param {(event: any, ...args: any[]) => any} listener
*/
handleOnce(channel, listener) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
if (typeof listener !== 'function') {
throw new TypeError('Listener must be a function');
}
if (this._handlers.has(channel)) {
throw new Error(`Attempted to register a second handler for '${channel}'`);
}
const onceWrapper = async (event, ...args) => {
this.removeHandler(channel);
return listener(event, ...args);
};
this._handlers.set(channel, onceWrapper);
}
/**
* Removes any handler for channel.
* @param {string} channel
*/
removeHandler(channel) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
this._handlers.delete(channel);
}
/**
* Simulates an invocation from a renderer process (ipcRenderer.invoke).
* @param {string} channel
* @param {object} [sender]
* @param {...any} args
* @returns {Promise<any>}
*/
async invoke(channel, sender = {}, ...args) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
const handler = this._handlers.get(channel);
if (!handler) {
throw new Error(`No handler registered for '${channel}'`);
}
const event = {
frameId: 1,
processId: process.pid,
sender,
senderFrame: null,
type: 'frame',
};
return handler(event, ...args);
}
/**
* Simulates sending an asynchronous message from renderer (ipcRenderer.send).
* @param {string} channel
* @param {object} [sender]
* @param {...any} args
*/
send(channel, sender = {}, ...args) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
const event = {
frameId: 1,
processId: process.pid,
ports: [],
sender,
senderFrame: null,
type: 'frame',
reply: (replyChannel, ...replyArgs) => {
if (typeof sender.emit === 'function') {
sender.emit(replyChannel, ...replyArgs);
}
},
returnValue: undefined,
};
this.emit(channel, event, ...args);
}
/**
* Simulates sending a synchronous message from renderer (ipcRenderer.sendSync).
* @param {string} channel
* @param {object} [sender]
* @param {...any} args
* @returns {any}
*/
sendSync(channel, sender = {}, ...args) {
if (typeof channel !== 'string' || !channel) {
throw new TypeError('Channel must be a non-empty string');
}
const event = {
frameId: 1,
processId: process.pid,
ports: [],
sender,
senderFrame: null,
type: 'frame',
reply: (replyChannel, ...replyArgs) => {
if (typeof sender.emit === 'function') {
sender.emit(replyChannel, ...replyArgs);
}
},
returnValue: undefined,
};
this.emit(channel, event, ...args);
return event.returnValue;
}
}
function createIpcMain() {
return new IpcMainEmulator();
}
module.exports = {
getIpcMainDeclarations,
IpcMainEmulator,
createIpcMain,
};
{
"name": "sample-electron-ipcmain",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-electron-ipcmain",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"electron": "43.4.1"
}
},
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
"integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/get": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"license": "MIT",
"dependencies": {
"debug": "^4.1.1",
"env-paths": "^3.0.0",
"graceful-fs": "^4.2.11",
"progress": "^2.0.3",
"semver": "^7.6.3",
"sumchecker": "^3.0.1"
},
"engines": {
"node": ">=22.12.0"
},
"optionalDependencies": {
"undici": "^7.24.4"
}
},
"node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/electron": {
"version": "43.4.1",
"resolved": "https://registry.npmjs.org/electron/-/electron-43.4.1.tgz",
"integrity": "sha512-5b+EuiwkgG5iRcsEL34rimgRpkYp15SsfZOa0pC5kXs0Tb82TH4n95rpQzTZa7yRCbA7tm0WoEbuBL6NaAhAcA==",
"license": "MIT",
"dependencies": {
"@electron-internal/extract-zip": "^1.0.1",
"@electron/get": "^5.0.0",
"@types/node": "^24.9.0"
},
"bin": {
"electron": "cli.js",
"install-electron": "install.js"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
"integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
"license": "Apache-2.0",
"dependencies": {
"debug": "^4.1.0"
},
"engines": {
"node": ">= 8.0"
}
},
"node_modules/undici": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
"integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"license": "MIT"
}
}
}
{
"name": "sample-electron-ipcmain",
"version": "1.0.0",
"description": "verify electron.ipcMain in pkg:npm/electron@43.4.1",
"main": "index.js",
"license": "MIT-0",
"dependencies": {
"electron": "43.4.1"
}
}
{
"schemaVersion": 1,
"goal": "verify electron.ipcMain in pkg:npm/electron@43.4.1",
"kind": "HOW",
"packages": [
"pkg:npm/electron@43.4.1"
],
"symbols": [
"electron.ipcMain"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
'use strict';
const assert = require('node:assert');
const { EventEmitter } = require('node:events');
const {
getIpcMainDeclarations,
IpcMainEmulator,
createIpcMain,
} = require('../index.js');
async function runTests() {
// Contract 1: electron type definitions declare IpcMain interface with handle, handleOnce, removeHandler, on, once, off, addListener, removeListener, and removeAllListeners methods
{
const decl = getIpcMainDeclarations();
assert.strictEqual(decl.hasAllMethods, true, 'IpcMain interface must declare all 9 expected methods');
assert.ok(decl.methods.includes('handle'), 'Must include handle');
assert.ok(decl.methods.includes('handleOnce'), 'Must include handleOnce');
assert.ok(decl.methods.includes('removeHandler'), 'Must include removeHandler');
assert.ok(decl.methods.includes('on'), 'Must include on');
assert.ok(decl.methods.includes('once'), 'Must include once');
assert.ok(decl.methods.includes('off'), 'Must include off');
assert.ok(decl.methods.includes('addListener'), 'Must include addListener');
assert.ok(decl.methods.includes('removeListener'), 'Must include removeListener');
assert.ok(decl.methods.includes('removeAllListeners'), 'Must include removeAllListeners');
assert.strictEqual(decl.isMainExported, true, 'ipcMain must be exported in Main namespace');
assert.strictEqual(decl.isCrossProcessExported, true, 'ipcMain must be exported in CrossProcessExports namespace');
assert.strictEqual(decl.hasEventInterface, true, 'IpcMainEvent interface must be declared');
assert.strictEqual(decl.hasInvokeEventInterface, true, 'IpcMainInvokeEvent interface must be declared');
}
// Contract 2: ipcMain handle registers invocable channel handlers and rejects duplicate handler registration for the same channel
{
const ipc = createIpcMain();
// Register async invoke handler
ipc.handle('calculate-area', async (event, width, height) => {
assert.strictEqual(event.type, 'frame');
return width * height;
});
const result = await ipc.invoke('calculate-area', {}, 6, 7);
assert.strictEqual(result, 42, 'invoke must resolve with handler result');
// Registering duplicate handler must throw
assert.throws(
() => {
ipc.handle('calculate-area', async () => 0);
},
/Attempted to register a second handler for 'calculate-area'/,
'Duplicate handle registration must throw'
);
}
// Contract 3: ipcMain handleOnce processes a single invoke request and automatically deregisters the handler for subsequent calls
{
const ipc = createIpcMain();
let callCount = 0;
ipc.handleOnce('single-use-token', async (event, prefix) => {
callCount++;
return `${prefix}-token-123`;
});
const firstResult = await ipc.invoke('single-use-token', {}, 'auth');
assert.strictEqual(firstResult, 'auth-token-123');
assert.strictEqual(callCount, 1);
// Second invoke on single-use handler must fail
await assert.rejects(
async () => {
await ipc.invoke('single-use-token', {}, 'auth');
},
/No handler registered for 'single-use-token'/,
'handleOnce handler must be unregistered after first execution'
);
assert.strictEqual(callCount, 1);
}
// Contract 4: ipcMain event listener methods on, once, and off receive IpcMainEvent with reply and returnValue capabilities
{
const ipc = createIpcMain();
// Test synchronous event handling via event.returnValue
ipc.on('sync-greeting', (event, name) => {
event.returnValue = `Hello, ${name}!`;
});
const syncReply = ipc.sendSync('sync-greeting', {}, 'Alice');
assert.strictEqual(syncReply, 'Hello, Alice!', 'sendSync must receive event.returnValue');
// Test asynchronous event reply via event.reply
let receivedReply = null;
const fakeSender = new EventEmitter();
fakeSender.on('custom-reply-channel', (status, code) => {
receivedReply = { status, code };
});
ipc.on('async-task', (event, taskId) => {
event.reply('custom-reply-channel', `Completed ${taskId}`, 200);
});
ipc.send('async-task', fakeSender, 'TASK-99');
assert.deepStrictEqual(receivedReply, { status: 'Completed TASK-99', code: 200 }, 'event.reply must transmit to sender');
// Test once listener
let onceFired = 0;
ipc.once('one-time-event', () => {
onceFired++;
});
ipc.send('one-time-event', {});
ipc.send('one-time-event', {});
assert.strictEqual(onceFired, 1, 'once listener must only fire once');
// Test off listener
let offFired = 0;
const listenerToOff = () => {
offFired++;
};
ipc.on('off-event', listenerToOff);
ipc.send('off-event', {});
ipc.off('off-event', listenerToOff);
ipc.send('off-event', {});
assert.strictEqual(offFired, 1, 'off must remove listener');
}
// Contract 5: ipcMain removeHandler and removeAllListeners successfully clear registered handlers and event listeners
{
const ipc = createIpcMain();
ipc.handle('temp-action', async () => 'ready');
const initCheck = await ipc.invoke('temp-action', {});
assert.strictEqual(initCheck, 'ready');
ipc.removeHandler('temp-action');
await assert.rejects(
async () => {
await ipc.invoke('temp-action', {});
},
/No handler registered for 'temp-action'/,
'removeHandler must remove registered invoke handler'
);
// removeAllListeners
let counter = 0;
ipc.on('multi-chan', () => counter++);
ipc.on('multi-chan', () => counter++);
assert.strictEqual(ipc.listenerCount('multi-chan'), 2);
ipc.removeAllListeners('multi-chan');
assert.strictEqual(ipc.listenerCount('multi-chan'), 0);
ipc.send('multi-chan', {});
assert.strictEqual(counter, 0, 'removeAllListeners must remove all listeners for the channel');
}
console.log('All 5 contracts passed successfully.');
}
runTests().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
原始种子者
匿名