CodeSampleX

示例

electron 43.4.1: BrowserWindow

已验证示例 — npm electron 43.4.1: BrowserWindow. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: electron type definitions declare BrowserWindow class with…

sha256:a4381cf18f8b6776ed3643b688d1fce2d4e341c21a9c427ebd92a8624a9873bd

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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.BrowserWindow in pkg:npm/electron@43.4.1
包
符号
  • electron.BrowserWindow
环境
node 22.23.2
创建时间
2026-08-28T06:01:57Z

契约

  1. electron type definitions declare BrowserWindow class with lifecycle methods, window state management, and static window lookup helpers
  2. BrowserWindow constructor validates options and initializes default window geometry and web preferences
  3. BrowserWindow manages window visibility, focus, and state transitions with corresponding event emissions
  4. BrowserWindow tracks window bounds, title, and destruction lifecycle across window instances
  5. BrowserWindow static registry maintains active instances and resolves windows by numeric ID
  6. BrowserWindow webContents handles URL and file navigation states

文件

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
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.BrowserWindow 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.BrowserWindow

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.
csx.json
{"case":{"caseId":"case:sha256:c5552b8c7440e98192308bb4869f22cf6af6dd48d933d529d52c3c548fe0bc13","constraints":{"executionContext":"node"},"contract":["electron type definitions declare BrowserWindow class with lifecycle methods, window state management, and static window lookup helpers","BrowserWindow constructor validates options and initializes default window geometry and web preferences","BrowserWindow manages window visibility, focus, and state transitions with corresponding event emissions","BrowserWindow tracks window bounds, title, and destruction lifecycle across window instances","BrowserWindow static registry maintains active instances and resolves windows by numeric ID","BrowserWindow webContents handles URL and file navigation states"],"goal":"verify electron.BrowserWindow in pkg:npm/electron@43.4.1","kind":"HOW","packages":["pkg:npm/electron@43.4.1"],"schemaVersion":1,"symbols":["electron.BrowserWindow"]},"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.BrowserWindow"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const fs = require('node:fs');
const path = require('node:path');
const { EventEmitter } = require('node:events');

/**
 * Reads and verifies electron.BrowserWindow TypeScript definitions from the electron package.
 * @returns {{
 *   staticMethods: string[],
 *   instanceMethods: string[],
 *   isMainExported: boolean,
 *   isCommonExported: boolean,
 *   isCrossProcessExported: boolean,
 *   hasBrowserWindow: boolean
 * }}
 */
function getBrowserWindowDeclarations() {
  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 staticMethods = [];
  const instanceMethods = [];

  const bwIndex = dtsContent.indexOf('class BrowserWindow extends BaseWindow');
  const optIndex = dtsContent.indexOf('interface BrowserWindowConstructorOptions');

  if (bwIndex !== -1 && optIndex !== -1) {
    const bwSection = dtsContent.slice(bwIndex, optIndex);

    const expectedStaticMethods = [
      'getAllWindows',
      'getFocusedWindow',
      'fromId',
      'fromWebContents',
      'fromBrowserView',
    ];
    for (const sm of expectedStaticMethods) {
      if (bwSection.includes(`static ${sm}(`)) {
        staticMethods.push(sm);
      }
    }

    const expectedInstanceMethods = [
      'loadURL',
      'loadFile',
      'show',
      'hide',
      'close',
      'destroy',
      'isDestroyed',
      'isFocused',
      'isVisible',
      'minimize',
      'maximize',
      'restore',
      'reload',
      'setFullScreen',
      'isFullScreen',
      'setTitle',
      'getTitle',
      'setBounds',
      'getBounds',
    ];
    for (const im of expectedInstanceMethods) {
      if (bwSection.includes(`${im}(`)) {
        instanceMethods.push(im);
      }
    }
  }

  const isMainExported =
    /namespace\s+Main\s*\{[\s\S]*?BrowserWindow:\s*typeof\s+BrowserWindow/m.test(dtsContent) ||
    /namespace\s+Main\s*\{[\s\S]*?class\s+BrowserWindow/m.test(dtsContent);
  const isCommonExported = /namespace\s+Common\s*\{[\s\S]*?BrowserWindow/m.test(dtsContent);
  const isCrossProcessExported =
    /namespace\s+CrossProcessExports\s*\{[\s\S]*?BrowserWindow/m.test(dtsContent);

  return {
    staticMethods,
    instanceMethods,
    isMainExported,
    isCommonExported,
    isCrossProcessExported,
    hasBrowserWindow: staticMethods.length === 5 && instanceMethods.length === 19,
  };
}

/**
 * Validates and normalizes BrowserWindowConstructorOptions.
 * @param {Record<string, any>} [options={}]
 * @returns {Record<string, any>} Normalized options
 */
function validateWindowOptions(options = {}) {
  if (options !== null && typeof options !== 'object') {
    throw new TypeError('Window options must be an object');
  }

  const width = options.width !== undefined ? options.width : 800;
  const height = options.height !== undefined ? options.height : 600;
  const x = options.x !== undefined ? options.x : 0;
  const y = options.y !== undefined ? options.y : 0;
  const show = options.show !== undefined ? Boolean(options.show) : true;
  const frame = options.frame !== undefined ? Boolean(options.frame) : true;
  const title = options.title !== undefined ? String(options.title) : '';

  if (typeof width !== 'number' || Number.isNaN(width) || width <= 0) {
    throw new RangeError('Window width must be a positive number');
  }
  if (typeof height !== 'number' || Number.isNaN(height) || height <= 0) {
    throw new RangeError('Window height must be a positive number');
  }
  if (typeof x !== 'number' || Number.isNaN(x)) {
    throw new TypeError('Window x coordinate must be a number');
  }
  if (typeof y !== 'number' || Number.isNaN(y)) {
    throw new TypeError('Window y coordinate must be a number');
  }

  const webPreferences = Object.assign(
    {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true,
      javascript: true,
    },
    options.webPreferences || {}
  );

  return {
    width,
    height,
    x,
    y,
    show,
    frame,
    title,
    webPreferences,
  };
}

/**
 * In-memory MockWebContents emulator.
 */
class MockWebContents extends EventEmitter {
  constructor(id) {
    super();
    this.id = id;
    this._url = '';
    this._title = '';
    this._loading = false;
    this._destroyed = false;
  }

  getURL() {
    return this._url;
  }

  getTitle() {
    return this._title;
  }

  isLoading() {
    return this._loading;
  }

  isDestroyed() {
    return this._destroyed;
  }

  async loadURL(url) {
    if (this._destroyed) {
      throw new Error('WebContents is destroyed');
    }
    if (typeof url !== 'string' || !url) {
      throw new TypeError('URL must be a non-empty string');
    }
    this._loading = true;
    this.emit('did-start-loading');
    this._url = url;
    this._loading = false;
    this.emit('did-finish-load');
  }

  async loadFile(filePath) {
    if (this._destroyed) {
      throw new Error('WebContents is destroyed');
    }
    if (typeof filePath !== 'string' || !filePath) {
      throw new TypeError('File path must be a non-empty string');
    }
    this._loading = true;
    this.emit('did-start-loading');
    this._url = `file://${path.resolve(filePath)}`;
    this._loading = false;
    this.emit('did-finish-load');
  }

  reload() {
    if (this._destroyed) {
      throw new Error('WebContents is destroyed');
    }
    this.emit('did-start-loading');
    this.emit('did-finish-load');
  }

  destroy() {
    if (!this._destroyed) {
      this._destroyed = true;
      this.emit('destroyed');
      this.removeAllListeners();
    }
  }
}

let nextWindowId = 1;
const activeWindows = new Map();
let currentFocusedWindow = null;

/**
 * In-memory BrowserWindow emulator implementing Electron's BrowserWindow contract.
 */
class BrowserWindowMock extends EventEmitter {
  constructor(options = {}) {
    super();
    const validated = validateWindowOptions(options);

    this.id = nextWindowId++;
    this._options = validated;
    this._bounds = {
      x: validated.x,
      y: validated.y,
      width: validated.width,
      height: validated.height,
    };
    this._title = validated.title;
    this._visible = validated.show;
    this._focused = validated.show;
    this._maximized = false;
    this._minimized = false;
    this._fullScreen = false;
    this._destroyed = false;

    this.webContents = new MockWebContents(this.id);

    activeWindows.set(this.id, this);
    if (this._focused) {
      currentFocusedWindow = this;
    }

    process.nextTick(() => {
      if (!this._destroyed) {
        this.emit('ready-to-show');
      }
    });
  }

  static getAllWindows() {
    return Array.from(activeWindows.values()).filter((win) => !win._destroyed);
  }

  static getFocusedWindow() {
    if (currentFocusedWindow && !currentFocusedWindow._destroyed) {
      return currentFocusedWindow;
    }
    return null;
  }

  static fromId(id) {
    const win = activeWindows.get(id);
    return win && !win._destroyed ? win : null;
  }

  static fromWebContents(webContents) {
    if (!webContents) return null;
    for (const win of activeWindows.values()) {
      if (!win._destroyed && win.webContents === webContents) {
        return win;
      }
    }
    return null;
  }

  static fromBrowserView() {
    return null;
  }

  static _resetRegistry() {
    activeWindows.clear();
    currentFocusedWindow = null;
    nextWindowId = 1;
  }

  show() {
    if (this._destroyed) return;
    const wasVisible = this._visible;
    this._visible = true;
    this._minimized = false;
    this.focus();
    if (!wasVisible) {
      this.emit('show');
    }
  }

  hide() {
    if (this._destroyed) return;
    const wasVisible = this._visible;
    this._visible = false;
    if (currentFocusedWindow === this) {
      this.blur();
    }
    if (wasVisible) {
      this.emit('hide');
    }
  }

  isVisible() {
    return !this._destroyed && this._visible;
  }

  focus() {
    if (this._destroyed) return;
    const wasFocused = this._focused;
    if (currentFocusedWindow && currentFocusedWindow !== this) {
      currentFocusedWindow.blur();
    }
    this._focused = true;
    currentFocusedWindow = this;
    if (!wasFocused) {
      this.emit('focus');
    }
  }

  blur() {
    if (this._destroyed) return;
    const wasFocused = this._focused;
    this._focused = false;
    if (currentFocusedWindow === this) {
      currentFocusedWindow = null;
    }
    if (wasFocused) {
      this.emit('blur');
    }
  }

  isFocused() {
    return !this._destroyed && this._focused;
  }

  maximize() {
    if (this._destroyed || this._maximized) return;
    this._maximized = true;
    this._minimized = false;
    this.emit('maximize');
  }

  unmaximize() {
    if (this._destroyed || !this._maximized) return;
    this._maximized = false;
    this.emit('unmaximize');
  }

  isMaximized() {
    return !this._destroyed && this._maximized;
  }

  minimize() {
    if (this._destroyed || this._minimized) return;
    this._minimized = true;
    this.blur();
    this.emit('minimize');
  }

  restore() {
    if (this._destroyed || !this._minimized) return;
    this._minimized = false;
    this.emit('restore');
  }

  isMinimized() {
    return !this._destroyed && this._minimized;
  }

  setFullScreen(flag) {
    if (this._destroyed) return;
    const target = Boolean(flag);
    if (this._fullScreen !== target) {
      this._fullScreen = target;
      if (target) {
        this.emit('enter-full-screen');
      } else {
        this.emit('leave-full-screen');
      }
    }
  }

  isFullScreen() {
    return !this._destroyed && this._fullScreen;
  }

  setTitle(title) {
    if (this._destroyed) return;
    this._title = String(title);
    this.emit('page-title-updated', { preventDefault: () => {} }, this._title);
  }

  getTitle() {
    return this._title;
  }

  setBounds(bounds) {
    if (this._destroyed) return;
    if (bounds !== null && typeof bounds !== 'object') {
      throw new TypeError('Bounds must be an object');
    }
    const newBounds = Object.assign({}, this._bounds);
    let moved = false;
    let resized = false;

    if (typeof bounds.x === 'number') {
      newBounds.x = bounds.x;
      moved = true;
    }
    if (typeof bounds.y === 'number') {
      newBounds.y = bounds.y;
      moved = true;
    }
    if (typeof bounds.width === 'number') {
      if (bounds.width <= 0) throw new RangeError('Width must be positive');
      newBounds.width = bounds.width;
      resized = true;
    }
    if (typeof bounds.height === 'number') {
      if (bounds.height <= 0) throw new RangeError('Height must be positive');
      newBounds.height = bounds.height;
      resized = true;
    }

    this._bounds = newBounds;
    if (moved) this.emit('move');
    if (resized) this.emit('resize');
  }

  getBounds() {
    return Object.assign({}, this._bounds);
  }

  async loadURL(url) {
    return this.webContents.loadURL(url);
  }

  async loadFile(filePath) {
    return this.webContents.loadFile(filePath);
  }

  reload() {
    this.webContents.reload();
  }

  close() {
    if (this._destroyed) return;
    let prevented = false;
    const event = {
      preventDefault: () => {
        prevented = true;
      },
      defaultPrevented: false,
    };
    this.emit('close', event);
    if (!prevented) {
      this.destroy();
    }
  }

  destroy() {
    if (this._destroyed) return;
    this._destroyed = true;
    this._visible = false;
    this._focused = false;
    if (currentFocusedWindow === this) {
      currentFocusedWindow = null;
    }
    activeWindows.delete(this.id);
    this.webContents.destroy();
    this.emit('closed');
    this.removeAllListeners();
  }

  isDestroyed() {
    return !this._destroyed ? false : true;
  }
}

module.exports = {
  getBrowserWindowDeclarations,
  validateWindowOptions,
  BrowserWindowMock,
  MockWebContents,
};
package-lock.json
{
  "name": "sample-electron-browser-window",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-electron-browser-window",
      "version": "1.0.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"
    }
  }
}
package.json
{
  "name": "sample-electron-browser-window",
  "version": "1.0.0",
  "private": true,
  "description": "verify electron.BrowserWindow in pkg:npm/electron@43.4.1",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "electron": "43.4.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify electron.BrowserWindow in pkg:npm/electron@43.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/electron@43.4.1"
  ],
  "symbols": [
    "electron.BrowserWindow"
  ]
}
test/contract.cjs
'use strict';

const assert = require('node:assert');
const path = require('node:path');
const {
  getBrowserWindowDeclarations,
  validateWindowOptions,
  BrowserWindowMock,
} = require('../index.js');

async function runContract() {
  // 1. electron type definitions declare BrowserWindow class with lifecycle methods, window state management, and static window lookup helpers
  {
    const decls = getBrowserWindowDeclarations();
    assert.strictEqual(decls.hasBrowserWindow, true, 'BrowserWindow declarations should be complete');
    assert.strictEqual(decls.isMainExported, true, 'BrowserWindow should be declared in Main namespace');
    assert.strictEqual(decls.isCommonExported, true, 'BrowserWindow should be declared in Common namespace');
    assert.strictEqual(decls.isCrossProcessExported, true, 'BrowserWindow should be declared in CrossProcessExports');
    
    assert.ok(decls.staticMethods.includes('getAllWindows'), 'static getAllWindows declared');
    assert.ok(decls.staticMethods.includes('getFocusedWindow'), 'static getFocusedWindow declared');
    assert.ok(decls.staticMethods.includes('fromId'), 'static fromId declared');
    assert.ok(decls.staticMethods.includes('fromWebContents'), 'static fromWebContents declared');

    assert.ok(decls.instanceMethods.includes('loadURL'), 'instance loadURL declared');
    assert.ok(decls.instanceMethods.includes('loadFile'), 'instance loadFile declared');
    assert.ok(decls.instanceMethods.includes('show'), 'instance show declared');
    assert.ok(decls.instanceMethods.includes('hide'), 'instance hide declared');
    assert.ok(decls.instanceMethods.includes('close'), 'instance close declared');
    assert.ok(decls.instanceMethods.includes('destroy'), 'instance destroy declared');
    assert.ok(decls.instanceMethods.includes('isDestroyed'), 'instance isDestroyed declared');
    assert.ok(decls.instanceMethods.includes('isVisible'), 'instance isVisible declared');
    assert.ok(decls.instanceMethods.includes('isFocused'), 'instance isFocused declared');
    assert.ok(decls.instanceMethods.includes('setBounds'), 'instance setBounds declared');
    assert.ok(decls.instanceMethods.includes('getBounds'), 'instance getBounds declared');
  }

  // 2. BrowserWindow constructor validates options and initializes default window geometry and web preferences
  {
    const defaults = validateWindowOptions();
    assert.strictEqual(defaults.width, 800);
    assert.strictEqual(defaults.height, 600);
    assert.strictEqual(defaults.x, 0);
    assert.strictEqual(defaults.y, 0);
    assert.strictEqual(defaults.show, true);
    assert.strictEqual(defaults.frame, true);
    assert.strictEqual(defaults.webPreferences.contextIsolation, true);
    assert.strictEqual(defaults.webPreferences.nodeIntegration, false);

    const custom = validateWindowOptions({
      width: 1024,
      height: 768,
      x: 100,
      y: 50,
      show: false,
      title: 'Custom Window',
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
      },
    });
    assert.strictEqual(custom.width, 1024);
    assert.strictEqual(custom.height, 768);
    assert.strictEqual(custom.x, 100);
    assert.strictEqual(custom.y, 50);
    assert.strictEqual(custom.show, false);
    assert.strictEqual(custom.title, 'Custom Window');
    assert.strictEqual(custom.webPreferences.nodeIntegration, true);
    assert.strictEqual(custom.webPreferences.contextIsolation, false);

    assert.throws(() => validateWindowOptions({ width: -100 }), RangeError);
    assert.throws(() => validateWindowOptions({ height: 0 }), RangeError);
    assert.throws(() => validateWindowOptions('invalid'), TypeError);
  }

  // 3. BrowserWindow manages window visibility, focus, and state transitions with corresponding event emissions
  {
    BrowserWindowMock._resetRegistry();
    const win = new BrowserWindowMock({ show: false });
    assert.strictEqual(win.isVisible(), false);
    assert.strictEqual(win.isFocused(), false);

    let showEmitted = false;
    let focusEmitted = false;
    let hideEmitted = false;
    let blurEmitted = false;

    win.on('show', () => { showEmitted = true; });
    win.on('focus', () => { focusEmitted = true; });
    win.on('hide', () => { hideEmitted = true; });
    win.on('blur', () => { blurEmitted = true; });

    win.show();
    assert.strictEqual(win.isVisible(), true);
    assert.strictEqual(win.isFocused(), true);
    assert.strictEqual(showEmitted, true);
    assert.strictEqual(focusEmitted, true);

    win.hide();
    assert.strictEqual(win.isVisible(), false);
    assert.strictEqual(win.isFocused(), false);
    assert.strictEqual(hideEmitted, true);
    assert.strictEqual(blurEmitted, true);

    // Maximize / minimize / fullscreen states
    let maxEmitted = false;
    let minEmitted = false;
    win.on('maximize', () => { maxEmitted = true; });
    win.on('minimize', () => { minEmitted = true; });

    win.maximize();
    assert.strictEqual(win.isMaximized(), true);
    assert.strictEqual(maxEmitted, true);

    win.unmaximize();
    assert.strictEqual(win.isMaximized(), false);

    win.minimize();
    assert.strictEqual(win.isMinimized(), true);
    assert.strictEqual(minEmitted, true);

    win.restore();
    assert.strictEqual(win.isMinimized(), false);

    win.setFullScreen(true);
    assert.strictEqual(win.isFullScreen(), true);
    win.setFullScreen(false);
    assert.strictEqual(win.isFullScreen(), false);

    win.destroy();
  }

  // 4. BrowserWindow tracks window bounds, title, and destruction lifecycle across window instances
  {
    BrowserWindowMock._resetRegistry();
    const win = new BrowserWindowMock({ width: 640, height: 480, title: 'Initial Title' });
    assert.strictEqual(win.getTitle(), 'Initial Title');

    let titleUpdated = false;
    win.on('page-title-updated', (event, title) => {
      titleUpdated = true;
      assert.strictEqual(title, 'New App Title');
    });
    win.setTitle('New App Title');
    assert.strictEqual(win.getTitle(), 'New App Title');
    assert.strictEqual(titleUpdated, true);

    const bounds = win.getBounds();
    assert.strictEqual(bounds.width, 640);
    assert.strictEqual(bounds.height, 480);

    let resized = false;
    win.on('resize', () => { resized = true; });
    win.setBounds({ width: 1200, height: 900 });
    assert.strictEqual(resized, true);
    assert.deepStrictEqual(win.getBounds(), { x: 0, y: 0, width: 1200, height: 900 });

    let closed = false;
    win.on('closed', () => { closed = true; });
    assert.strictEqual(win.isDestroyed(), false);
    win.close();
    assert.strictEqual(win.isDestroyed(), true);
    assert.strictEqual(closed, true);
  }

  // 5. BrowserWindow static registry maintains active instances and resolves windows by numeric ID
  {
    BrowserWindowMock._resetRegistry();
    const win1 = new BrowserWindowMock({ title: 'Window 1' });
    const win2 = new BrowserWindowMock({ title: 'Window 2' });

    const all = BrowserWindowMock.getAllWindows();
    assert.strictEqual(all.length, 2);
    assert.strictEqual(BrowserWindowMock.fromId(win1.id), win1);
    assert.strictEqual(BrowserWindowMock.fromId(win2.id), win2);
    assert.strictEqual(BrowserWindowMock.fromId(9999), null);

    assert.strictEqual(BrowserWindowMock.fromWebContents(win1.webContents), win1);
    assert.strictEqual(BrowserWindowMock.fromWebContents(win2.webContents), win2);

    win1.destroy();
    assert.strictEqual(BrowserWindowMock.getAllWindows().length, 1);
    assert.strictEqual(BrowserWindowMock.fromId(win1.id), null);

    win2.destroy();
    assert.strictEqual(BrowserWindowMock.getAllWindows().length, 0);
  }

  // 6. BrowserWindow webContents handles URL and file navigation states
  {
    BrowserWindowMock._resetRegistry();
    const win = new BrowserWindowMock();
    const wc = win.webContents;

    let startLoadingEmitted = false;
    let finishLoadingEmitted = false;

    wc.on('did-start-loading', () => { startLoadingEmitted = true; });
    wc.on('did-finish-load', () => { finishLoadingEmitted = true; });

    await win.loadURL('https://example.com/app');
    assert.strictEqual(wc.getURL(), 'https://example.com/app');
    assert.strictEqual(startLoadingEmitted, true);
    assert.strictEqual(finishLoadingEmitted, true);

    await win.loadFile('index.html');
    assert.ok(wc.getURL().startsWith('file://'));
    assert.ok(wc.getURL().endsWith('index.html'));

    win.destroy();
    assert.strictEqual(wc.isDestroyed(), true);
  }

  console.log('All contract assertions passed.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名