Repository: Flysoft-Studio/QQNTim Branch: dev Commit: 5cd25d12b7a8 Files: 103 Total size: 1.1 MB Directory structure: gitextract_sv6t5qoj/ ├── .gitattributes ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ └── build.yml ├── .gitignore ├── .vscode/ │ ├── extensions.json │ └── settings.json ├── .yarn/ │ └── sdks/ │ ├── integrations.yml │ └── typescript/ │ ├── bin/ │ │ ├── tsc │ │ └── tsserver │ ├── lib/ │ │ ├── tsc.js │ │ ├── tsserver.js │ │ ├── tsserverlibrary.js │ │ └── typescript.js │ └── package.json ├── COPYING ├── COPYING.LESSER ├── DEVELOPMENT.md ├── MANUAL.md ├── README.md ├── build.ts ├── examples/ │ └── NT-API/ │ ├── consts.js │ ├── qqntim.json │ ├── renderer.js │ └── settings.js ├── package.json ├── publish/ │ ├── _/ │ │ ├── install.ps1 │ │ └── uninstall.ps1 │ ├── install.cmd │ ├── install.sh │ ├── install_macos.sh │ ├── uninstall.cmd │ ├── uninstall.sh │ └── uninstall_macos.sh ├── rome.json ├── scripts/ │ ├── pack.ps1 │ ├── pack.sh │ ├── start.ps1 │ └── start.sh ├── src/ │ ├── builtins/ │ │ └── settings/ │ │ ├── package.json │ │ ├── publish/ │ │ │ ├── qqntim.json │ │ │ └── style.css │ │ ├── src/ │ │ │ ├── _renderer.tsx │ │ │ ├── exports/ │ │ │ │ ├── components.tsx │ │ │ │ └── index.ts │ │ │ ├── installer.ts │ │ │ ├── main.ts │ │ │ ├── nav.tsx │ │ │ ├── panel.tsx │ │ │ ├── qqntim-env.d.ts │ │ │ ├── renderer.ts │ │ │ └── utils/ │ │ │ ├── consts.ts │ │ │ ├── hooks.tsx │ │ │ ├── sep.ts │ │ │ └── utils.ts │ │ └── tsconfig.json │ ├── common/ │ │ ├── global.ts │ │ ├── ipc.ts │ │ ├── loader.ts │ │ ├── patch.ts │ │ ├── paths.ts │ │ ├── sep.ts │ │ ├── utils/ │ │ │ ├── console.ts │ │ │ ├── freePort.ts │ │ │ ├── ntVersion.ts │ │ │ └── process.ts │ │ ├── version.ts │ │ └── watch.ts │ ├── electron/ │ │ ├── README.txt │ │ └── package.json │ ├── main/ │ │ ├── api.ts │ │ ├── compatibility.ts │ │ ├── config.ts │ │ ├── debugger.ts │ │ ├── loader.ts │ │ ├── main.ts │ │ ├── patch.ts │ │ └── plugins.ts │ ├── qqntim-env.d.ts │ ├── renderer/ │ │ ├── api/ │ │ │ ├── app.ts │ │ │ ├── browserWindow.ts │ │ │ ├── dialog.ts │ │ │ ├── getVueId.ts │ │ │ ├── index.ts │ │ │ ├── nt/ │ │ │ │ ├── call.ts │ │ │ │ ├── constructor.ts │ │ │ │ ├── destructor.ts │ │ │ │ ├── index.ts │ │ │ │ ├── media.ts │ │ │ │ └── watcher.ts │ │ │ ├── waitForElement.ts │ │ │ └── windowLoadPromise.ts │ │ ├── debugger.ts │ │ ├── loader.ts │ │ ├── main.ts │ │ ├── patch.ts │ │ └── vueHelper.ts │ └── typings/ │ ├── COPYING │ ├── COPYING.LESSER │ ├── electron.d.ts │ ├── index.d.ts │ ├── package.json │ └── tsconfig.json └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ /.yarn/** linguist-vendored /.yarn/releases/* binary /.yarn/plugins/**/* binary /.pnp.* binary linguist-generated ================================================ FILE: .github/dependabot.yml ================================================ # To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "npm" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" ================================================ FILE: .github/workflows/build.yml ================================================ name: Build on: workflow_dispatch: push: jobs: build: runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/checkout@v3 - name: Use Node.js uses: actions/setup-node@v3 with: node-version: 18.x - name: Setup Corepack run: corepack enable - name: Cache Yarn dependencies id: yarn-cache uses: actions/cache@v3 with: path: | .yarn/cache .yarn/unplugged .yarn/install-state.gz .pnp.cjs key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-yarn- - name: Install Yarn dependencies run: yarn install - name: Build run: yarn build:linux - name: Compress files run: | mkdir upload pushd dist tar -zcvf ../upload/qqntim-build.tar.gz . zip -r9 ../upload/qqntim-build.zip . popd - name: Upload artifact uses: actions/upload-artifact@v3 with: name: build path: upload/* - name: Create release if: github.ref_type == 'tag' uses: softprops/action-gh-release@v1 with: files: upload/* generate_release_notes: true tag_name: ${{ github.ref_name }} prerelease: ${{ endsWith(github.ref_name, 'alpha') }} draft: false name: ${{ github.ref_name }} - name: Setup .yarnrc.yml if: github.ref_type == 'tag' run: | yarn config set npmRegistryServer https://registry.npmjs.org yarn config set npmAlwaysAuth true yarn config set npmAuthToken $NPM_AUTH_TOKEN env: NPM_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - name: Publish NPM Package if: github.ref_type == 'tag' run: yarn workspace @flysoftbeta/qqntim-typings npm publish ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* .pnpm-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional stylelint cache .stylelintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variable files .env .env.development.local .env.test.local .env.production.local .env.local # parcel-bundler cache (https://parceljs.org/) .cache .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # vuepress v2.x temp and cache directory .temp .cache # Docusaurus cache and generated files .docusaurus # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions # Swap the comments on the following lines if you don't wish to use zero-installs # Documentation here: https://yarnpkg.com/features/zero-installs # !.yarn/cache .pnp.* test.sh ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": ["arcanis.vscode-zipfs"] } ================================================ FILE: .vscode/settings.json ================================================ { "search.exclude": { "**/.yarn": true, "**/.pnp.*": true }, "typescript.tsdk": ".yarn/sdks/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true } ================================================ FILE: .yarn/sdks/integrations.yml ================================================ # This file is automatically generated by @yarnpkg/sdks. # Manual changes might be lost! integrations: - vscode ================================================ FILE: .yarn/sdks/typescript/bin/tsc ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/bin/tsc require(absPnpApiPath).setup(); } } // Defer to the real typescript/bin/tsc your application uses module.exports = absRequire(`typescript/bin/tsc`); ================================================ FILE: .yarn/sdks/typescript/bin/tsserver ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/bin/tsserver require(absPnpApiPath).setup(); } } // Defer to the real typescript/bin/tsserver your application uses module.exports = absRequire(`typescript/bin/tsserver`); ================================================ FILE: .yarn/sdks/typescript/lib/tsc.js ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/lib/tsc.js require(absPnpApiPath).setup(); } } // Defer to the real typescript/lib/tsc.js your application uses module.exports = absRequire(`typescript/lib/tsc.js`); ================================================ FILE: .yarn/sdks/typescript/lib/tsserver.js ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); const moduleWrapper = tsserver => { if (!process.versions.pnp) { return tsserver; } const {isAbsolute} = require(`path`); const pnpApi = require(`pnpapi`); const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); const isPortal = str => str.startsWith("portal:/"); const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { return `${locator.name}@${locator.reference}`; })); // VSCode sends the zip paths to TS using the "zip://" prefix, that TS // doesn't understand. This layer makes sure to remove the protocol // before forwarding it to TS, and to add it back on all returned paths. function toEditorPath(str) { // We add the `zip:` prefix to both `.zip/` paths and virtual paths if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { // We also take the opportunity to turn virtual paths into physical ones; // this makes it much easier to work with workspaces that list peer // dependencies, since otherwise Ctrl+Click would bring us to the virtual // file instances instead of the real ones. // // We only do this to modules owned by the the dependency tree roots. // This avoids breaking the resolution when jumping inside a vendor // with peer dep (otherwise jumping into react-dom would show resolution // errors on react). // const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; if (resolved) { const locator = pnpApi.findPackageLocator(resolved); if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { str = resolved; } } str = normalize(str); if (str.match(/\.zip\//)) { switch (hostInfo) { // Absolute VSCode `Uri.fsPath`s need to start with a slash. // VSCode only adds it automatically for supported schemes, // so we have to do it manually for the `zip` scheme. // The path needs to start with a caret otherwise VSCode doesn't handle the protocol // // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 // // 2021-10-08: VSCode changed the format in 1.61. // Before | ^zip:/c:/foo/bar.zip/package.json // After | ^/zip//c:/foo/bar.zip/package.json // // 2022-04-06: VSCode changed the format in 1.66. // Before | ^/zip//c:/foo/bar.zip/package.json // After | ^/zip/c:/foo/bar.zip/package.json // // 2022-05-06: VSCode changed the format in 1.68 // Before | ^/zip/c:/foo/bar.zip/package.json // After | ^/zip//c:/foo/bar.zip/package.json // case `vscode <1.61`: { str = `^zip:${str}`; } break; case `vscode <1.66`: { str = `^/zip/${str}`; } break; case `vscode <1.68`: { str = `^/zip${str}`; } break; case `vscode`: { str = `^/zip/${str}`; } break; // To make "go to definition" work, // We have to resolve the actual file system path from virtual path // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) case `coc-nvim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); str = resolve(`zipfile:${str}`); } break; // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) // We have to resolve the actual file system path from virtual path, // everything else is up to neovim case `neovim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); str = `zipfile://${str}`; } break; default: { str = `zip:${str}`; } break; } } else { str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`); } } return str; } function fromEditorPath(str) { switch (hostInfo) { case `coc-nvim`: { str = str.replace(/\.zip::/, `.zip/`); // The path for coc-nvim is in format of //zipfile://.yarn/... // So in order to convert it back, we use .* to match all the thing // before `zipfile:` return process.platform === `win32` ? str.replace(/^.*zipfile:\//, ``) : str.replace(/^.*zipfile:/, ``); } break; case `neovim`: { str = str.replace(/\.zip::/, `.zip/`); // The path for neovim is in format of zipfile:////.yarn/... return str.replace(/^zipfile:\/\//, ``); } break; case `vscode`: default: { return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) } break; } } // Force enable 'allowLocalPluginLoads' // TypeScript tries to resolve plugins using a path relative to itself // which doesn't work when using the global cache // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but // TypeScript already does local loads and if this code is running the user trusts the workspace // https://github.com/microsoft/vscode/issues/45856 const ConfiguredProject = tsserver.server.ConfiguredProject; const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; ConfiguredProject.prototype.enablePluginsWithOptions = function() { this.projectService.allowLocalPluginLoads = true; return originalEnablePluginsWithOptions.apply(this, arguments); }; // And here is the point where we hijack the VSCode <-> TS communications // by adding ourselves in the middle. We locate everything that looks // like an absolute path of ours and normalize it. const Session = tsserver.server.Session; const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; let hostInfo = `unknown`; Object.assign(Session.prototype, { onMessage(/** @type {string | object} */ message) { const isStringMessage = typeof message === 'string'; const parsedMessage = isStringMessage ? JSON.parse(message) : message; if ( parsedMessage != null && typeof parsedMessage === `object` && parsedMessage.arguments && typeof parsedMessage.arguments.hostInfo === `string` ) { hostInfo = parsedMessage.arguments.hostInfo; if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( // The RegExp from https://semver.org/ but without the caret at the start /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ ) ?? []).map(Number) if (major === 1) { if (minor < 61) { hostInfo += ` <1.61`; } else if (minor < 66) { hostInfo += ` <1.66`; } else if (minor < 68) { hostInfo += ` <1.68`; } } } } const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { return typeof value === 'string' ? fromEditorPath(value) : value; }); return originalOnMessage.call( this, isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) ); }, send(/** @type {any} */ msg) { return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { return typeof value === `string` ? toEditorPath(value) : value; }))); } }); return tsserver; }; if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/lib/tsserver.js require(absPnpApiPath).setup(); } } // Defer to the real typescript/lib/tsserver.js your application uses module.exports = moduleWrapper(absRequire(`typescript/lib/tsserver.js`)); ================================================ FILE: .yarn/sdks/typescript/lib/tsserverlibrary.js ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); const moduleWrapper = tsserver => { if (!process.versions.pnp) { return tsserver; } const {isAbsolute} = require(`path`); const pnpApi = require(`pnpapi`); const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); const isPortal = str => str.startsWith("portal:/"); const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { return `${locator.name}@${locator.reference}`; })); // VSCode sends the zip paths to TS using the "zip://" prefix, that TS // doesn't understand. This layer makes sure to remove the protocol // before forwarding it to TS, and to add it back on all returned paths. function toEditorPath(str) { // We add the `zip:` prefix to both `.zip/` paths and virtual paths if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { // We also take the opportunity to turn virtual paths into physical ones; // this makes it much easier to work with workspaces that list peer // dependencies, since otherwise Ctrl+Click would bring us to the virtual // file instances instead of the real ones. // // We only do this to modules owned by the the dependency tree roots. // This avoids breaking the resolution when jumping inside a vendor // with peer dep (otherwise jumping into react-dom would show resolution // errors on react). // const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; if (resolved) { const locator = pnpApi.findPackageLocator(resolved); if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { str = resolved; } } str = normalize(str); if (str.match(/\.zip\//)) { switch (hostInfo) { // Absolute VSCode `Uri.fsPath`s need to start with a slash. // VSCode only adds it automatically for supported schemes, // so we have to do it manually for the `zip` scheme. // The path needs to start with a caret otherwise VSCode doesn't handle the protocol // // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 // // 2021-10-08: VSCode changed the format in 1.61. // Before | ^zip:/c:/foo/bar.zip/package.json // After | ^/zip//c:/foo/bar.zip/package.json // // 2022-04-06: VSCode changed the format in 1.66. // Before | ^/zip//c:/foo/bar.zip/package.json // After | ^/zip/c:/foo/bar.zip/package.json // // 2022-05-06: VSCode changed the format in 1.68 // Before | ^/zip/c:/foo/bar.zip/package.json // After | ^/zip//c:/foo/bar.zip/package.json // case `vscode <1.61`: { str = `^zip:${str}`; } break; case `vscode <1.66`: { str = `^/zip/${str}`; } break; case `vscode <1.68`: { str = `^/zip${str}`; } break; case `vscode`: { str = `^/zip/${str}`; } break; // To make "go to definition" work, // We have to resolve the actual file system path from virtual path // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) case `coc-nvim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); str = resolve(`zipfile:${str}`); } break; // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) // We have to resolve the actual file system path from virtual path, // everything else is up to neovim case `neovim`: { str = normalize(resolved).replace(/\.zip\//, `.zip::`); str = `zipfile://${str}`; } break; default: { str = `zip:${str}`; } break; } } else { str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`); } } return str; } function fromEditorPath(str) { switch (hostInfo) { case `coc-nvim`: { str = str.replace(/\.zip::/, `.zip/`); // The path for coc-nvim is in format of //zipfile://.yarn/... // So in order to convert it back, we use .* to match all the thing // before `zipfile:` return process.platform === `win32` ? str.replace(/^.*zipfile:\//, ``) : str.replace(/^.*zipfile:/, ``); } break; case `neovim`: { str = str.replace(/\.zip::/, `.zip/`); // The path for neovim is in format of zipfile:////.yarn/... return str.replace(/^zipfile:\/\//, ``); } break; case `vscode`: default: { return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) } break; } } // Force enable 'allowLocalPluginLoads' // TypeScript tries to resolve plugins using a path relative to itself // which doesn't work when using the global cache // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but // TypeScript already does local loads and if this code is running the user trusts the workspace // https://github.com/microsoft/vscode/issues/45856 const ConfiguredProject = tsserver.server.ConfiguredProject; const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; ConfiguredProject.prototype.enablePluginsWithOptions = function() { this.projectService.allowLocalPluginLoads = true; return originalEnablePluginsWithOptions.apply(this, arguments); }; // And here is the point where we hijack the VSCode <-> TS communications // by adding ourselves in the middle. We locate everything that looks // like an absolute path of ours and normalize it. const Session = tsserver.server.Session; const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; let hostInfo = `unknown`; Object.assign(Session.prototype, { onMessage(/** @type {string | object} */ message) { const isStringMessage = typeof message === 'string'; const parsedMessage = isStringMessage ? JSON.parse(message) : message; if ( parsedMessage != null && typeof parsedMessage === `object` && parsedMessage.arguments && typeof parsedMessage.arguments.hostInfo === `string` ) { hostInfo = parsedMessage.arguments.hostInfo; if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( // The RegExp from https://semver.org/ but without the caret at the start /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ ) ?? []).map(Number) if (major === 1) { if (minor < 61) { hostInfo += ` <1.61`; } else if (minor < 66) { hostInfo += ` <1.66`; } else if (minor < 68) { hostInfo += ` <1.68`; } } } } const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { return typeof value === 'string' ? fromEditorPath(value) : value; }); return originalOnMessage.call( this, isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) ); }, send(/** @type {any} */ msg) { return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { return typeof value === `string` ? toEditorPath(value) : value; }))); } }); return tsserver; }; if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/lib/tsserverlibrary.js require(absPnpApiPath).setup(); } } // Defer to the real typescript/lib/tsserverlibrary.js your application uses module.exports = moduleWrapper(absRequire(`typescript/lib/tsserverlibrary.js`)); ================================================ FILE: .yarn/sdks/typescript/lib/typescript.js ================================================ #!/usr/bin/env node const {existsSync} = require(`fs`); const {createRequire} = require(`module`); const {resolve} = require(`path`); const relPnpApiPath = "../../../../.pnp.cjs"; const absPnpApiPath = resolve(__dirname, relPnpApiPath); const absRequire = createRequire(absPnpApiPath); if (existsSync(absPnpApiPath)) { if (!process.versions.pnp) { // Setup the environment to be able to require typescript/lib/typescript.js require(absPnpApiPath).setup(); } } // Defer to the real typescript/lib/typescript.js your application uses module.exports = absRequire(`typescript/lib/typescript.js`); ================================================ FILE: .yarn/sdks/typescript/package.json ================================================ { "name": "typescript", "version": "5.0.4-sdk", "main": "./lib/typescript.js", "type": "commonjs" } ================================================ FILE: COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: COPYING.LESSER ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: DEVELOPMENT.md ================================================ # 开发文档 此文档包含了插件开发文档(插件清单规范 v2.0)。 **在开始之前,强烈建议你使用我们的[插件模板仓库](https://github.com/Flysoft-Studio/QQNTim-Plugin-Template)进行开发。** 模板仓库已经包含了 TypeScript 类型定义、自动构建及发布等内容,无需手动配置。 ## 文件结构 ### 数据文件夹 请查看 [使用手册-数据文件夹](MANUAL.md#数据文件夹) 查看默认的数据文件夹路径及其修改方式。 数据文件夹存放了所有插件和设置。 以下是一个结构示意图: ``` QQNTim ├─ plugins ├─ plugins-user └─ config.json ``` ### `plugins` 文件夹 存放所有插件的文件夹。在此文件夹下的插件**对所有账户都生效**。 以下是一个结构示意图: ``` plugins ├─ 插件1 (文件夹) │ ├─ qqntim.json │ ├─ renderer.js │ └─ style.css └─ 插件2 (文件夹) ├─ qqntim.json ├─ main.js ├─ renderer.js ├─ example.jpg └─ native.node ``` ### `plugins-user` 文件夹 存放指定账户插件的文件夹。在此文件夹下的插件**只对指定账户生效**。 以下是一个结构示意图: ``` plugins-user ├─ 10000 │ ├─ 插件1 │ └─ 插件2 └─ 10001 └─ ... ``` ### `config.json` 文件 存放 QQNTim 配置的文件。 一个示例配置文件如下所示: ```json { // (可选) 插件加载相关设置 "plugins": { // 插件加载黑、白名单 // (应指定插件的 ID,可以在插件的 qqntim.json 内的 id 栏查看) // ---------------------------------------------------- // (string[] 可选) 插件加载白名单 "whitelist": [], // (string[] 可选) 插件加载黑名单 "blacklist": ["mica", "mica-ui"] // ---------------------------------------------------- } } ``` ## 插件文件夹 插件文件夹存放了所有插件和设置。 ### `qqntim.json` 文件 存放插件信息的清单文件,包含了插件的基本信息、插件加载条件、要注入的 [JS 脚本](#js-文件)等。 类型:[Manifest](#manifest) 一个完整的示例如下: ```json { "manifestVersion": "2.0", "id": "my-plugin", "name": "我的插件", "author": "Flysoft", "requirements": { "os": [ { "platform": "win32", "lte": "10.0.22621", "gte": "6.1.0" } ] }, "injections": [ { "type": "main", "script": "main.js" }, { "type": "renderer", "page": ["main", "chat"], "script": "main.js", "stylesheet": "style.css" } ] } ``` ### `*.js` 文件 脚本入口文件。 #### 主进程脚本 该脚本必须使用 CommonJS 标准默认导出一个实现 [`QQNTim.Entry.Main`](src/typings/index.d.ts) 的类。 一个示例如下: ```typescript import { QQNTim } from "@flysoftbeta/qqntim-typings"; // 例子:QQNT 启动时显示一条 Hello world! 控制台信息 // `qqntim` 内包含了很多实用的 API,可以帮助你对 QQNT 做出修改 export default class Entry implements QQNTim.Entry.Main { constructor(qqntim: QQNTim.API.Main.API) { console.log("Hello world!", qqntim); } } ``` #### 渲染进程脚本 该脚本必须使用 CommonJS 标准默认导出一个实现 `QQNTim.Entry.Renderer` 的类。 一个示例如下: ```typescript import { QQNTim } from "@flysoftbeta/qqntim-typings"; // 例子:QQNT 启动时显示一条 Hello world! 控制台信息 // `qqntim` 内包含了很多实用的 API,可以帮助你对 QQNT 做出修改 export default class Entry implements QQNTim.Entry.Renderer { constructor(qqntim: QQNTim.API.Renderer.API) { console.log("Hello world!", qqntim); } } ``` ## 类型定义 请查看 QQNTim 的 [TypeScript 类型定义文件](src/typings/index.d.ts)。此类型定义可通过安装 NPM 包 `@flysoftbeta/qqntim-typings` 添加到你的项目中。 ================================================ FILE: MANUAL.md ================================================ # 使用手册 此文档包含了使用教程。 ## 已知支持的 QQNT 版本 | 操作系统 | 最高版本 | 最低版本 | | -------- | -------- | -------- | | Windows | 9.9.1 | 9.8.0 | | Linux | 3.1.2 | 3.0.0 | | macOS | 6.9.17 (12118) | 6.9.12 (10951) | ## 安装 **请务必仔细阅读本章节内容以避免不必要的麻烦!** QQNTim 支持 LiteLoader,但**不支持 BetterQQNT**。 > ### LiteLoader 相关安装教程: > > #### 如果你已经安装了 LiteLoader,想安装 QQNTim: > > 1. **确保 LiteLoader 文件夹名称为 `LiteLoader` 或 `LiteLoaderQQNT`。否则 LiteLoader 将不会被加载!** > > 2. 到 `QQNT 根目录/resources/app` 下修改 `package.json`,将 `"LiteLoader"` 修改为 `"./app_launcher/index.js"`,之后再运行 QQNTim 的安装脚本即可。 > > #### 如果你已经安装了 QQNTim,想安装 LiteLoader: > > 请遵循 [LiteLoader 官方安装教程](https://github.com/mo-jinran/LiteLoaderQQNT/blob/main/README.md#安装方法) 进行安装即可,但请注意以下两点: > > 1. **确保 LiteLoader 文件夹名称为 `LiteLoader` 或 `LiteLoaderQQNT`。否则 LiteLoader 将不会被加载!** > > 2. **不要按照教程中的方法修改 `package.json`!否则 QQNTim 将不会加载。你只需保持它原样即可。** 安装前请确保电脑上已经安装了 QQNT。 如果你正在使用的是 **[不支持的 QQNT 版本](#已知支持的-qqnt-版本)、发现 QQNTim 无法正常使用且希望申请适配**,请通过 [附录-显示终端日志](#显示终端日志) 中提供的方法收集日志,并[向我们**提交此问题**](https://github.com/Flysoft-Studio/QQNTim/issues)。 请先从 [Releases](https://github.com/Flysoft-Studio/QQNTim/releases) 中下载最新的版本(对于一般用户,建议下载 `qqntim-build.zip`),下载后,请确保你**解压了所有文件(必须包含 `_` 文件夹)**! 在 Windows 下,请运行 `install.cmd` 安装或运行 `uninstall.cmd` 卸载。 在 Linux 下,请在安装文件夹下运行: ```bash # 安装 chmod +x ./install.sh ./install.sh # 卸载 chmod +x ./uninstall.sh ./uninstall.sh ``` 在 macOS 下,打开 `终端.app` 执行以下操作: ```zsh # 安装 chmod +x <----将 install_macos.sh 文件拖进终端窗口后按回车运行 <----将 install_macos.sh 文件拖进终端窗口后按回车运行 # 卸载 chmod +x <----将 uninstall_macos.sh 文件拖进终端窗口后按回车运行 <----将 uninstall_macos.sh 文件拖进终端窗口后按回车运行 ``` 需要输入管理员密码鉴权,同时在弹出的通知中选择允许终端修改App,或前往 `系统设置->隐私与安全性->App管理` 中打开/添加 `终端` 来允许终端修改文件。 安装后,打开 "设置" 页面: ![设置入口](.github/settings-entry.png) 如果左侧菜单出现 "QQNTim 设置",即代表安装成功: ![QQNTim 设置页面](.github/qqntim-settings-page.png) 如果此项目并未按预期出现,则可能代表 QQNTim 安装没有成功,或 QQNTim 加载失败。请通过 [附录-显示终端日志](#显示终端日志) 中提供的方法收集日志,并[向我们**提交此问题**](https://github.com/Flysoft-Studio/QQNTim/issues)。 ## 插件管理 ### 获取插件 **[Plugins Galaxy](https://github.com/FlysoftBeta/QQNTim-Plugins-Galaxy) 中拥有很多功能丰富的插件,欢迎下载。** 支持 QQNTim 3.0 及以上版本的插件: | 名称 | 说明 | 作者 | | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -------------------------------------------- | | [QQNTim-Plugin-Markdown](https://github.com/Flysoft-Studio/QQNTim-Plugin-Markdown) | 显示 Markdown 消息/LaTeX 渲染插件 | [Flysoft](https://github.com/Flysoft-Studio) | | [QQNTim-Plugin-Wallpaper](https://github.com/Flysoft-Studio/QQNTim-Plugin-Wallpaper) | 自定义你的壁纸 | [Flysoft](https://github.com/Flysoft-Studio) | | [QQNTim-Plugin-No-Revoked-Messages](https://github.com/Flysoft-Studio/QQNTim-Plugin-No-Revoked-Messages) | 支持消息持久化保存的防撤回插件 | [Flysoft](https://github.com/Flysoft-Studio) | | [QQNTim-Plugins-Galaxy](https://github.com/FlysoftBeta/QQNTim-Plugins-Galaxy) | 插件商城(注意:只有 GaussianUI 插件支持 QQNTim 3.0) | [Flysoft](https://github.com/Flysoft-Studio) | 仅支持 QQNTim 2.2 及以下版本的插件: | 名称 | 说明 | 作者 | | ----------------------------------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------- | | [QQNTim-Plugin-NTHttp](https://github.com/Rei1mu/QQNTim-Plugin-NTHttp) | WebSocket+Http 的通信实现 | [Rei1mu](https://github.com/Rei1mu) | | [QQNTim-Plugin-NoUpdate](https://github.com/Rei1mu/QQNTim-Plugin-NoUpdate) | 取消提示自动更新的烦人弹窗 | [Rei1mu](https://github.com/Rei1mu) | | [QQNTim-Plugins-Galaxy](https://github.com/FlysoftBeta/QQNTim-Plugins-Galaxy) | 插件商城(注意:壁纸插件不支持 QQNTim 2.2 及以下版本) | [Flysoft](https://github.com/Flysoft-Studio) | ### 安装插件 要安装插件,请准备一个插件**压缩包 (.zip) 或文件夹**。 结构如下图所示(每个插件结构各不相同,这里提供的结构图仅供参考): ``` 我的插件 ├─ qqntim.json ├─ renderer.js ├─ style.css └─ ... ``` 打开 "设置" 页面,选中 "插件管理": ![插件管理页面](.github/qqntim-plugin-management-page.png) 如果你登录了多个 QQ 账户,且希望某个插件只对当前账户生效,那么请点击 "仅对账号 [你的 QQ 号] 生效的插件" 右侧的安装按钮。 如果你希望插件对所有账户生效,那么请点击 "对所有账号生效的插件" 右侧的安装按钮进行安装。 **_注意:根据提示选择插件相关文件安装后,你可能需要重启 QQ 才能使这些插件开始生效。_** 安装插件后,如果插件没有按预期正常工作,请通过 [附录-显示终端日志](#显示终端日志) 中提供的方法收集日志,并向插件作者提交此问题。 ### 管理现有插件 打开 "设置" 页面,选中 "插件管理": ![插件管理页面](.github/qqntim-plugin-management-page.png) 目前,你可以启用、禁用或删除插件。 **_注意:修改设置之后需要点击 "保存并重启" 才能使设置生效。_** ## 数据文件夹 数据文件夹存放了所有插件和设置。 在 Windows 下,默认数据文件夹位于 `%UserProfile%/.qqntim`(例如:`C:/Users/[你的用户名]/.qqntim`)。 在 Linux 下,默认数据文件夹位于 `$HOME/.local/share/QQNTim`(例如:`/home/[你的用户名]/.local/share/QQNTim`,可能需要启用**显示隐藏文件**选项才能显示出来)。 你可以修改 `QQNTIM_HOME` 环境变量以修改数据文件夹的位置。 ## 附录 ### 显示终端日志 #### 在 Windows 下显示终端日志 1. 桌面右键 QQ 图标,点击 "打开文件所在位置"。 2. 在出现的文件夹窗口内按住 `Shift` 右键,点击 "在此处打开命令窗口" 或 "在此处打开 PowerShell 窗口"。 3. 在弹出的控制台窗口内输入 ".\QQ.exe" 并按下 `Enter`。 4. 日志信息将会出现在控制台窗口内。 #### 在 GNOME (Linux) 下显示终端日志 1. 按两次 `Super` 键,打开 "所有应用"。 2. 输入 "终端",并按下 `Enter`。 3. 在弹出的控制台窗口内输入 "linuxqq ; qq" 并按下 `Enter`。 4. 日志信息将会出现在控制台窗口内。 #### 在 KDE (Linux) 下显示终端日志 1. 按一次次 `Super` 键,打开 "KDE 菜单"。 2. 输入 "Konsole",并按下 `Enter`。 3. 在弹出的控制台窗口内输入 "linuxqq ; qq" 并按下 `Enter`。 4. 日志信息将会出现在控制台窗口内。 ================================================ FILE: README.md ================================================ # QQNT-Improved - PC 端 QQNT 插件管理器 此项目已废弃,我们正在全力开发全新 QQ 客户端——QPlugged,敬请期待。 [![Maintainability](https://api.codeclimate.com/v1/badges/bb8c6d1f5c2647ae38e8/maintainability)](https://codeclimate.com/github/Flysoft-Studio/QQNTim/maintainability) [![License](https://img.shields.io/github/license/FlysoftBeta/QQNTim)](https://github.com/Flysoft-Studio/QQNTim/blob/dev/COPYING.LESSER) [![Build](https://img.shields.io/github/actions/workflow/status/Flysoft-Studio/QQNTim/build.yml)](https://github.com/Flysoft-Studio/QQNTim/actions/workflows/build.yml) ![截图](.github/screenshot.png) QQNT-Improved (简称 QQNTim) 是一个给 QQNT 的插件管理器,目前处于 Alpha 版本阶段,支持 Windows,Linux 等平台 (macOS 未测试,不保证可用性)。 本程序**不提供任何担保**(包括但不限于使用导致的系统故障、封号等)。 Telegram 群组:,欢迎加入。 > QQNTim 可以与 **[LiteLoaderQQNT](https://github.com/mo-jinran/LiteLoaderQQNT)** 并存,快去试试吧! > > 请阅读 [使用手册-安装](MANUAL.md#安装) 查看如何安装。 ## 安装与使用 请查看我们的[使用手册](MANUAL.md)。 ## 插件开发 请查看我们的[开发文档](DEVELOPMENT.md)。 ## 协议 本程序使用 GNU Lesser General Public License v3.0 or later 协议发行。 请在此源代码树下的 [COPYING](./COPYING) 和 [COPYING.LESSER](./COPYING.LESSER) 查看完整的协议。 ================================================ FILE: build.ts ================================================ import { BuildOptions, build } from "esbuild"; import { copy, emptyDir, ensureDir, readdir, writeFile } from "fs-extra"; import { dirname, sep as s } from "path"; import { getAllLocators, getPackageInformation } from "pnpapi"; type Package = { packageLocation: string; packageDependencies: Map; }; type Packages = Record>; const unpackedPackages = ["chii"]; const junkFiles = [ ".d.ts", ".markdown", ".md", "/.eslintrc", "/.eslintrc.js", "/.prettierrc", "/.nycrc", ".yml", ".yaml", ".bak", "/.editorconfig", "/bower.json", "/.jscs.json", "/AUTHORS", "/LICENSE", "/License", "/yarn.lock", "/package-lock.json", ".map", ".debug.js", ".min.js", ".test.js", "/test/", "/bin/", "/tests/", "/.github/", ]; const isProduction = process.env["NODE_ENV"] == "production"; const commonOptions: Partial = { target: "node18", bundle: true, platform: "node", write: true, allowOverwrite: true, sourcemap: isProduction ? false : "inline", minify: isProduction, treeShaking: isProduction, }; async function buildBundles() { const buildPromise = Promise.all([ build({ ...commonOptions, entryPoints: [`src${s}main${s}main.ts`], outfile: `dist${s}_${s}qqntim.js`, external: ["electron", "./index.js", ...unpackedPackages], }), build({ ...commonOptions, entryPoints: [`src${s}renderer${s}main.ts`], outfile: `dist${s}_${s}qqntim-renderer.js`, external: ["electron", ...unpackedPackages], }), ]); return await buildPromise; } async function buildBuiltinPlugins() { const rootDir = `src${s}builtins`; const pluginsDir = await readdir(rootDir); await Promise.all( pluginsDir.map(async (dir) => { const pluginDir = `${rootDir}${s}${dir}`; const distDir = `dist${s}_${s}builtins${s}${dir}`; await ensureDir(pluginDir); await build({ ...commonOptions, entryPoints: [`${pluginDir}${s}src${s}main.ts`, `${pluginDir}${s}src${s}renderer.ts`], outdir: distDir, external: ["electron", "react", "react/jsx-runtime", "react-dom", "react-dom/client", "qqntim/main", "qqntim/renderer"], format: "cjs", }); await copy(`${pluginDir}${s}publish`, `${distDir}`); }), ); } async function prepareDistDir() { await emptyDir("dist"); await ensureDir(`dist${s}_`); await copy("publish", "dist"); } function collectDeps() { const packages: Packages = {}; getAllLocators().forEach((locator) => { if (!packages[locator.name]) packages[locator.name] = {}; packages[locator.name][locator.reference] = getPackageInformation(locator); }); return packages; } async function unpackPackage(packages: Packages, rootDir: string, name: string, reference?: string) { const item = packages[name]; if (!item) return; const location = item[reference ? reference : Object.keys(item)[0]]; const dir = `${rootDir}${s}node_modules${s}${name}`; await ensureDir(dir); await copy(location.packageLocation, dir, { filter: (src) => { for (const file of junkFiles) { if (src.includes(file)) return false; } return true; }, }); const promises: Promise[] = []; location.packageDependencies.forEach((depReference, depName) => { if (name == depName) return; promises.push(unpackPackage(packages, dir, depName, depReference)); }); await Promise.all(promises); } const packages = collectDeps(); prepareDistDir().then(() => Promise.all([buildBundles(), buildBuiltinPlugins(), Promise.all(unpackedPackages.map((unpackedPackage) => unpackPackage(packages, `dist${s}_`, unpackedPackage)))])); ================================================ FILE: examples/NT-API/consts.js ================================================ module.exports = { id: "example-nt-api", defaults: { showAccountInfo: true, showHistoryMessages: true, historyMessageObject: "both", autoReply: true, testInputValue: "默认值", }, }; ================================================ FILE: examples/NT-API/qqntim.json ================================================ { "manifestVersion": "3.0", "id": "example-nt-api", "name": "示例插件:NT API", "author": "Flysoft", "injections": [{ "type": "renderer", "script": "renderer.js", "page": "main" }, { "type": "renderer", "script": "settings.js", "page": "settings" }] } ================================================ FILE: examples/NT-API/renderer.js ================================================ const path = require("path"); const qqntim = require("qqntim/renderer"); const { id, defaults } = require("./consts"); module.exports.default = class Entry { constructor() { const config = qqntim.env.config.plugins?.config?.[id]; const showAccountInfo = config?.showAccountInfo != undefined ? config.showAccountInfo : defaults.showAccountInfo; const historyMessageObject = config?.historyMessageObject != undefined ? config.historyMessageObject : defaults.historyMessageObject; const showHistoryMessages = config?.showHistoryMessages != undefined ? config.showHistoryMessages : defaults.showHistoryMessages; const autoReply = config?.autoReply != undefined ? config.autoReply : defaults.autoReply; const testInputValue = config?.testInputValue != undefined ? config.testInputValue : defaults.testInputValue; //#region 示例:获取当前账号 if (showAccountInfo) qqntim.nt.getAccountInfo().then((account) => { console.log("[Example-NT-API] 当前账号信息", account); }); //#endregion //#region 示例:获取好友和群的最近 20 条历史消息 if (showHistoryMessages) { if (historyMessageObject == "friends" || historyMessageObject == "both") qqntim.nt.getFriendsList().then((list) => { console.log("[Example-NT-API] 好友列表", list); list.forEach((friend) => qqntim.nt.getPreviousMessages({ chatType: "friend", uid: friend.uid }, 20).then((messages) => qqntim.nt.getUserInfo(friend.uid).then((user) => console.log("[Example-NT-API] 好友", user, "的最近 20 条消息:", messages)))); }); if (historyMessageObject == "groups" || historyMessageObject == "both") qqntim.nt.getGroupsList().then((list) => { console.log("[Example-NT-API] 群组列表", list); list.forEach((group) => qqntim.nt.getPreviousMessages({ chatType: "group", uid: group.uid }, 20).then((messages) => console.log(`[Example-NT-API] 群组 ${group.name} (${group.uid}) 的最近 20 条消息:`, messages))); }); } //#endregion //#region 示例:自动回复 if (autoReply) qqntim.nt.on("new-messages", (messages) => { console.log("[Example-NT-API] 收到新消息:", messages); messages.forEach((message) => { if (message.peer.chatType != "friend") return; message.allDownloadedPromise.then(() => { qqntim.nt .sendMessage(message.peer, [ { type: "text", content: "收到一条来自好友的消息:", }, ...message.elements, { type: "text", content: "(此消息两秒后自动撤回)\n示例图片:", }, // 附带一个插件目录下的 example.jpg 作为图片发送 { type: "image", file: path.join(__dirname, "example.jpg"), }, ]) .then((id) => { setTimeout(() => { qqntim.nt.revokeMessage(message.peer, id); }, 2000); }); }); }); }); //#endregion console.log("[Example-NT-API] 测试消息:", testInputValue); } }; ================================================ FILE: examples/NT-API/settings.js ================================================ const { Fragment, createElement } = require("react"); const { defineSettingsPanels } = require("qqntim-settings"); const { SettingsSection, SettingsBox, SettingsBoxItem, Switch, Input, Dropdown } = require("qqntim-settings/components"); const { id, defaults } = require("./consts"); function SettingsPanel({ config, setConfig }) { return createElement( Fragment, undefined, createElement( SettingsSection, { title: "插件设置" }, createElement( SettingsBox, undefined, createElement( SettingsBoxItem, { title: "显示账户信息", description: ["在控制台中显示当前登录的账户信息。"] }, createElement(Switch, { checked: config?.[id]?.showAccountInfo != undefined ? config?.[id]?.showAccountInfo : defaults.showAccountInfo, onToggle: (state) => setConfig((prev) => { return { ...(prev || {}), [id]: { ...(prev[id] || {}), showAccountInfo: state, }, }; }), }), ), createElement( SettingsBoxItem, { title: "显示历史消息", description: ["在控制台中显示历史 20 条消息。"] }, createElement(Switch, { checked: config?.[id]?.showHistoryMessages != undefined ? config?.[id]?.showHistoryMessages : defaults.showHistoryMessages, onToggle: (state) => setConfig((prev) => { return { ...(prev || {}), [id]: { ...(prev[id] || {}), showHistoryMessages: state, }, }; }), }), ), (config?.[id]?.showHistoryMessages != undefined ? config?.[id]?.showHistoryMessages : defaults.showHistoryMessages) && createElement( SettingsBoxItem, { title: "获取历史消息的对象" }, createElement(Dropdown, { items: [ ["friends", "好友"], ["groups", "群"], ["both", "好友和群"], ], selected: config?.[id]?.historyMessageObject != undefined ? config?.[id]?.historyMessageObject : defaults.historyMessageObject, onChange: (state) => setConfig((prev) => { return { ...(prev || {}), [id]: { ...(prev[id] || {}), historyMessageObject: state, }, }; }), width: "150px", }), ), createElement( SettingsBoxItem, { title: "自动回复", description: ["自动回复私聊消息。"] }, createElement(Switch, { checked: config?.[id]?.autoReply != undefined ? config?.[id]?.autoReply : defaults.autoReply, onToggle: (state) => setConfig((prev) => { return { ...(prev || {}), [id]: { ...(prev[id] || {}), autoReply: state, }, }; }), }), ), createElement( SettingsBoxItem, { title: "测试", description: ["测试输入框。"], isLast: true }, createElement(Input, { value: config?.[id]?.testInputValue != undefined ? config?.[id]?.testInputValue : defaults.testInputValue, onChange: (state) => setConfig((prev) => { return { ...(prev || {}), [id]: { ...(prev[id] || {}), testInputValue: state, }, }; }), }), ), ), ), ); } module.exports.default = class Entry { constructor() { defineSettingsPanels([ "Example-NT-API 设置", SettingsPanel, ``, ]); } }; ================================================ FILE: package.json ================================================ { "name": "qqnt-improved", "private": true, "version": "3.1.3", "license": "LGPL-3.0-or-later", "packageManager": "yarn@3.6.1", "workspaces": ["src/electron", "src/typings", "src/builtins/*"], "scripts": { "dev": "TS_NODE_FILES=1 TS_NODE_TRANSPILE_ONLY=1 NODE_ENV=development ts-node ./build.ts", "build:win": "TS_NODE_FILES=1 TS_NODE_TRANSPILE_ONLY=1 NODE_ENV=production ts-node ./build.ts && powershell -ExecutionPolicy Unrestricted -File ./scripts/pack.ps1", "build:linux": "TS_NODE_FILES=1 TS_NODE_TRANSPILE_ONLY=1 NODE_ENV=production ts-node ./build.ts && chmod +x ./scripts/pack.sh && ./scripts/pack.sh", "install:win": "QQNTIM_INSTALLER_NO_KILL_QQ=1 cmd /c start \"\" /wait cmd /c dist\\\\install.cmd", "install:linux": "chmod +x ./dist/install.sh && QQNTIM_INSTALLER_NO_KILL_QQ=1 ./dist/install.sh", "start:win": "powershell -ExecutionPolicy Unrestricted -File ./scripts/start.ps1", "start:linux": "chmod +x ./scripts/start.sh && ./scripts/start.sh", "lint": "tsc && rome check .", "lint:apply": "rome check . --apply", "lint:apply-unsafe": "rome check . --apply-unsafe", "format": "rome format . --write" }, "dependencies": { "@electron/remote": "^2.0.11", "@flysoftbeta/qqntim-typings": "workspace:*", "axios": "^1.5.0", "chii": "^1.9.0", "electron": "workspace:*", "fs-extra": "^11.1.1", "react": "^18.2.0", "react-dom": "^18.2.0", "semver": "^7.5.4", "supports-color": "^9.4.0" }, "devDependencies": { "@types/fs-extra": "^11.0.1", "@types/node": "^20.6.2", "@types/react": "^18.2.21", "@types/react-dom": "^18.2.7", "@types/semver": "^7.5.2", "@yarnpkg/sdks": "^3.0.0-rc.50", "esbuild": "^0.19.2", "rome": "12.1.3", "ts-node": "^10.9.1", "typed-emitter": "^2.1.0", "typescript": "^5.2.2" } } ================================================ FILE: publish/_/install.ps1 ================================================ $ErrorActionPreference = "Stop" $Host.UI.RawUI.WindowTitle = "QQNTim 安装程序 (PowerShell)" Set-Location (Split-Path -Parent $MyInvocation.MyCommand.Definition) $CD = (Get-Location).Path # 判断是否拥有管理员权限 if (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) { throw "权限不足。" } } # 从注册表获取 QQ 安装路径 foreach ($RegistryPath in @("HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*")) { try { foreach ($Item in (Get-ItemProperty $RegistryPath)) { if ($Item.PSChildName -eq "QQ") { $QQInstallDir = (Split-Path -Parent $Item.UninstallString) break } } } catch {} } if (($null -eq $QQInstallDir) -or ((Test-Path $QQInstallDir) -eq $false)) { throw "未找到 QQNT 安装目录。" } $QQExecutableFile = "$QQInstallDir\QQ.exe" $QQExecutableBackupFile = "$QQInstallDir\QQ.exe.bak" $QQExecutableHashFile = "$QQInstallDir\QQ.exe.md5" $QQAppDir = "$QQInstallDir\resources\app" $QQAppLauncherDir = "$QQAppDir\app_launcher" $PackageJSONFile = "$QQAppDir\package.json" $QQNTimFlagFile = "$QQAppLauncherDir\qqntim-flag.txt" $SuccessFlagFile = "$env:TEMP\qqntim-install-successful.tmp" # 清理旧版文件,恢复被修改的入口文件 if ((Test-Path "$QQAppLauncherDir\index.js.bak") -eq $true) { Write-Output "正在清理旧版 QQNTim……" Move-Item "$QQAppLauncherDir\index.js.bak" "$QQAppLauncherDir\index.js" -Force "" | Out-File $QQNTimFlagFile -Encoding UTF8 -Force } # 询问用户,如果存在旧版则不提示 if ((Test-Path $QQNTimFlagFile) -eq $false) { if ((Read-Host "是否要安装 QQNTim (y/n)?") -notcontains "y") { throw "安装已被用户取消。" } } else { Write-Output "检测到已有安装,正在更新……" } if ($env:QQNTIM_INSTALLER_NO_KILL_QQ -ne "1") { Write-Output "正在关闭 QQ……" Stop-Process -Name QQ -ErrorAction SilentlyContinue } Write-Output "正在复制文件……" # 如果 node_modules 不存在或已经过期则执行复制 if ((Test-Path .\node_modules.zip.md5) -eq $true -and (Test-Path .\node_modules.zip) -eq $true) { if ((Test-Path "$QQAppLauncherDir\node_modules.zip.md5") -eq $false -or (Get-Content "$QQAppLauncherDir\node_modules.zip.md5" -Encoding UTF8 -Force) -ne (Get-Content .\node_modules.zip.md5 -Encoding UTF8 -Force)) { $SourceZipPath = "$CD\node_modules.zip"; $DestinationDirPath = "$QQAppLauncherDir\node_modules" # 清空原有 node_modules 文件夹 if ((Test-Path $DestinationDirPath) -eq $true) { Remove-Item $DestinationDirPath -Recurse -Force } New-Item $DestinationDirPath -ItemType Directory -Force | Out-Null try { # 回退 1 - 仅支持 .NET Framework 4.5 及以上 Add-Type -AssemblyName System.IO.Compression.Filesystem [System.IO.Compression.ZipFile]::ExtractToDirectory($SourceZipPath, $DestinationDirPath) } catch { # 回退 2 - 使用系统 COM 复制 API $Shell = New-Object -ComObject Shell.Application $Shell.NameSpace($DestinationDirPath).CopyHere($Shell.NameSpace($SourceZipPath).Items()) } } Copy-Item ".\node_modules.zip.md5" $QQAppLauncherDir -Recurse -Force } elseif ((Test-Path .\node_modules) -eq $true) { Copy-Item ".\node_modules" $QQAppLauncherDir -Recurse -Force } Copy-Item ".\qqntim.js", ".\qqntim-renderer.js", ".\builtins" $QQAppLauncherDir -Recurse -Force Write-Output "正在修补 package.json……" # 使用 UTF-8 without BOM 进行保存 $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False [System.IO.File]::WriteAllLines($PackageJSONFile, ((Get-Content $PackageJSONFile -Encoding UTF8 -Force) -replace "./app_launcher/index.js", "./app_launcher/qqntim.js"), $Utf8NoBomEncoding) # For QQ 9.9.1+ # 如果 QQ.exe 未被修补或已被新安装覆盖则进行修补 if ((Test-Path $QQExecutableHashFile) -eq $false -or (Get-Content $QQExecutableHashFile -Encoding UTF8 -Force) -replace "`r`n", "" -ne (Get-FileHash $QQExecutableFile -Algorithm MD5).Hash) { Write-Output "正在修补 QQ.exe,这可能需要一些时间……" Copy-Item $QQExecutableFile $QQExecutableBackupFile -Force # 引入 crypt32.dll 定义 $Crypt32Def = @" [DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptStringToBinary( string pszString, int cchString, int dwFlags, byte[] pbBinary, ref int pcbBinary, int pdwSkip, ref int pdwFlags ); [DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptBinaryToString( byte[] pbBinary, int cbBinary, int dwFlags, StringBuilder pszString, ref int pcchString ); "@ Add-Type -MemberDefinition $Crypt32Def -Namespace PKI -Name Crypt32 -UsingNamespace "System.Text" $HexRawEncoding = 12 $QQBin = [System.IO.File]::ReadAllBytes($QQExecutableFile) # Byte[] 转 Hex String $pcchString = 0 # Size if ([PKI.Crypt32]::CryptBinaryToString($QQBin, $QQBin.Length, $HexRawEncoding, $null, [ref]$pcchString)) { $QQHex = New-Object Text.StringBuilder $pcchString [void][PKI.Crypt32]::CryptBinaryToString($QQBin, $QQBin.Length, $HexRawEncoding, $QQHex, [ref]$pcchString) $PatchedQQHex = $QQHex.ToString() -replace "7061636b6167652e6a736f6e00696e6465782e6a73006c61756e636865722e6a73006c61756e636865722e6e6f646500", "696e6465782e6a730000000000696e6465782e6a73006c61756e636865722e6a73006c61756e636865722e6e6f646500" -replace "7061636b6167652e488d942400020000488902c742086a736f6e", "6c61756e63686572488d942400020000488902c742082e6a7300" # Hex String 转 Byte[] $pcbBinary = 0 # Size $pdwFlags = 0 if ([PKI.Crypt32]::CryptStringToBinary($PatchedQQHex, $PatchedQQHex.Length, $HexRawEncoding, $null, [ref]$pcbBinary, 0, [ref]$pdwFlags)) { $PatchedQQBin = New-Object byte[] -ArgumentList $pcbBinary [void][PKI.Crypt32]::CryptStringToBinary($PatchedQQHex, $PatchedQQHex.Length, $HexRawEncoding, $PatchedQQBin, [ref]$pcbBinary, 0, [ref]$pdwFlags) # 写出文件 [System.IO.File]::WriteAllBytes($QQExecutableFile, $PatchedQQBin) # 写出 MD5 $QQFileHash = (Get-FileHash $QQExecutableFile -Algorithm MD5).Hash [System.IO.File]::WriteAllLines($QQExecutableHashFile, $QQFileHash, $Utf8NoBomEncoding) } else { throw $((New-Object ComponentModel.Win32Exception ([Runtime.InteropServices.Marshal]::GetLastWin32Error())).Message) } } else { throw $((New-Object ComponentModel.Win32Exception ([Runtime.InteropServices.Marshal]::GetLastWin32Error())).Message) } } else { Write-Output "QQ.exe 未更新,无需修补!" } if ((Test-Path $QQNTimFlagFile) -eq $false) { "" | Out-File $QQNTimFlagFile -Encoding UTF8 -Force } if ((Test-Path $SuccessFlagFile) -eq $false) { "" | Out-File $SuccessFlagFile -Encoding UTF8 -Force } if ($env:QQNTIM_INSTALLER_NO_DELAYED_EXIT -ne "1") { Write-Output "安装成功。安装程序将在 5 秒后自动退出。" Start-Sleep -Seconds 5 } else { Write-Output "安装成功。" } ================================================ FILE: publish/_/uninstall.ps1 ================================================ $ErrorActionPreference = "Stop" $Host.UI.RawUI.WindowTitle = "QQNTim 卸载程序 (PowerShell)" Set-Location (Split-Path -Parent $MyInvocation.MyCommand.Definition) # 判断是否拥有管理员权限 if (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) { throw "权限不足。" } } # 从注册表获取 QQ 安装路径 foreach ($RegistryPath in @("HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*")) { try { foreach ($Item in (Get-ItemProperty $RegistryPath)) { if ($Item.PSChildName -eq "QQ") { $QQInstallDir = (Split-Path -Parent $Item.UninstallString) break } } } catch {} } if (($null -eq $QQInstallDir) -or ((Test-Path $QQInstallDir) -eq $false)) { throw "未找到 QQNT 安装目录。" } $QQExecutableFile = "$QQInstallDir\QQ.exe" $QQExecutableBackupFile = "$QQInstallDir\QQ.exe.bak" $QQExecutableHashFile = "$QQInstallDir\QQ.exe.md5" $QQAppDir = "$QQInstallDir\resources\app" $QQAppLauncherDir = "$QQAppDir\app_launcher" $QQNTimFlagFile = "$QQAppLauncherDir\qqntim-flag.txt" $SuccessFlagFile = "$env:TEMP\qqntim-uninstall-successful.tmp" if ((Test-Path $QQNTimFlagFile) -eq $false) { throw "QQNTim 未被安装。" } if ((Read-Host "是否要卸载 QQNTim (y/n)?") -notcontains "y") { throw "卸载已被用户取消。" } if ((Read-Host "是否需要同时移除所有数据 (y/n)?") -contains "y") { Remove-Item "${env:UserProfile}\.qqntim" -Recurse -Force -ErrorAction SilentlyContinue } if ($env:QQNTIM_UNINSTALLER_NO_KILL_QQ -ne "1") { Write-Output "正在关闭 QQ……" Stop-Process -Name QQ -ErrorAction SilentlyContinue } Write-Output "正在移除文件……" if ((Test-Path "$QQAppLauncherDir\node_modules.zip.md5") -eq $true) { Remove-Item "$QQAppLauncherDir\node_modules.zip.md5" -Force } Remove-Item "$QQAppLauncherDir\qqntim.js", "$QQAppLauncherDir\qqntim-renderer.js", "$QQAppLauncherDir\node_modules", "$QQAppLauncherDir\builtins" -Recurse -Force Write-Output "正在还原 package.json……" $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False [System.IO.File]::WriteAllLines("$QQAppDir\package.json", ((Get-Content "$QQAppDir\package.json" -Encoding UTF8 -Force) -replace "./app_launcher/qqntim.js", "./app_launcher/index.js"), $Utf8NoBomEncoding) Write-Output "正在还原 QQ.exe……" if ((Test-Path $QQExecutableHashFile) -eq $true) { Remove-Item $QQExecutableHashFile -Force } if ((Test-Path $QQExecutableBackupFile) -eq $true) { Remove-Item $QQExecutableFile -Force Move-Item $QQExecutableBackupFile $QQExecutableFile -Force } Remove-Item $QQNTimFlagFile -Force if ((Test-Path $SuccessFlagFile) -eq $false) { "" | Out-File $SuccessFlagFile -Encoding UTF8 -Force } if ($env:QQNTIM_UNINSTALLER_NO_DELAYED_EXIT -ne "1") { Write-Output "卸载成功。卸载程序将在 5 秒后自动退出。" Start-Sleep -Seconds 5 } else { Write-Output "卸载成功。" } ================================================ FILE: publish/install.cmd ================================================ @setlocal enableextensions @echo off cd /d %~dp0_ color F0 mode con cols=65 lines=16 set PS_PREFIX=powershell -NoProfile -ExecutionPolicy Unrestricted "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" >nul 2>nul if "%ERRORLEVEL%" neq "0" ( goto try_run_as ) else ( goto main ) goto:eof :try_run_as %PS_PREFIX% -WindowStyle Hidden -Command Start-Process -Wait -FilePath """%COMSPEC%""" -Verb RunAs -ArgumentList """/c""","""`"""%~f0`"""""" goto:eof :main set SUCCESS_FLAG=%TEMP%\qqntim-install-successful.tmp if exist "%SUCCESS_FLAG%" ( del /f /q "%SUCCESS_FLAG%" ) %PS_PREFIX% -File .\install.ps1 if not exist "%SUCCESS_FLAG%" ( echo Installation error. If you believe this is an issue of QQNTim, please report it to us. pause >nul 2>nul ) goto:eof ================================================ FILE: publish/install.sh ================================================ #!/usr/bin/env bash pushd "$( dirname "${BASH_SOURCE[0]}" )/_" > /dev/null # 判断是否拥有 root 权限 if [ ! "$(whoami)" == "root" ]; then echo "正在提升权限……" popd > /dev/null sudo QQNTIM_INSTALLER_NO_KILL_QQ="$QQNTIM_INSTALLER_NO_KILL_QQ" QQNTIM_INSTALLER_NO_DELAYED_EXIT="$QQNTIM_INSTALLER_NO_DELAYED_EXIT" "${BASH_SOURCE[0]}" exit 0 fi # 获取 QQ 安装路径 qq_installation_dir=$( dirname $( readlink $( which qq || which linuxqq ) ) 2>/dev/null || echo "/var/lib/flatpak/app/com.qq.QQ/current/active/files/extra/QQ" ) if [ ! -d "$qq_installation_dir" ]; then echo "未找到 QQNT 安装目录。" fi qq_app_dir="$qq_installation_dir/resources/app" qq_applauncher_dir="$qq_app_dir/app_launcher" qqntim_flag_file="$qq_applauncher_dir/qqntim-flag.txt" # 询问用户,如果存在旧版则不提示 if [ ! -f "$qqntim_flag_file" ]; then read -p "是否要安装 QQNTim (y/n)?" choice case $choice in y) ;; Y) ;; *) exit -1 ;; esac else echo "检测到已有安装,正在更新……" fi if [ "$QQNTIM_INSTALLER_NO_KILL_QQ" != "1" ]; then echo "正在关闭 QQ……" killall -w qq linuxqq > /dev/null 2>&1 fi echo "正在复制文件……" if [ -f "./node_modules.zip.md5" -a -f "./node_modules.zip" ]; then diff "$qq_applauncher_dir/node_modules.zip.md5" "./node_modules.zip.md5" > /dev/null 2>&1 [ $? != 0 ] && unzip -qo ./node_modules.zip -d "$qq_applauncher_dir/node_modules" cp -f ../node_modules.zip.md5 "$qq_applauncher_dir" elif [ -d "./node_modules" ]; then cp -rf ./node_modules "$qq_applauncher_dir" fi cp -rf ./qqntim.js ./qqntim-renderer.js ./builtins "$qq_applauncher_dir" echo "正在修补 package.json……" sed -i "s#\.\/app_launcher\/index\.js#\.\/app_launcher\/qqntim\.js#g" "$qq_app_dir/package.json" touch "$qqntim_flag_file" if [ "$QQNTIM_INSTALLER_NO_DELAYED_EXIT" != "1" ]; then echo "安装成功。安装程序将在 5 秒后自动退出。" sleep 5s else echo "安装成功。" fi exit 0 ================================================ FILE: publish/install_macos.sh ================================================ #!/usr/bin/env bash pushd "$( dirname "${BASH_SOURCE[0]}" )/_" > /dev/null # 判断是否拥有 root 权限 if [ ! "$(whoami)" == "root" ]; then echo "正在提升权限……" popd > /dev/null sudo QQNTIM_INSTALLER_NO_KILL_QQ="$QQNTIM_INSTALLER_NO_KILL_QQ" QQNTIM_INSTALLER_NO_DELAYED_EXIT="$QQNTIM_INSTALLER_NO_DELAYED_EXIT" "${BASH_SOURCE[0]}" exit 0 fi # 获取 QQ 安装路径 qq_installation_dir="/Applications/QQ.app/Contents" if [ ! -d "$qq_installation_dir" ]; then echo "未找到 QQNT 安装目录。" fi qq_app_dir="$qq_installation_dir/Resources/app" qq_applauncher_dir="$qq_app_dir/app_launcher" qqntim_flag_file="$qq_applauncher_dir/qqntim-flag.txt" # 询问用户,如果存在旧版则不提示 if [ ! -f "$qqntim_flag_file" ]; then read -p "是否要安装 QQNTim (y/n)?" choice case $choice in y) ;; Y) ;; *) exit -1 ;; esac else echo "检测到已有安装,正在更新……" fi if [ "$QQNTIM_INSTALLER_NO_KILL_QQ" != "1" ]; then echo "正在关闭 QQ……" pkill QQ > /dev/null 2>&1 fi echo "正在复制文件……" # 清理安装目录 if [ -d "$qq_applauncher_dir/node_modules" ]; then rm -rf else mkdir $qq_applauncher_dir/node_modules fi if [ -f "./node_modules.zip.md5" -a -f "./node_modules.zip" ]; then diff "$qq_applauncher_dir/node_modules.zip.md5" "./node_modules.zip.md5" > /dev/null 2>&1 [ $? != 0 ] unzip -qo ./node_modules.zip -d "$qq_applauncher_dir/node_modules" cp -f ./node_modules.zip.md5 "$qq_applauncher_dir" elif [ -d "./node_modules" ]; then cp -rf ./node_modules "$qq_applauncher_dir" fi cp -rf ./qqntim.js ./qqntim-renderer.js ./builtins "$qq_applauncher_dir" echo "正在修补 package.json……" sed -i "" "s#\.\/app_launcher\/index\.js#\.\/app_launcher\/qqntim\.js#g" "$qq_app_dir/package.json" touch "$qqntim_flag_file" if [ "$QQNTIM_INSTALLER_NO_DELAYED_EXIT" != "1" ]; then echo "安装成功。安装程序将在 5 秒后自动退出。" sleep 5 else echo "安装成功。" fi exit 0 ================================================ FILE: publish/uninstall.cmd ================================================ @setlocal enableextensions @echo off cd /d %~dp0_ color F0 mode con cols=65 lines=16 set PS_PREFIX=powershell -NoProfile -ExecutionPolicy Unrestricted "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" >nul 2>nul if "%ERRORLEVEL%" neq "0" ( goto try_run_as ) else ( goto main ) goto:eof :try_run_as %PS_PREFIX% -WindowStyle Hidden -Command Start-Process -Wait -FilePath """%COMSPEC%""" -Verb RunAs -ArgumentList """/c""","""`"""%~f0`"""""" goto:eof :main set SUCCESS_FLAG=%TEMP%\qqntim-uninstall-successful.tmp if exist "%SUCCESS_FLAG%" ( del /f /q "%SUCCESS_FLAG%" ) %PS_PREFIX% -File .\uninstall.ps1 if not exist "%SUCCESS_FLAG%" ( echo Uninstallation error. If you believe this is an issue of QQNTim, please report it to us. pause >nul 2>nul ) goto:eof ================================================ FILE: publish/uninstall.sh ================================================ #!/usr/bin/env bash pushd "$( dirname "${BASH_SOURCE[0]}" )/_" > /dev/null # 判断是否拥有 root 权限 if [ ! "$(whoami)" == "root" ]; then echo "正在提升权限……" popd > /dev/null sudo QQNTIM_UNINSTALLER_NO_KILL_QQ="$QQNTIM_UNINSTALLER_NO_KILL_QQ" QQNTIM_UNINSTALLER_NO_DELAYED_EXIT="$QQNTIM_UNINSTALLER_NO_DELAYED_EXIT" "${BASH_SOURCE[0]}" exit 0 fi # 获取 QQ 安装路径 qq_installation_dir=$( dirname $( readlink $( which qq || which linuxqq ) ) 2>/dev/null || echo "/var/lib/flatpak/app/com.qq.QQ/current/active/files/extra/QQ" ) if [ ! -d "$qq_installation_dir" ]; then echo "未找到 QQNT 安装目录。" fi qq_app_dir="$qq_installation_dir/resources/app" qq_applauncher_dir="$qq_app_dir/app_launcher" qqntim_flag_file="$qq_applauncher_dir/qqntim-flag.txt" if [ ! -f "$qqntim_flag_file" ]; then echo "QQNTim 未被安装。" exit -1 fi read -p "是否要卸载 QQNTim (y/n)?" choice case $choice in y) ;; *) exit -1 ;; esac read -p "是否需要同时移除所有数据 (y/n)?" choice case $choice in y) rm -rf "$HOME/.local/share/QQNTim" ;; *) ;; esac if [ "$QQNTIM_UNINSTALLER_NO_KILL_QQ" != "1" ]; then echo "正在关闭 QQ……" killall -w qq linuxqq > /dev/null 2>&1 fi echo "正在移除文件……" [ -f "$qq_applauncher_dir/node_modules.zip.md5" ] && rm -f "$qq_applauncher_dir/node_modules.zip.md5" rm -rf "$qq_applauncher_dir/qqntim.js" "$qq_applauncher_dir/qqntim-renderer.js" "$qq_applauncher_dir/node_modules" "$qq_applauncher_dir/builtins" echo "正在还原 package.json……" sed -i "s#\.\/app_launcher\/qqntim\.js#\.\/app_launcher\/index\.js#g" "$qq_app_dir/package.json" rm -f "$qqntim_flag_file" if [ "$QQNTIM_UNINSTALLER_NO_DELAYED_EXIT" != "1" ]; then echo "卸载成功。卸载程序将在 5 秒后自动退出。" sleep 5s else echo "卸载成功。" fi exit 0 ================================================ FILE: publish/uninstall_macos.sh ================================================ #!/usr/bin/env bash pushd "$( dirname "${BASH_SOURCE[0]}" )/_" > /dev/null # 判断是否拥有 root 权限 if [ ! "$(whoami)" == "root" ]; then echo "正在提升权限……" popd > /dev/null sudo QQNTIM_UNINSTALLER_NO_KILL_QQ="$QQNTIM_UNINSTALLER_NO_KILL_QQ" QQNTIM_UNINSTALLER_NO_DELAYED_EXIT="$QQNTIM_UNINSTALLER_NO_DELAYED_EXIT" "${BASH_SOURCE[0]}" exit 0 fi # 获取 QQ 安装路径 qq_installation_dir="/Applications/QQ.app/Contents" if [ ! -d "$qq_installation_dir" ]; then echo "未找到 QQNT 安装目录。" fi qq_app_dir="$qq_installation_dir/Resources/app" qq_applauncher_dir="$qq_app_dir/app_launcher" qqntim_flag_file="$qq_applauncher_dir/qqntim-flag.txt" if [ ! -f "$qqntim_flag_file" ]; then echo "QQNTim 未被安装。" exit -1 fi read -p "是否要卸载 QQNTim (y/n)?" choice case $choice in y) ;; *) exit -1 ;; esac read -p "是否需要同时移除所有数据 (y/n)?" choice case $choice in y) rm -rf "$HOME/.local/share/QQNTim" ;; *) ;; esac if [ "$QQNTIM_UNINSTALLER_NO_KILL_QQ" != "1" ]; then echo "正在关闭 QQ……" pkill QQ > /dev/null 2>&1 fi echo "正在移除文件……" [ -f "$qq_applauncher_dir/node_modules.zip.md5" ] && rm -f "$qq_applauncher_dir/node_modules.zip.md5" rm -rf "$qq_applauncher_dir/qqntim.js" "$qq_applauncher_dir/qqntim-renderer.js" "$qq_applauncher_dir/node_modules" "$qq_applauncher_dir/builtins" echo "正在还原 package.json……" sed -i "" "s#\.\/app_launcher\/qqntim\.js#\.\/app_launcher\/index\.js#g" "$qq_app_dir/package.json" rm -f "$qqntim_flag_file" if [ "$QQNTIM_UNINSTALLER_NO_DELAYED_EXIT" != "1" ]; then echo "卸载成功。卸载程序将在 5 秒后自动退出。" sleep 5 else echo "卸载成功。" fi exit 0 ================================================ FILE: rome.json ================================================ { "$schema": "https://docs.rome.tools/schemas/12.1.3/schema.json", "organizeImports": { "enabled": true }, "files": { "ignore": [".pnp.cjs", ".pnp.loader.mjs", ".yarn/*", "dist/*", "src/typings/src/electron.d.ts"] }, "formatter": { "indentSize": 4, "indentStyle": "space", "lineWidth": 300 }, "linter": { "enabled": true, "rules": { "recommended": true, "suspicious": { "noExplicitAny": "off", "noDoubleEquals": "off" }, "style": { "noParameterAssign": "off", "noNonNullAssertion": "off" }, "a11y": { "all": false } } } } ================================================ FILE: scripts/pack.ps1 ================================================ $ErrorActionPreference = "Stop" Set-Location ((Split-Path -Parent $MyInvocation.MyCommand.Definition) + "\..") $CD = (Get-Location).Path $SourceDirPath = "$CD\dist\_\node_modules" $DestinationZipPath = "$CD\dist\_\node_modules.zip" # 设置特定时间戳,确保两次构建结果 Hash 不变 Get-ChildItem $SourceDirPath -Recurse | ForEach-Object { $_.LastWriteTimeUtc = "01/01/1970 08:00:00"; $_.LastAccessTimeUtc = "01/01/1970 08:00:00"; $_.CreationTimeUtc = "01/01/1970 08:00:00"; } # 打包 node_modules # 仅支持 .NET Framework 4.5 及以上 Add-Type -AssemblyName System.IO.Compression.Filesystem [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirPath, $DestinationZipPath) Remove-Item $SourceDirPath -Recurse -Force # 生成 MD5 校验和 $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $false [System.IO.File]::WriteAllLines($DestinationZipPath, (Get-FileHash "$DestinationZipPath.md5" -Algorithm MD5).Hash, $Utf8NoBomEncoding) ================================================ FILE: scripts/pack.sh ================================================ #!/usr/bin/env bash cd "$( dirname "${BASH_SOURCE[0]}" )/.." pushd ./dist/_/node_modules > /dev/null # 设置特定时间戳,确保两次构建结果 Hash 不变 find . -exec touch -d @0 {} + # 打包 node_modules zip -Xyqr9 ../node_modules.zip . popd > /dev/null rm -rf ./dist/_/node_modules # 生成 MD5 校验和 (md5sum -b ./dist/_/node_modules.zip | cut -d" " -f1) > ./dist/_/node_modules.zip.md5 ================================================ FILE: scripts/start.ps1 ================================================ $ErrorActionPreference = "Stop" Set-Location ((Split-Path -Parent $MyInvocation.MyCommand.Definition) + "\..") # 从注册表获取 QQ 安装路径 foreach ($RegistryPath in @("HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*")) { try { foreach ($Item in (Get-ItemProperty $RegistryPath)) { if ($Item.PSChildName -eq "QQ") { $QQInstallDir = (Split-Path -Parent $Item.UninstallString) break } } } catch {} } if (($null -eq $QQInstallDir) -or ((Test-Path $QQInstallDir) -eq $false)) { throw "未找到 QQNT 安装目录。" } Start-Process "$QQInstallDir\QQ.exe" -Wait ================================================ FILE: scripts/start.sh ================================================ #!/usr/bin/env bash cd "$( dirname "${BASH_SOURCE[0]}" )/.." ( qq || linuxqq || flatpak run com.qq.QQ ) 2>&1 | sed -e '/NODE_TLS_REJECT_UNAUTHORIZED/d' -e '/Gtk-Message/d' -e '/to show where the warning was created/d' -e '/gbm_wrapper\.cc/d' -e '/node_bindings\.cc/d' -e '/UnhandledPromiseRejectionWarning/d' -e '/\[BuglyManager\.cpp\]/d' -e '/\[NativeCrashHandler\.cpp\]/d' -e '/\[BuglyService\.cpp\]/d' -e '/\[HotUpdater\]/d' -e '/ERROR:CONSOLE/d' ================================================ FILE: src/builtins/settings/package.json ================================================ { "name": "@flysoftbeta/qqntim-plugin-settings", "private": true, "devDependencies": { "@flysoftbeta/qqntim-typings": "workspace:*", "@types/node": "^20.6.2", "@types/react": "^18.2.21", "@types/react-dom": "^18.2.7", "@types/unzipper": "^0.10.7" }, "dependencies": { "unzipper": "^0.10.14" } } ================================================ FILE: src/builtins/settings/publish/qqntim.json ================================================ { "manifestVersion": "3.0", "id": "builtin-settings-ui", "name": "设置", "author": "Flysoft", "injections": [ { "type": "renderer", "page": "settings", "stylesheet": "style.css", "script": "renderer.js" } ] } ================================================ FILE: src/builtins/settings/publish/style.css ================================================ .q-switch { position: relative; } .q-switch > input { position: absolute; left: 0; right: 0; top: 0; bottom: 0; appearance: none !important; margin: 0; z-index: 10; } .q-button { margin: 0 !important; } .qqntim-settings-panel-open .setting-main .setting-main__content:not(.qqntim-settings-panel), body:not(.qqntim-settings-panel-open) .setting-main .setting-main__content.qqntim-settings-panel { display: none !important; } .qqntim-settings-panel { padding: 20px 16px 70px !important; } .qqntim-settings-panel-section-header { display: flex; flex-direction: row; align-items: center; justify-content: space-between; padding: 8px; } .qqntim-settings-panel-section-header-title { font-size: min(var(--font_size_2), 18px) !important; } .qqntim-settings-panel-section-header-buttons { display: flex; flex-direction: row; align-items: center; gap: 5px; } .qqntim-settings-panel-section-content { border-radius: 5px; padding: 0 16px; background-color: var(--fg_white); } .qqntim-settings-panel-settings-versions { display: flex; flex-direction: row; justify-content: space-between; gap: 5px; padding: 16px 0; } .qqntim-settings-panel-settings-versions-item { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; white-space: nowrap; flex: 10; } .qqntim-settings-panel-settings-versions-item > h3 { font-size: min(var(--font_size_3), 18px) !important; } .qqntim-settings-panel-settings-versions-item > div { font-size: min(var(--font_size_2), 16px) !important; color: var(--text_secondary_01); } .qqntim-settings-panel-box { display: flex; flex-direction: column; } .qqntim-settings-panel-box-item { display: flex; flex-direction: row; justify-content: space-between; align-items: center; width: 100%; min-height: 44px; padding: 8px 0; } .qqntim-settings-panel-box-item > span { display: flex; flex-direction: column; justify-content: center; } .qqntim-settings-panel-box-item > div { display: flex; flex-direction: row; align-items: center; gap: 5px; } .qqntim-settings-panel-box-item-title { font-size: min(var(--font_size_3), 18px) !important; } .qqntim-settings-panel-box-item-description { font-size: min(var(--font_size_2), 16px) !important; color: var(--text_secondary_01); } .qqntim-settings-panel-box-item:not(.qqntim-settings-panel-box-item-last) { border-bottom: 1px solid var(--divider_standard); } .qqntim-settings-panel-save { position: fixed; right: 20px; bottom: 20px; display: flex; flex-direction: row; align-items: center; gap: 10px; z-index: 100; } ================================================ FILE: src/builtins/settings/src/_renderer.tsx ================================================ import * as exports from "./exports"; import * as exportsComponents from "./exports/components"; import { Navigation, TabWithOtherTab } from "./nav"; import { Panel } from "./panel"; import { cl } from "./utils/consts"; import { defineModules, nt, utils } from "qqntim/renderer"; import { createRoot } from "react-dom/client"; export default class Entry implements QQNTim.Entry.Renderer { constructor() { defineModules({ "qqntim-settings": exports as typeof QQNTim.Settings, "qqntim-settings/components": exportsComponents as typeof QQNTim.SettingsComponents }); Promise.all([nt.getAccountInfo(), utils.waitForElement(".nav-bar:not(.qqntim-settings-nav)"), utils.waitForElement(".setting-main"), utils.waitForElement(`.setting-main .setting-main__content:not(.${cl.panel.c})`)]).then( ([account, nav, panel, panelContent]) => { if (!account) throw new Error("获取当前账户信息时失败"); const panelVueId = utils.getVueId(panelContent)!; const panelContainer = document.createElement("div"); panelContainer.classList.add("setting-main__content", cl.panel.c); panelContainer.setAttribute(panelVueId, ""); const panelRoot = createRoot(panelContainer); const renderPanel = (currentTab: TabWithOtherTab) => { panelRoot.render(); }; panel.appendChild(panelContainer); const navVueId = utils.getVueId(nav.firstElementChild as HTMLElement)!; const navContainer = document.createElement("div"); navContainer.classList.add(cl.nav.c); const navRoot = createRoot(navContainer); const renderNav = () => { navRoot.render(); }; nav.appendChild(navContainer); exports.setRenderNavFunction(renderNav); renderNav(); }, ); } } ================================================ FILE: src/builtins/settings/src/exports/components.tsx ================================================ import { cl } from "../utils/consts"; import { Fragment, ReactNode, useState } from "react"; export function SettingsSection({ title, children, buttons }: { title: string; children: ReactNode; buttons?: ReactNode }) { return (

{title}

{!!buttons &&
{buttons}
}
{children}
); } export function SettingsBox({ children }: { children: ReactNode }) { return
{children}
; } export function SettingsBoxItem({ title, description, children, isLast = false }: { title: string; description?: string[]; children?: ReactNode; isLast?: boolean }) { return ( ); } export function Switch({ checked, onToggle }: { checked: boolean; onToggle: (checked: boolean) => void }) { return (
onToggle(!checked)}> onToggle(event.target.checked)} />
); } export function Input({ value, onChange, width }: { value: string; onChange: (value: string) => void; width }) { const [focus, setFocus] = useState(false); return (
onChange(event.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} spellCheck={false} style={{ fontSize: "12px", height: "26px", lineHeight: "26px", padding: "0 32px 0 8px", border: "1px solid transparent", borderRadius: "4px", boxSizing: "border-box", ...(focus && { border: " 1px solid var(--brand_standard)", borderRadius: "4px", caretColor: "var(--brand_standard)", }), }} />
); } export function Dropdown({ items, selected, onChange, width }: { items: [T, string][]; selected: T; onChange: (id: T) => void; width: string }) { const [open, setOpen] = useState(false); const [selectedId, selectedContent] = items.find(([id]) => id == selected)!; return (
setOpen((prev) => !prev)}>
{selectedContent}
{open && (
    {items.map(([id, content]) => { const isSelected = id == selectedId; return (
  • { onChange(id); setOpen(false); }} > {content} {isSelected && ( )}
  • ); })}
)}
); } export function Button({ onClick, primary, small, children }: { onClick: () => void; primary: boolean; small: boolean; children: ReactNode }) { return ( ); } ================================================ FILE: src/builtins/settings/src/exports/index.ts ================================================ export const panels: [string, QQNTim.Settings.Panel, string | undefined][] = []; let renderNav: Function = () => undefined; export function defineSettingsPanels(...newSettingsPanels: [string, QQNTim.Settings.Panel, string | undefined][]) { panels.push(...newSettingsPanels); renderNav(); } export function setRenderNavFunction(newFunction: Function) { renderNav = newFunction; } ================================================ FILE: src/builtins/settings/src/installer.ts ================================================ import { s } from "./utils/sep"; import { randomUUID } from "crypto"; import * as path from "path"; import { allPlugins, app, dialog, env, modules } from "qqntim/renderer"; import { Extract } from "unzipper"; const { fs } = modules; export async function installZipPluginsForAccount(uin: string, requiresRestart: boolean) { const result = await dialog.openDialog({ title: "选择插件压缩包", properties: ["openFile"], filters: [{ name: "ZIP 压缩文件", extensions: ["zip"] }] }); if (result.canceled) return; const filePath = result.filePaths[0]; if (!(await fs.exists(filePath)) || !(await fs.stat(filePath)).isFile()) return; const tmpDir = `${process.platform == "win32" ? process.env["TEMP"] : "/tmp"}${s}${randomUUID()}`; try { await fs.ensureDir(tmpDir); await new Promise((resolve, reject) => fs .createReadStream(result.filePaths[0]) .pipe(Extract({ path: tmpDir })) .on("close", () => resolve()) .on("error", (error) => reject(error)), ); } catch (reason) { await dialog.alert("解压插件压缩包时出现错误:\n" + reason); return false; } return await installPluginsForAccount(uin, requiresRestart, tmpDir); } export async function installFolderPluginsForAccount(uin: string, requiresRestart: boolean) { const result = await dialog.openDialog({ title: "选择插件文件夹", properties: ["openDirectory"] }); if (result.canceled) return; const filePath = result.filePaths[0]; if (!(await fs.exists(filePath)) || !(await fs.stat(filePath)).isDirectory()) return false; return await installPluginsForAccount(uin, requiresRestart, filePath); } async function collectManifests(dir: string) { const getManifestFile = async (dir: string) => { const manifestFile = `${dir}${s}qqntim.json`; if ((await fs.exists(manifestFile)) && (await fs.stat(manifestFile)).isFile()) return manifestFile; }; let manifestFiles: string[] = []; const manifestFile = await getManifestFile(dir); if (!manifestFile) { const folders = await fs.readdir(dir); manifestFiles = ( await Promise.all( folders.map(async (folder) => { const folderPath = `${dir}${s}${folder}`; if ((await fs.exists(folderPath)) && (await fs.stat(folderPath)).isDirectory()) { return await getManifestFile(folderPath); } }), ) ).filter(Boolean) as string[]; } else manifestFiles = [manifestFile]; return manifestFiles; } async function installPluginsForAccount(uin: string, requiresRestart: boolean, dir: string) { const manifestFiles = await collectManifests(dir); if (manifestFiles.length == 0) { await dialog.alert("未在目标文件夹或文件夹搜索到任何插件。\n请联系插件作者以获得更多信息。"); return false; } let count = 0; for (const manifestFile of manifestFiles) { const manifest = fs.readJSONSync(manifestFile) as QQNTim.Manifest; const pluginDir = `${uin == "" ? env.path.pluginDir : `${env.path.pluginPerUserDir}${s}${uin}`}${s}${manifest.id}`; if (!(await dialog.confirm(`扫描到一个插件:\n\nID:${manifest.id}\n名称:${manifest.name}\n作者:${manifest.author || "未知"}\n说明:${manifest.description || "该插件没有提供说明。"}\n\n是否希望安装此插件?`))) continue; try { if (allPlugins[uin]?.[manifest.id]) await fs.rm(allPlugins[uin][manifest.id].dir); await fs.ensureDir(pluginDir); await fs.copy(path.dirname(manifestFile), pluginDir); count++; } catch (reason) { await dialog.alert("复制插件时出现错误:\n" + reason); } } await dialog.alert(`成功安装了 ${count} 个插件。${requiresRestart ? `\n\n点击 "确定" 将重启你的 QQ。` : ""}`); if (requiresRestart) app.relaunch(); return true; } export async function uninstallPlugin(requiresRestart: boolean, pluginDir: string) { if (!(await dialog.confirm("是否要卸载此插件?"))) return false; try { await fs.remove(pluginDir); await dialog.alert(`成功卸载此插件。${requiresRestart ? `\n\n点击 "确定" 将重启你的 QQ。` : ""}`); if (requiresRestart) app.relaunch(); return true; } catch (reason) { await dialog.alert(`卸载插件时出现错误:\n${reason}`); return false; } } ================================================ FILE: src/builtins/settings/src/main.ts ================================================ ================================================ FILE: src/builtins/settings/src/nav.tsx ================================================ import { panels } from "./exports"; import { cl } from "./utils/consts"; import { utils } from "qqntim/renderer"; import { Fragment, useEffect, useState } from "react"; interface OtherTab { key?: undefined; type?: undefined; title?: string; icon?: string; } interface PluginsManagerTab { key: string; type: "plugins-manager"; title: string; icon: string; } interface SettingsTab { key: string; type: "settings"; title: string; icon: string; } interface PluginTab { key: string; type: "plugin"; title: string; icon: string | undefined; node: QQNTim.Settings.Panel; } export type Tab = PluginsManagerTab | SettingsTab | PluginTab; export type TabWithOtherTab = Tab | OtherTab; export function Navigation({ vueId, onCurrentTabChange }: { vueId: string; onCurrentTabChange: (tab: TabWithOtherTab) => void }) { const [currentTab, setCurrentTab] = useState({}); useEffect(() => { utils.waitForElement(".nav-bar").then((element) => element.addEventListener("click", (event) => { const item = (event.target as HTMLElement).closest(".nav-item"); if (!item) return; if (item.classList.contains(cl.nav.item.c)) return; item.classList.toggle("nav-item-active", true); const title = item.firstElementChild?.nextElementSibling as HTMLElement; if (title) setCurrentTab({ title: title.innerText }); }), ); }, []); useEffect(() => { if (currentTab.type) utils.waitForElement(`.nav-item.nav-item-active:not(.${cl.nav.item.c})`).then((element) => element.classList.remove("nav-item-active")); onCurrentTabChange(currentTab); }, [currentTab]); const tabs: Tab[] = [ { key: "settings", type: "settings", title: "QQNTim 设置", icon: ``, }, { key: "plugins-manager", type: "plugins-manager", title: "插件管理", icon: ``, }, ...panels.map(([title, node, icon], idx): PluginTab => { return { key: `plugin-${idx}`, type: "plugin", title: title, icon: icon, node: node, }; }), ]; return ( {tabs.map((item) => (
setCurrentTab(item)} {...{ [vueId]: "" }}> {!!item.icon && ( */ dangerouslySetInnerHTML={{ __html: item.icon }} style={{ width: "16px", height: "16px", marginRight: "8px", alignItems: "center", color: "inherit", display: "inline-flex", justifyContent: "center", }} /> )}
{item.title}
))}
); } ================================================ FILE: src/builtins/settings/src/panel.tsx ================================================ import { Button, SettingsBox, SettingsBoxItem, SettingsSection, Switch } from "./exports/components"; import { installFolderPluginsForAccount, installZipPluginsForAccount, uninstallPlugin } from "./installer"; import { TabWithOtherTab } from "./nav"; import { cl } from "./utils/consts"; import { enablePlugin, getPluginDescription, isInBlacklist, isInWhitelist, isPluginsExistent } from "./utils/utils"; import { shell } from "electron"; import { allPlugins, app, env, modules, utils } from "qqntim/renderer"; import { useEffect, useState } from "react"; const { fs } = modules; interface PanelProps { account: QQNTim.API.Renderer.NT.LoginAccount; config: Required; setConfig: React.Dispatch>>; } export function Panel({ currentTab, account }: { currentTab: TabWithOtherTab; account: QQNTim.API.Renderer.NT.LoginAccount }) { const [config, setConfig] = useState>(env.config); const [pluginsConfig, setPluginsConfig] = useState>(config.plugins.config || {}); const saveConfigAndRestart = () => { fs.writeJSONSync(env.path.configFile, config); app.relaunch(); }; const resetConfigAndRestart = () => { fs.writeJSONSync(env.path.configFile, {}); app.relaunch(); }; useEffect( () => setConfig((prev) => { return { ...prev, plugins: { ...prev.plugins, config: pluginsConfig } }; }), [pluginsConfig], ); useEffect(() => { document.body.classList.toggle(cl.panel.open.c, !!currentTab.type); utils.waitForElement(".setting-title").then((element) => { if (element.__VUE__?.[0]?.props?.title && currentTab.title) element.__VUE__[0].props.title = currentTab.title; }); }, [currentTab]); const panelProps: PanelProps = { account, config, setConfig, }; return ( <> {currentTab.type == "settings" ? : currentTab.type == "plugins-manager" ? : currentTab.type == "plugin" ? : null}
); } function SettingsPanel({ config, setConfig }: PanelProps) { return ( <>
{[ ["QQNTim", process.versions.qqntim], ["QQNT", process.versions.qqnt], ["Electron", process.versions.electron], ["Node.js", process.versions.node], ["Chromium", process.versions.chrome], ["V8", process.versions.v8], ].map(([name, version]) => (

{name}

{version}
))}
{( [ [ "显示详细日志输出", "开启后,可以在控制台内查看到 IPC 通信、部分 Electron 对象的成员访问信息等。", config.verboseLogging, (state: boolean) => setConfig((prev) => { return { ...prev, verboseLogging: state }; }), ], [ "使用原版 DevTools", "使用 Chromium DevTools 而不是 chii DevTools (Windows 版 9.8.5 及以上不可用)。", config.useNativeDevTools, (state) => setConfig((prev) => { return { ...prev, useNativeDevTools: state }; }), ], [ "禁用兼容性处理", "禁用后,LiteLoader 可能将不能与 QQNTim 一起使用。", config.disableCompatibilityProcessing, (state) => setConfig((prev) => { return { ...prev, disableCompatibilityProcessing: state }; }), ], ] as [string, string, boolean, (state: boolean) => void][] ).map(([title, description, value, setValue], idx, array) => ( // rome-ignore lint/suspicious/noArrayIndexKey: ))} ); } function PluginsManagerPanel({ account, config, setConfig }: PanelProps) { const [existentPlugins, setExistentPlugins] = useState(isPluginsExistent()); return Array.from(new Set([...Object.keys(allPlugins), account.uin])) .sort() .map((uin: string) => { const plugins = allPlugins[uin] || {}; const requiresRestart = uin == account.uin || uin == ""; const isEmpty = Object.keys(plugins).length == 0; if (uin != account.uin && isEmpty) return; return ( } > {!isEmpty ? ( Object.keys(plugins) .sort() .map((id, idx, array) => { const plugin = plugins[id]; const inWhitelist = isInWhitelist(id, config.plugins.whitelist); const inBlacklist = isInBlacklist(id, config.plugins.blacklist); const description = getPluginDescription(plugin); if (!existentPlugins.includes(id)) return; return ( enablePlugin(setConfig, id, state, inWhitelist, inBlacklist)} /> ); }) ) : ( )} ); }); } ================================================ FILE: src/builtins/settings/src/qqntim-env.d.ts ================================================ /// ================================================ FILE: src/builtins/settings/src/renderer.ts ================================================ import Entry from "./_renderer"; export default Entry; ================================================ FILE: src/builtins/settings/src/utils/consts.ts ================================================ export const cl = { nav: { c: "qqntim-settings-nav", item: { c: "qqntim-settings-nav-item", }, }, panel: { c: "qqntim-settings-panel", open: { c: "qqntim-settings-panel-open", }, settings: { versions: { c: "qqntim-settings-panel-settings-versions", item: { c: "qqntim-settings-panel-settings-versions-item", }, }, }, section: { c: "qqntim-settings-panel-section", header: { c: "qqntim-settings-panel-section-header", title: { c: "qqntim-settings-panel-section-header-title", }, buttons: { c: "qqntim-settings-panel-section-header-buttons", }, }, content: { c: "qqntim-settings-panel-section-content", }, }, box: { c: "qqntim-settings-panel-box", item: { c: "qqntim-settings-panel-box-item", last: { c: "qqntim-settings-panel-box-item-last", }, title: { c: "qqntim-settings-panel-box-item-title", }, description: { c: "qqntim-settings-panel-box-item-description", }, }, }, save: { c: "qqntim-settings-panel-save", }, }, }; ================================================ FILE: src/builtins/settings/src/utils/hooks.tsx ================================================ import { useEffect, useRef } from "react"; // Thanks https://learnersbucket.com/examples/interview/useprevious-hook-in-react/ export function usePrevious(value: T) { const ref = useRef(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } ================================================ FILE: src/builtins/settings/src/utils/sep.ts ================================================ export { sep as s } from "path"; ================================================ FILE: src/builtins/settings/src/utils/utils.ts ================================================ import { allPlugins, modules } from "qqntim/renderer"; const { fs } = modules; export function isInWhitelist(id: string, whitelist?: string[]) { return !!(whitelist && !whitelist.includes(id)); } export function isInBlacklist(id: string, blacklist?: string[]) { return !!blacklist?.includes(id); } function addItemToArray(array: T[], item: T) { return [...array, item]; } function removeItemFromArray(array: T[], item: T) { return array.filter((value) => value != item); } export function enablePlugin(setConfig: React.Dispatch>>, id: string, enable: boolean, inWhitelist: boolean, inBlacklist: boolean) { setConfig((prev) => { let _config = prev; if (_config.plugins.whitelist && enable != inWhitelist) _config = { ..._config, plugins: { ..._config.plugins, whitelist: (enable ? addItemToArray : removeItemFromArray)(_config.plugins.whitelist!, id), }, }; else if (!_config.plugins.blacklist) _config.plugins.blacklist = []; if (_config.plugins.blacklist && enable == inBlacklist) _config = { ..._config, plugins: { ..._config.plugins, blacklist: (!enable ? addItemToArray : removeItemFromArray)(_config.plugins.blacklist!, id), }, }; return _config; }); } export function isPluginsExistent() { const ids: string[] = []; Object.keys(allPlugins).forEach((uin) => Object.keys(allPlugins[uin]).forEach((id) => { const plugin = allPlugins[uin][id]; if (fs.existsSync(plugin.dir) && fs.statSync(plugin.dir).isDirectory()) ids.push(id); }), ); return ids; } export function getPluginDescription(plugin: QQNTim.Plugin) { const versionText = [plugin.manifest.version, plugin.manifest.author].filter(Boolean).join(" - "); const warnText = [!plugin.meetRequirements && "当前环境不满足需求,未加载", plugin.manifest.manifestVersion != "3.0" && "插件使用了过时的插件标准,请提醒作者更新"].filter(Boolean).join("; "); const description = plugin.manifest.description || "该插件没有提供说明。"; return [versionText, warnText && `警告: ${warnText}。`, description].filter(Boolean); } ================================================ FILE: src/builtins/settings/tsconfig.json ================================================ { "compilerOptions": { "jsx": "react-jsx", "module": "CommonJS", "moduleResolution": "Node", "target": "ESNext", "resolveJsonModule": true, "strictNullChecks": true, "strictFunctionTypes": true, "noEmit": true }, "include": ["src"], "exclude": ["node_modules", "**/node_modules/*"] } ================================================ FILE: src/common/global.ts ================================================ export const env = {} as QQNTim.Environment; export const allPlugins = {} as QQNTim.Plugin.AllUsersPlugins; export const setEnv = (value: QQNTim.Environment) => Object.assign(env, value); export const setAllPlugins = (value: QQNTim.Plugin.AllUsersPlugins) => Object.assign(allPlugins, value); ================================================ FILE: src/common/ipc.ts ================================================ import { env } from "./global"; import { printObject } from "./utils/console"; import { isMainProcess } from "./utils/process"; const interruptIpcs: [QQNTim.IPC.InterruptFunction, QQNTim.IPC.InterruptIPCOptions | undefined][] = []; function interruptIpc(args: QQNTim.IPC.Args, direction: QQNTim.IPC.Direction, channel: string, sender?: Electron.WebContents) { for (const [func, options] of interruptIpcs) { if (options?.cmdName && (!args[1] || (args[1][0]?.cmdName != options?.cmdName && args[1][0] != options?.cmdName))) continue; if (options?.eventName && !args[0]?.eventName?.startsWith(`${options?.eventName}-`)) continue; if (options?.type && (!args[0] || args[0].type != options?.type)) continue; if (options?.direction && options?.direction != direction) continue; const ret = func(args, channel, sender); if (ret == false) return false; } return true; } export function handleIpc(args: QQNTim.IPC.Args, direction: QQNTim.IPC.Direction, channel: string, sender?: Electron.WebContents) { if (args[0]?.eventName?.startsWith("ns-LoggerApi-")) return false; return interruptIpc(args, direction, channel, sender); } export function addInterruptIpc(func: QQNTim.IPC.InterruptFunction, options?: QQNTim.IPC.InterruptIPCOptions) { interruptIpcs.push([func, options]); } export function watchIpc() { if (env.config.verboseLogging && (env.config.useNativeDevTools || (!env.config.useNativeDevTools && isMainProcess))) { (["in", "out"] as QQNTim.IPC.Direction[]).forEach((type) => { addInterruptIpc((args, channel, sender) => console.debug(`[!Watch:IPC?${type == "in" ? "In" : "Out"}${sender ? `:${sender.id.toString()}` : ""}] ${channel}`, printObject(args)), { direction: type }); }); } } ================================================ FILE: src/common/loader.ts ================================================ import { s } from "./sep"; const loadedPlugins: QQNTim.Plugin.LoadedPlugins = {}; function getUserPlugins(allPlugins: QQNTim.Plugin.AllUsersPlugins, uin: string) { const userPlugins = allPlugins[uin]; if (!userPlugins) { console.warn(`[!Loader] 账户 (${uin}) 没有插件,跳过加载`); return; } if (uin != "") console.log(`[!Loader] 正在为账户 (${uin}) 加载插件`); else console.log("[!Loader] 正在为所有账户加载插件"); return userPlugins; } export function loadPlugins(allPlugins: QQNTim.Plugin.AllUsersPlugins, uin: string, shouldInject: (injection: QQNTim.Plugin.Injection) => boolean, scripts: [QQNTim.Plugin, string][], stylesheets?: [QQNTim.Plugin, string][]) { const userPlugins = getUserPlugins(allPlugins, uin); if (!userPlugins) return false; for (const id in userPlugins) { if (loadedPlugins[id]) continue; const plugin = userPlugins[id]; if (!plugin.loaded) continue; loadedPlugins[id] = plugin; console.log(`[!Loader] 正在加载插件:${id}`); plugin.injections.forEach((injection) => { const rendererInjection = injection as QQNTim.Plugin.InjectionRenderer; if (!shouldInject(injection)) return; stylesheets && rendererInjection.stylesheet && stylesheets.push([plugin, `${plugin.dir}${s}${rendererInjection.stylesheet}`]); injection.script && scripts.push([plugin, `${plugin.dir}${s}${injection.script}`]); }); } return true; } ================================================ FILE: src/common/patch.ts ================================================ const modules: Record = {}; export function defineModules(newModules: Record) { for (const name in newModules) { if (modules[name]) throw new Error(`模块名已经被使用:${name}`); modules[name] = newModules[name]; } } export function getModule(name: string) { return modules[name]; } ================================================ FILE: src/common/paths.ts ================================================ import { s } from "./sep"; export const dataDir = process.env["QQNTIM_HOME"] || (process.platform == "win32" ? `${process.env["UserProfile"]}${s}.qqntim` : `${process.env["HOME"]}${s}.local${s}share${s}QQNTim`); export const configFile = `${dataDir}${s}config.json`; export const pluginDir = `${dataDir}${s}plugins`; export const pluginPerUserDir = `${dataDir}${s}plugins-user`; ================================================ FILE: src/common/sep.ts ================================================ export { sep as s } from "path"; ================================================ FILE: src/common/utils/console.ts ================================================ import { isMainProcess } from "./process"; import supportsColor from "supports-color"; import { inspect } from "util"; export const hasColorSupport = !!supportsColor.stdout; export function printObject(object: any, enableColorSupport = isMainProcess && hasColorSupport) { return inspect(object, { compact: true, depth: null, showHidden: true, colors: enableColorSupport, }); } ================================================ FILE: src/common/utils/freePort.ts ================================================ import { AddressInfo, createServer } from "net"; export function findFreePort() { const server = createServer().listen(0); const { port } = server.address()! as AddressInfo; server.close(); return port; } ================================================ FILE: src/common/utils/ntVersion.ts ================================================ import { s } from "../sep"; import { readJSONSync } from "fs-extra"; export function getCurrentNTVersion() { let version: string; if (process.platform == "win32") { version = readJSONSync(`${__dirname}${s}..${s}versions${s}config.json`)?.curVersion; } else if (process.platform == "linux" || process.platform == "darwin") { version = readJSONSync(`${__dirname}${s}..${s}package.json`)?.version; } else throw new Error(`unsupported platform: ${process.platform}`); if (!version) throw new Error("cannot determine QQNT version"); return version; } ================================================ FILE: src/common/utils/process.ts ================================================ import { app } from "electron"; export const isMainProcess = !!app as boolean; ================================================ FILE: src/common/version.ts ================================================ import { version } from "../../package.json"; import { getCurrentNTVersion } from "./utils/ntVersion"; export function mountVersion() { const ntVersion = getCurrentNTVersion(); Object.defineProperties(process.versions, { qqnt: { value: ntVersion, writable: false }, qqntim: { value: version, writable: false }, }); } ================================================ FILE: src/common/watch.ts ================================================ import { env } from "./global"; import { printObject } from "./utils/console"; type Constructor = new (...args: any[]) => T; export function getter(scope: string | undefined, target: T, p: R) { if (p == "__qqntim_original_object") return target; if (typeof target[p] == "function") return (...argArray: any[]) => { const res = (target[p] as Function).apply(target, argArray); if (scope && env.config.verboseLogging) console.debug(`[!Watch:${scope}] 调用:${p as string}`, printObject(argArray), res != target ? printObject(res) : "[已隐藏]"); return res; }; else { const res = target[p]; if (scope && env.config.verboseLogging) console.debug(`[!Watch:${scope}] 获取:${p as string}`); return res; } } export function setter(scope: string | undefined, _: T, p: R, newValue: T[R]) { if (scope && env.config.verboseLogging) console.debug(`[!Watch:${scope}] 设置:${p as string}`, printObject(newValue)); return true; } export function construct>(scope: string | undefined, target: T, argArray: any[]) { if (scope && env.config.verboseLogging) console.debug(`[!Watch:${scope}] 构造新实例:`, printObject(argArray)); return new target(...argArray); } export function apply(target: T, thisArg: any, argArray: any[]) { return target.apply(thisArg, argArray); } ================================================ FILE: src/electron/README.txt ================================================ Silence is golden. ================================================ FILE: src/electron/package.json ================================================ { "name": "electron", "private": true, "version": "25.2.0" } ================================================ FILE: src/main/api.ts ================================================ import { env } from "../common/global"; import { addInterruptIpc } from "../common/ipc"; import { defineModules } from "../common/patch"; import { mountVersion } from "../common/version"; import { addInterruptWindowArgs, addInterruptWindowCreation } from "./patch"; import { plugins } from "./plugins"; import * as fs from "fs-extra"; export let api: typeof QQNTim.API.Main; export function initAPI() { mountVersion(); api = { allPlugins: plugins, env: env, interrupt: { ipc: addInterruptIpc, windowCreation: addInterruptWindowCreation, windowArgs: addInterruptWindowArgs, }, defineModules: defineModules, modules: { fs: fs, }, }; defineModules({ "qqntim/main": api }); } ================================================ FILE: src/main/compatibility.ts ================================================ import { env } from "../common/global"; import { existsSync } from "fs-extra"; import { resolve } from "path"; export function loadCustomLoaders() { if (env.config.disableCompatibilityProcessing) return; console.log("[!Compatibility] 正在进行兼容性处理"); env.config.pluginLoaders.map((loader: string) => { const path = resolve(__dirname, "..", loader); if (existsSync(path)) require(path); }); } ================================================ FILE: src/main/config.ts ================================================ import { configFile, dataDir, pluginDir, pluginPerUserDir } from "../common/paths"; import * as fs from "fs-extra"; function toBoolean(item: boolean | undefined, env: string, defaultValue: boolean) { const envValue = process.env[env]; return envValue ? !!parseInt(envValue) : typeof item == "boolean" ? item : defaultValue; } function toStringArray(item: R, env: string, defaultValue: R) { const envValue = process.env[env]; return envValue ? envValue.split(";") : item && item instanceof Array ? item : defaultValue; } // function toNumberArray( // item: number[] | undefined, // env: string, // defaultValue: number[] | undefined, // isFloat = false // ) { // const envValue = process.env[env]; // return envValue // ? envValue // .split(";") // .map((value) => (isFloat ? parseFloat(value) : parseInt(value))) // : item instanceof Array // ? item // : defaultValue; // } export function getEnvironment(config: QQNTim.Configuration): QQNTim.Environment { return { config: { plugins: { whitelist: toStringArray(config.plugins?.whitelist, "QQNTIM_PLUGINS_WHITELIST", undefined), blacklist: toStringArray(config.plugins?.blacklist, "QQNTIM_PLUGINS_BLACKLIST", undefined), config: config.plugins?.config || {}, }, pluginLoaders: toStringArray(config.pluginLoaders, "QQNTIM_PLUGIN_LOADER", ["LiteLoader", "LiteLoaderQQNT"]), verboseLogging: toBoolean(config.verboseLogging, "QQNTIM_VERBOSE_LOGGING", false), useNativeDevTools: toBoolean(config.useNativeDevTools, "QQNTIM_USE_NATIVE_DEVTOOLS", false), disableCompatibilityProcessing: toBoolean(config.disableCompatibilityProcessing, "QQNTIM_NO_COMPATIBILITY_PROCESSING", false), }, path: { dataDir, configFile, pluginDir, pluginPerUserDir, }, }; } function prepareDataDir() { fs.ensureDirSync(dataDir); fs.ensureDirSync(pluginDir); fs.ensureDirSync(pluginPerUserDir); if (!fs.existsSync(configFile)) fs.writeJSONSync(configFile, {}); } export function loadConfig() { prepareDataDir(); const config = fs.readJSONSync(configFile) || {}; return getEnvironment(config); } ================================================ FILE: src/main/debugger.ts ================================================ import { env } from "../common/global"; import { findFreePort } from "../common/utils/freePort"; import axios from "axios"; import { start } from "chii/server"; import { BrowserWindow } from "electron"; export let debuggerHost = ""; export let debuggerPort = -1; export let debuggerOrigin = ""; export async function initDebugger() { if (!env.config.useNativeDevTools) { debuggerPort = findFreePort(); debuggerHost = "127.0.0.1"; debuggerOrigin = `http://${debuggerHost}:${debuggerPort}`; console.log(`[!Debugger] 正在启动 chii 调试器:${debuggerOrigin}`); await start({ host: debuggerHost, port: debuggerPort, useHttps: false, }); } } async function listChiiTargets() { const res = await axios.get(`${debuggerOrigin}/targets`); return (res.data.targets as any[]).map((target) => [target.title, target.id]); } export async function createDebuggerWindow(debuggerId: string, win: BrowserWindow) { const targets = await listChiiTargets(); for (const [id, target] of targets) { if (id == debuggerId) { const url = `${debuggerOrigin}/front_end/chii_app.html?ws=${debuggerHost}:${debuggerPort}/client/${(Math.random() * 6).toString()}?target=${target}`; console.log(`[!Debugger] 正在打开 chii 调试器窗口:${url}`); const debuggerWin = new BrowserWindow({ width: 800, height: 600, show: true, webPreferences: { webSecurity: false, allowRunningInsecureContent: true, devTools: false, nodeIntegration: false, nodeIntegrationInSubFrames: false, contextIsolation: true, }, }); debuggerWin.webContents.loadURL(url); win.on("closed", () => debuggerWin.destroy()); break; } } } ================================================ FILE: src/main/loader.ts ================================================ import { loadPlugins } from "../common/loader"; let scripts: [QQNTim.Plugin, string][] = []; function shouldInject(injection: QQNTim.Plugin.Injection) { return injection.type == "main"; } export function applyPlugins(allPlugins: QQNTim.Plugin.AllUsersPlugins, uin = "") { loadPlugins(allPlugins, uin, shouldInject, scripts); applyScripts(); return true; } function applyScripts() { scripts = scripts.filter(([plugin, script]) => { try { const mod = require(script); if (mod) new ((mod.default || mod) as typeof QQNTim.Entry.Main)(); return false; } catch (reason) { console.error(`[!Loader] 运行此插件脚本时出现意外错误:${script},请联系插件作者 (${plugin.manifest.author}) 解决`); console.error(reason); } return true; }); } ================================================ FILE: src/main/main.ts ================================================ /** * @license * Copyright (c) Flysoft. */ import { setAllPlugins, setEnv } from "../common/global"; import { watchIpc } from "../common/ipc"; import { initAPI } from "./api"; import { loadCustomLoaders } from "./compatibility"; import { loadConfig } from "./config"; import { initDebugger } from "./debugger"; import { applyPlugins } from "./loader"; import { patchModuleLoader } from "./patch"; import { collectPlugins, plugins } from "./plugins"; setEnv(loadConfig()); initDebugger(); patchModuleLoader(); watchIpc(); loadCustomLoaders(); collectPlugins(); setAllPlugins(plugins); initAPI(); applyPlugins(plugins); console.log("[!Main] QQNTim 加载成功"); require("./index.js"); ================================================ FILE: src/main/patch.ts ================================================ import { env } from "../common/global"; import { handleIpc } from "../common/ipc"; import { defineModules, getModule } from "../common/patch"; import { s } from "../common/sep"; import { hasColorSupport } from "../common/utils/console"; import { apply, construct, getter, setter } from "../common/watch"; import { createDebuggerWindow, debuggerOrigin } from "./debugger"; import { applyPlugins } from "./loader"; import { plugins } from "./plugins"; import { enable, initialize } from "@electron/remote/main"; import { BrowserWindow, Menu, MenuItem, app, dialog, ipcMain } from "electron"; import { Module } from "module"; const interruptWindowArgs: QQNTim.WindowCreation.InterruptArgsFunction[] = []; const interruptWindowCreation: QQNTim.WindowCreation.InterruptFunction[] = []; ipcMain.on("___!boot", (event) => { if (!event.returnValue) event.returnValue = { enabled: false }; }); ipcMain.on("___!log", (event, level, ...args) => { console[{ 0: "debug", 1: "log", 2: "info", 3: "warn", 4: "error" }[level] || "log"](`[!Renderer:Log:${event.sender.id}]`, ...args); }); ipcMain.handle("___!dialog", (event, method: string, options: object) => dialog[method](BrowserWindow.fromWebContents(event.sender), options)); function patchBrowserWindow() { const windowMenu: Electron.MenuItem[] = [ new MenuItem({ label: "刷新", role: "reload", accelerator: "F5", }), new MenuItem({ label: "开发者工具", accelerator: "F12", ...(env.config.useNativeDevTools ? { role: "toggleDevTools" } : { click: (_, win) => { if (!win) return; const debuggerId = win.webContents.id.toString(); createDebuggerWindow(debuggerId, win); }, }), }), ]; return new Proxy(BrowserWindow, { apply(target, thisArg, argArray) { return apply(target, thisArg, argArray); }, get(target, p) { return getter(undefined, target, p as any); }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, construct(target, [options]: [Electron.BrowserWindowConstructorOptions]) { let patchedArgs: Electron.BrowserWindowConstructorOptions = { ...options, webPreferences: { ...options.webPreferences, preload: `${__dirname}${s}qqntim-renderer.js`, webSecurity: false, allowRunningInsecureContent: true, nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false, devTools: env.config.useNativeDevTools, sandbox: false, }, }; interruptWindowArgs.forEach((func) => { patchedArgs = func(patchedArgs); }); const win = construct("BrowserWindow", target, [patchedArgs]) as BrowserWindow; const webContentsId = win.webContents.id.toString(); let thirdpartyPreloads: string[] = win.webContents.session.getPreloads(); win.webContents.session.setPreloads([]); enable(win.webContents); const session = new Proxy(win.webContents.session, { get(target, p) { const res = getter(undefined, target, p as any); if (p == "setPreloads") return (newPreloads: string[]) => { thirdpartyPreloads = newPreloads; }; return res; }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, }); const webContents = new Proxy(win.webContents, { get(target, p) { const res = getter(undefined, target, p as any); if (p == "session") return session; return res; }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, }); const send = win.webContents.send; win.webContents.send = (channel: string, ...args: QQNTim.IPC.Args) => { handleIpc(args, "out", channel); return send.call(win.webContents, channel, ...args); }; win.webContents.on("ipc-message", (_, channel, ...args) => { if (!handleIpc(args as any, "in", channel, win.webContents)) throw new Error("QQNTim 已强行中断了一条 IPC 消息"); if (channel == "___!apply_plugins") applyPlugins(plugins, args[0] as string); }); win.webContents.on("ipc-message-sync", (event, channel, ...args) => { handleIpc(args as any, "in", channel, win.webContents); if (channel == "___!boot") { event.returnValue = { enabled: true, preload: Array.from(new Set([...thirdpartyPreloads, options.webPreferences?.preload].filter(Boolean))), debuggerOrigin: !env.config.useNativeDevTools && debuggerOrigin, webContentsId: webContentsId, plugins: plugins, env: env, hasColorSupport: hasColorSupport, }; } else if (channel == "___!browserwindow_api") { event.returnValue = win[args[0][0]](...args[0][1]); } else if (channel == "___!app_api") { event.returnValue = app[args[0][0]](...args[0][1]); } }); const setMenu = win.setMenu; win.setMenu = (menu) => { const patchedMenu = Menu.buildFromTemplate([...(menu?.items || []), ...windowMenu]); return setMenu.call(win, patchedMenu); }; win.setMenu(null); return new Proxy(win, { get(target, p) { const res = getter(undefined, target, p as any); if (p == "webContents") return webContents; return res; }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, }); }, }); } export function addInterruptWindowCreation(func: QQNTim.WindowCreation.InterruptFunction) { interruptWindowCreation.push(func); } export function addInterruptWindowArgs(func: QQNTim.WindowCreation.InterruptArgsFunction) { interruptWindowArgs.push(func); } export function patchModuleLoader() { // 阻止 Electron 默认菜单生成 Menu.setApplicationMenu(null); initialize(); const patchedElectron: typeof Electron.CrossProcessExports = { ...require("electron"), BrowserWindow: patchBrowserWindow(), }; defineModules({ electron: patchedElectron }); const loadBackend = (Module as any)._load; (Module as any)._load = (request: string, parent: NodeModule, isMain: boolean) => { return getModule(request) || loadBackend(request, parent, isMain); }; } ================================================ FILE: src/main/plugins.ts ================================================ import { env } from "../common/global"; import { s } from "../common/sep"; import * as fs from "fs-extra"; import * as os from "os"; import * as semver from "semver"; const supportedManifestVersions: QQNTim.Manifest.ManifestVersion[] = ["3.0"]; export const plugins: QQNTim.Plugin.AllUsersPlugins = {}; function isPluginEnabled(manifest: QQNTim.Manifest) { if (env.config.plugins.whitelist) return env.config.plugins.whitelist.includes(manifest.id); else if (env.config.plugins.blacklist) return !env.config.plugins.blacklist.includes(manifest.id); else return true; } function isPluginRequirementsMet(manifest: QQNTim.Manifest) { if (manifest.requirements?.os) { let meetRequirements = false; const osRelease = os.release(); for (const item of manifest.requirements.os) { if (item.platform != process.platform) continue; if (item.lte && !semver.lte(item.lte, osRelease)) continue; if (item.lt && !semver.lt(item.lt, osRelease)) continue; if (item.gte && !semver.gte(item.gte, osRelease)) continue; if (item.gt && !semver.gt(item.gt, osRelease)) continue; if (item.eq && !semver.eq(item.eq, osRelease)) continue; meetRequirements = true; break; } if (!meetRequirements) { return false; } } return true; } export function parsePlugin(dir: string) { try { const manifestFile = `${dir}${s}qqntim.json`; if (!fs.existsSync(manifestFile)) return null; const manifest = fs.readJSONSync(manifestFile) as QQNTim.Manifest; if (!manifest.manifestVersion) manifest.manifestVersion = supportedManifestVersions[0]; else if (!supportedManifestVersions.includes(manifest.manifestVersion)) throw new TypeError(`此插件包含一个无效的清单版本:${manifest.manifestVersion},支持的版本有:${supportedManifestVersions.join(", ")}`); const meetRequirements = isPluginRequirementsMet(manifest); const enabled = isPluginEnabled(manifest); const loaded = meetRequirements && enabled; if (!meetRequirements) console.error(`[!Plugins] 跳过加载插件:${manifest.id}(当前环境不满足要求)`); else if (!enabled) console.error(`[!Plugins] 跳过加载插件:${manifest.id}(插件已被禁用)`); return { enabled: enabled, meetRequirements: meetRequirements, loaded: loaded, id: manifest.id, dir: dir, injections: manifest.injections.map((injection) => { return injection.type == "main" ? { ...injection } : { ...injection, pattern: injection.pattern && new RegExp(injection.pattern), }; }), manifest: manifest, } as QQNTim.Plugin; } catch (reason) { console.error("[!Plugins] 解析插件时出现意外错误:", dir); console.error(reason); return null; } } function collectPluginsFromDir(baseDir: string, uin = "") { const folders = fs.readdirSync(baseDir); if (!plugins[uin]) plugins[uin] = {}; folders.forEach((folder) => { const folderPath = `${baseDir}${s}${folder}`; if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) { const plugin = parsePlugin(folderPath); if (!plugin) return; if (plugins[uin][plugin.id]) return; plugins[uin][plugin.id] = plugin; } }); } export function collectPlugins() { collectPluginsFromDir(`${__dirname}${s}builtins`); collectPluginsFromDir(env.path.pluginDir); const folders = fs.readdirSync(env.path.pluginPerUserDir); folders.forEach((folder) => { const folderPath = `${env.path.pluginPerUserDir}${s}${folder}`; if (fs.statSync(folderPath).isDirectory()) { collectPluginsFromDir(folderPath, folder); } }); } ================================================ FILE: src/qqntim-env.d.ts ================================================ /// ================================================ FILE: src/renderer/api/app.ts ================================================ import { ipcRenderer } from "electron"; class AppAPI implements QQNTim.API.Renderer.AppAPI { relaunch() { ipcRenderer.sendSync("___!app_api", ["relaunch", []]); this.quit(); } quit() { ipcRenderer.sendSync("___!app_api", ["quit", []]); } exit() { ipcRenderer.sendSync("___!app_api", ["exit", []]); } } export const appApi = new AppAPI(); ================================================ FILE: src/renderer/api/browserWindow.ts ================================================ import { ipcRenderer } from "electron"; class BrowserWindowAPI implements QQNTim.API.Renderer.BrowserWindowAPI { setSize(width: number, height: number) { ipcRenderer.sendSync( "___!browserwindow_api", { eventName: "QQNTIM_BROWSERWINDOW_API", }, ["setSize", [width, height]], ); } setMinimumSize(width: number, height: number) { ipcRenderer.sendSync( "___!browserwindow_api", { eventName: "QQNTIM_BROWSERWINDOW_API", }, ["setMinimumSize", [width, height]], ); } } export const browserWindowApi = new BrowserWindowAPI(); ================================================ FILE: src/renderer/api/dialog.ts ================================================ import { ipcRenderer } from "electron"; class DialogAPI implements QQNTim.API.Renderer.DialogAPI { async confirm(message = "") { const res = await this.messageBox({ message, buttons: ["确定", "取消"], defaultId: 0, type: "question" }); return res.response == 0; } async alert(message = "") { await this.messageBox({ message, buttons: ["确定"], defaultId: 0, type: "info" }); return; } messageBox(options: Electron.MessageBoxOptions): Promise { return ipcRenderer.invoke("___!dialog", "showMessageBox", options); } openDialog(options: Electron.OpenDialogOptions): Promise { return ipcRenderer.invoke("___!dialog", "showOpenDialog", options); } saveDialog(options: Electron.SaveDialogOptions): Promise { return ipcRenderer.invoke("___!dialog", "showSaveDialog", options); } } export const dialogApi = new DialogAPI(); ================================================ FILE: src/renderer/api/getVueId.ts ================================================ export function getVueId(element: HTMLElement) { let vueId: string | undefined; for (const item in element.dataset) { if (item.startsWith("v")) vueId = `data-${item .split("") .map((item) => { const low = item.toLocaleLowerCase(); if (low != item) return `-${low}`; else return low; }) .join("")}`; } return vueId; } ================================================ FILE: src/renderer/api/index.ts ================================================ import { allPlugins, env } from "../../common/global"; import { addInterruptIpc } from "../../common/ipc"; import { defineModules } from "../../common/patch"; import { mountVersion } from "../../common/version"; import { appApi } from "./app"; import { browserWindowApi } from "./browserWindow"; import { dialogApi } from "./dialog"; import { getVueId } from "./getVueId"; import { nt } from "./nt"; import { ntCall } from "./nt/call"; import { waitForElement } from "./waitForElement"; import { windowLoadPromise } from "./windowLoadPromise"; import * as fs from "fs-extra"; export let api: typeof QQNTim.API.Renderer; export function initAPI() { mountVersion(); nt.init(); api = { allPlugins: allPlugins, env: env, interrupt: { ipc: addInterruptIpc, }, nt: nt, browserWindow: browserWindowApi, app: appApi, dialog: dialogApi, modules: { fs: fs, }, defineModules: defineModules, utils: { waitForElement: waitForElement, getVueId: getVueId, ntCall: ntCall, }, windowLoadPromise: windowLoadPromise, }; defineModules({ "qqntim/renderer": api }); } ================================================ FILE: src/renderer/api/nt/call.ts ================================================ import { addInterruptIpc } from "../../../common/ipc"; import { webContentsId } from "../../main"; import { randomUUID } from "crypto"; import { ipcRenderer } from "electron"; class NTCallError extends Error { public code: number; public message: string; constructor(code: number, message: string) { super(); this.code = code; this.message = message; } } const pendingCallbacks: Record = {}; addInterruptIpc( (args) => { const id = args[0].callbackId; if (pendingCallbacks[id]) { pendingCallbacks[id](args); delete pendingCallbacks[id]; return false; } }, { direction: "in", }, ); export function ntCall(eventName: string, cmdName: string, args: any[], isRegister = false) { return new Promise((resolve, reject) => { const uuid = randomUUID(); pendingCallbacks[uuid] = (args: QQNTim.IPC.Args) => { if (args[1] && args[1].result != undefined && args[1].result != 0) reject(new NTCallError(args[1].result, args[1].errMsg)); else resolve(args[1]); }; ipcRenderer.send( `IPC_UP_${webContentsId}`, { type: "request", callbackId: uuid, eventName: `${eventName}-${webContentsId}${isRegister ? "-register" : ""}`, }, [cmdName, ...args], ); }); } ================================================ FILE: src/renderer/api/nt/constructor.ts ================================================ import { ntMedia } from "./media"; export function constructTextElement(ele: any): QQNTim.API.Renderer.NT.MessageElementText { return { type: "text", content: ele.textElement.content, raw: ele, }; } export function constructImageElement(ele: any, msg: any): QQNTim.API.Renderer.NT.MessageElementImage { return { type: "image", file: ele.picElement.sourcePath, downloadedPromise: ntMedia.downloadMedia(msg.msgId, ele.elementId, msg.peerUid, msg.chatType, ele.picElement.thumbPath.get(0), ele.picElement.sourcePath), raw: ele, }; } export function constructFaceElement(ele: any): QQNTim.API.Renderer.NT.MessageElementFace { return { type: "face", faceIndex: ele.faceElement.faceIndex, faceType: ele.faceElement.faceType == 1 ? "normal" : ele.faceElement.faceType == 2 ? "normal-extended" : ele.faceElement.faceType == 3 ? "super" : ele.faceElement.faceType, faceSuperIndex: ele.faceElement.stickerId && parseInt(ele.faceElement.stickerId), raw: ele, }; } export function constructRawElement(ele: any): QQNTim.API.Renderer.NT.MessageElementRaw { return { type: "raw", raw: ele, }; } export function constructMessage(msg: any): QQNTim.API.Renderer.NT.Message { const downloadedPromises: Promise[] = []; const elements = (msg.elements as any[]).map((ele): QQNTim.API.Renderer.NT.MessageElement => { if (ele.elementType == 1) return constructTextElement(ele); else if (ele.elementType == 2) { const element = constructImageElement(ele, msg); downloadedPromises.push(element.downloadedPromise); return element; } else if (ele.elementType == 6) return constructFaceElement(ele); else return constructRawElement(ele); }); return { allDownloadedPromise: Promise.all(downloadedPromises), peer: { uid: msg.peerUid, name: msg.peerName, chatType: msg.chatType == 1 ? "friend" : msg.chatType == 2 ? "group" : "others", }, sender: { uid: msg.senderUid, memberName: msg.sendMemberName || msg.sendNickName, nickName: msg.sendNickName, }, elements: elements, raw: msg, }; } export function constructUser(user: any): QQNTim.API.Renderer.NT.User { return { uid: user.uid, qid: user.qid, uin: user.uin, avatarUrl: user.avatarUrl, nickName: user.nick, bio: user.longNick, sex: { 1: "male", 2: "female", 255: "unset", 0: "unset" }[user.sex] || "others", raw: user, }; } export function constructGroup(group: any): QQNTim.API.Renderer.NT.Group { return { uid: group.groupCode, avatarUrl: group.avatarUrl, name: group.groupName, role: { 4: "master", 3: "moderator", 2: "member" }[group.memberRole] || "others", maxMembers: group.maxMember, members: group.memberCount, raw: group, }; } ================================================ FILE: src/renderer/api/nt/destructor.ts ================================================ export function destructTextElement(element: QQNTim.API.Renderer.NT.MessageElementText) { return { elementType: 1, elementId: "", textElement: { content: element.content, atType: 0, atUid: "", atTinyId: "", atNtUid: "", }, }; } export function destructImageElement(element: QQNTim.API.Renderer.NT.MessageElementImage, picElement: any) { return { elementType: 2, elementId: "", picElement: picElement, }; } export function destructFaceElement(element: QQNTim.API.Renderer.NT.MessageElementFace) { return { elementType: 6, elementId: "", faceElement: { faceIndex: element.faceIndex, faceType: element.faceType == "normal" ? 1 : element.faceType == "normal-extended" ? 2 : element.faceType == "super" ? 3 : element.faceType, ...((element.faceType == "super" || element.faceType == 3) && { packId: "1", stickerId: (element.faceSuperIndex || "0").toString(), stickerType: 1, sourceType: 1, resultId: "", superisedId: "", randomType: 1, }), }, }; } export function destructRawElement(element: QQNTim.API.Renderer.NT.MessageElementRaw) { return element.raw; } export function destructPeer(peer: QQNTim.API.Renderer.NT.Peer) { return { chatType: peer.chatType == "friend" ? 1 : peer.chatType == "group" ? 2 : 1, peerUid: peer.uid, guildId: "", }; } ================================================ FILE: src/renderer/api/nt/index.ts ================================================ import { addInterruptIpc } from "../../../common/ipc"; import { ntCall } from "./call"; import { constructGroup, constructMessage, constructUser } from "./constructor"; import { destructFaceElement, destructImageElement, destructPeer, destructRawElement, destructTextElement } from "./destructor"; import { ntMedia } from "./media"; import { NTWatcher } from "./watcher"; import { EventEmitter } from "events"; const NTEventEmitter = EventEmitter as new () => QQNTim.API.Renderer.NT.EventEmitter; class NT extends NTEventEmitter implements QQNTim.API.Renderer.NT { private sentMessageWatcher: NTWatcher; private profileChangeWatcher: NTWatcher; private friendsList: QQNTim.API.Renderer.NT.User[] = []; private groupsList: QQNTim.API.Renderer.NT.Group[] = []; public init() { this.listenNewMessages(); this.listenContactListChange(); ntMedia.init(); this.sentMessageWatcher = new NTWatcher((args) => args?.[1]?.[0]?.payload?.msgRecord?.peerUid, "ns-ntApi", "nodeIKernelMsgListener/onAddSendMsg", "in", "request"); this.profileChangeWatcher = new NTWatcher((args) => args?.[1]?.[0]?.payload?.profiles?.keys()?.next()?.value, "ns-ntApi", "nodeIKernelProfileListener/onProfileSimpleChanged", "in", "request"); } private listenNewMessages() { addInterruptIpc( (args) => { const messages = (args?.[1]?.[0]?.payload?.msgList as any[]).map((msg): QQNTim.API.Renderer.NT.Message => constructMessage(msg)); this.emit("new-messages", messages); }, { eventName: "ns-ntApi", cmdName: "nodeIKernelMsgListener/onRecvMsg", direction: "in", type: "request" }, ); } private listenContactListChange() { addInterruptIpc( (args) => { this.friendsList = []; ((args?.[1]?.[0]?.payload?.data || []) as any[]).forEach((category) => this.friendsList.push(...((category?.buddyList || []) as any[]).map((friend) => constructUser(friend)))); this.emit("friends-list-updated", this.friendsList); }, { eventName: "ns-ntApi", cmdName: "nodeIKernelBuddyListener/onBuddyListChange", direction: "in", type: "request" }, ); addInterruptIpc( (args) => { this.groupsList = ((args[1]?.[0]?.payload?.groupList || []) as any[]).map((group) => constructGroup(group)); this.emit("groups-list-updated", this.groupsList); }, { eventName: "ns-ntApi", cmdName: "nodeIKernelGroupListener/onGroupListUpdate", direction: "in", type: "request" }, ); } async getAccountInfo(): Promise { return await ntCall("ns-BusinessApi", "fetchAuthData", []).then((data) => { if (!data) return; return { uid: data.uid, uin: data.uin } as QQNTim.API.Renderer.NT.LoginAccount; }); } async getUserInfo(uid: string): Promise { ntCall("ns-ntApi", "nodeIKernelProfileService/getUserDetailInfo", [{ uid: uid }, undefined]); return await this.profileChangeWatcher.wait(uid).then((args) => constructUser(args?.[1]?.[0]?.payload?.profiles?.get(uid))); } async revokeMessage(peer: QQNTim.API.Renderer.NT.Peer, message: string) { await ntCall("ns-ntApi", "nodeIKernelMsgService/recallMsg", [ { peer: destructPeer(peer), msgIds: [message], }, ]); } async sendMessage(peer: QQNTim.API.Renderer.NT.Peer, elements: QQNTim.API.Renderer.NT.MessageElement[]) { ntCall("ns-ntApi", "nodeIKernelMsgService/sendMsg", [ { msgId: "0", peer: destructPeer(peer), msgElements: await Promise.all( elements.map(async (element) => { if (element.type == "text") return destructTextElement(element); else if (element.type == "image") return destructImageElement(element, await ntMedia.prepareImageElement(element.file)); else if (element.type == "face") return destructFaceElement(element); else if (element.type == "raw") return destructRawElement(element); else return null; }), ), }, null, ]); return await this.sentMessageWatcher.wait(peer.uid).then((args) => args?.[1]?.[0]?.payload?.msgRecord?.msgId); } async getFriendsList(forced: boolean) { ntCall("ns-ntApi", "nodeIKernelBuddyService/getBuddyList", [{ force_update: forced }, undefined]); return await new Promise((resolve) => { this.once("friends-list-updated", (list) => resolve(list)); }); } async getGroupsList(forced: boolean) { ntCall("ns-ntApi", "nodeIKernelGroupService/getGroupList", [{ forceFetch: forced }, undefined]); return await new Promise((resolve) => { this.once("groups-list-updated", (list) => resolve(list)); }); } async getPreviousMessages(peer: QQNTim.API.Renderer.NT.Peer, count = 20, startMsgId = "0") { try { const msgs = await ntCall("ns-ntApi", "nodeIKernelMsgService/getMsgsIncludeSelf", [ { peer: destructPeer(peer), msgId: startMsgId, cnt: count, queryOrder: true, }, undefined, ]); const messages = (msgs.msgList as any[]).map((msg) => constructMessage(msg)); return messages; } catch { return []; } } } export const nt = new NT(); ================================================ FILE: src/renderer/api/nt/media.ts ================================================ import { ntCall } from "./call"; import { NTWatcher } from "./watcher"; import { exists } from "fs-extra"; class NTMedia { private mediaDownloadWatcher: NTWatcher; private registerEventsPromise: Promise; public init() { this.mediaDownloadWatcher = new NTWatcher((args) => args[1][0].payload?.notifyInfo?.msgElementId, "ns-ntApi", "nodeIKernelMsgListener/onRichMediaDownloadComplete", "in", "request"); this.registerEventsPromise = ntCall("ns-ntApi", "nodeIKernelMsgListener/onRichMediaDownloadComplete", [], true); } public async prepareImageElement(file: string) { const type = await ntCall("ns-fsApi", "getFileType", [file]); const md5 = await ntCall("ns-fsApi", "getFileMd5", [file]); const fileName = `${md5}.${type.ext}`; const filePath = await ntCall("ns-ntApi", "nodeIKernelMsgService/getRichMediaFilePath", [ { md5HexStr: md5, fileName: fileName, elementType: 2, elementSubType: 0, thumbSize: 0, needCreate: true, fileType: 1, }, ]); await ntCall("ns-fsApi", "copyFile", [{ fromPath: file, toPath: filePath }]); const imageSize = await ntCall("ns-fsApi", "getImageSizeFromPath", [file]); const fileSize = await ntCall("ns-fsApi", "getFileSize", [file]); return { md5HexStr: md5, fileSize: fileSize, picWidth: imageSize.width, picHeight: imageSize.height, fileName: fileName, sourcePath: filePath, original: true, picType: 1001, picSubType: 0, fileUuid: "", fileSubId: "", thumbFileSize: 0, summary: "", }; } public async downloadMedia(msgId: string, elementId: string, peerUid: string, chatType: number, filePath: string, originalFilePath: string) { if (await exists(originalFilePath)) return; await this.registerEventsPromise; ntCall("ns-ntApi", "nodeIKernelMsgService/downloadRichMedia", [ { getReq: { msgId: msgId, chatType: chatType, peerUid: peerUid, elementId: elementId, thumbSize: 0, downloadType: 2, filePath: filePath, }, }, undefined, ]); return await this.mediaDownloadWatcher.wait(elementId).then(() => undefined); } } export const ntMedia = new NTMedia(); ================================================ FILE: src/renderer/api/nt/watcher.ts ================================================ import { addInterruptIpc } from "../../../common/ipc"; export class NTWatcher { private pendingList = {} as Record; constructor(getId: (args: QQNTim.IPC.Args) => T, eventName: string, cmdName: string, direction?: QQNTim.IPC.Direction, type?: QQNTim.IPC.Type) { addInterruptIpc( (args) => { const id = getId(args); if (this.pendingList[id]) { this.pendingList[id](args); delete this.pendingList[id]; return false; } }, { type: type, eventName: eventName, cmdName: cmdName, direction: direction }, ); } wait(id: T) { return new Promise>((resolve) => { this.pendingList[id] = (args: QQNTim.IPC.Args) => { resolve(args); }; }); } } ================================================ FILE: src/renderer/api/waitForElement.ts ================================================ import { windowLoadPromise } from "./windowLoadPromise"; let waitForElementSelectors: [string, (element: Element) => void][] = []; windowLoadPromise.then(() => new MutationObserver(() => refreshStatus()).observe(document.documentElement, { childList: true, subtree: true, }), ); export function refreshStatus() { waitForElementSelectors = waitForElementSelectors.filter(([selector, callback]) => { const element = document.querySelector(selector); element && callback(element); return !element; }); } export function waitForElement(selector: string) { return new Promise((resolve) => { waitForElementSelectors.push([ selector, (element) => { resolve(element as T); }, ]); refreshStatus(); }); } ================================================ FILE: src/renderer/api/windowLoadPromise.ts ================================================ export const windowLoadPromise = new Promise((resolve) => window.addEventListener("load", () => resolve())); ================================================ FILE: src/renderer/debugger.ts ================================================ import { env } from "../common/global"; import { debuggerOrigin, webContentsId } from "./main"; export function attachDebugger() { if (!env.config.useNativeDevTools) window.addEventListener("DOMContentLoaded", () => { // 将标题临时改为当前 WebContents ID 用于标识此窗口 const oldTitle = document.title; document.title = webContentsId; window.addEventListener("load", () => { document.title = oldTitle == "" ? "QQ" : oldTitle; }); const scriptTag = document.createElement("script"); scriptTag.src = `${debuggerOrigin}/target.js`; document.head.appendChild(scriptTag); }); } ================================================ FILE: src/renderer/loader.ts ================================================ import { loadPlugins } from "../common/loader"; import { windowLoadPromise } from "./api/windowLoadPromise"; import { ipcRenderer } from "electron"; import * as fs from "fs-extra"; let scripts: [QQNTim.Plugin, string][] = []; const stylesheets: [QQNTim.Plugin, string][] = []; function detectCurrentPage(): QQNTim.Manifest.PageWithAbout { const url = window.location.href; for (const [keyword, name] of [ ["login", "login"], ["main", "main"], ["chat", "chat"], ["setting", "settings"], ["about", "about"], ] as [string, QQNTim.Manifest.PageWithAbout][]) { if (url.includes(keyword)) return name; } return "others"; } function shouldInject(injection: QQNTim.Plugin.Injection, page: QQNTim.Manifest.Page) { return injection.type == "renderer" && (!injection.pattern || injection.pattern.test(window.location.href)) && (!injection.page || injection.page.includes(page)); } export function applyPlugins(allPlugins: QQNTim.Plugin.AllUsersPlugins, uin = "") { const page = detectCurrentPage(); if (page == "about") return false; loadPlugins(allPlugins, uin, (injection) => shouldInject(injection, page), scripts, stylesheets); applyScripts(); windowLoadPromise.then(() => applyStylesheets()); if (uin != "") ipcRenderer.send("___!apply_plugins", uin); return true; } function applyStylesheets() { console.log("[!Loader] 正在注入 CSS", stylesheets); let element: HTMLStyleElement = document.querySelector("#qqntim_injected_styles")!; if (element) element.remove(); element = document.createElement("style"); element.id = "qqntim_injected_styles"; element.innerHTML = stylesheets.map(([plugin, stylesheet]) => `/* ${plugin.manifest.id.replaceAll("/", "-")} - ${stylesheet.replaceAll("/", "-")} */\n${fs.readFileSync(stylesheet).toString()}`).join("\n"); document.body.appendChild(element); } function applyScripts() { scripts = scripts.filter(([plugin, script]) => { try { const mod = require(script); if (mod) { const entry = new ((mod.default || mod) as typeof QQNTim.Entry.Renderer)(); windowLoadPromise.then(() => entry.onWindowLoaded?.()); } return false; } catch (reason) { console.error(`[!Loader] 运行此插件脚本时出现意外错误:${script},请联系插件作者 (${plugin.manifest.author}) 解决`); console.error(reason); } return true; }); } ================================================ FILE: src/renderer/main.ts ================================================ import { setAllPlugins, setEnv } from "../common/global"; import { watchIpc } from "../common/ipc"; import { initAPI } from "./api"; import { nt } from "./api/nt"; import { attachDebugger } from "./debugger"; import { applyPlugins } from "./loader"; import { patchLogger, patchModuleLoader } from "./patch"; import { hookVue3 } from "./vueHelper"; import { ipcRenderer } from "electron"; export const { enabled, preload, debuggerOrigin, webContentsId, plugins, env, hasColorSupport } = ipcRenderer.sendSync("___!boot"); patchModuleLoader(); if (enabled) { setEnv(env); setAllPlugins(plugins); patchLogger(); watchIpc(); hookVue3(); attachDebugger(); initAPI(); const timer = setInterval(() => { if (window.location.href.includes("blank")) return; clearInterval(timer); applyPlugins(plugins); nt.getAccountInfo().then((account) => { if (!account) return; const uin = account.uin; applyPlugins(plugins, uin); }); console.log("[!Main] QQNTim 加载成功"); }, 1); } preload.forEach((item: string) => require(item)); ================================================ FILE: src/renderer/patch.ts ================================================ import { env } from "../common/global"; import { handleIpc } from "../common/ipc"; import { defineModules, getModule } from "../common/patch"; import { printObject } from "../common/utils/console"; import { getter, setter } from "../common/watch"; import { hasColorSupport } from "./main"; import { contextBridge, ipcRenderer } from "electron"; import { Module } from "module"; import * as React from "react"; import * as ReactDOM from "react-dom"; import * as ReactDOMClient from "react-dom/client"; import * as ReactJSXRuntime from "react/jsx-runtime"; function patchIpcRenderer() { return new Proxy(ipcRenderer, { get(target, p) { if (p == "on") return (channel: string, listener: (event: any, ...args: any[]) => void) => { target.on(channel, (event: any, ...args: QQNTim.IPC.Args) => { if (handleIpc(args, "in", channel)) listener(event, ...args); }); }; else if (p == "send") return (channel: string, ...args: QQNTim.IPC.Args) => { if (handleIpc(args, "out", channel)) target.send(channel, ...args); }; else if (p == "sendSync") return (channel: string, ...args: QQNTim.IPC.Args) => { if (handleIpc(args, "out", channel)) return target.sendSync(channel, ...args); }; return getter(undefined, target, p as any); }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, }); } function patchContextBridge() { return new Proxy(contextBridge, { get(target, p) { if (p == "exposeInMainWorld") return (apiKey: string, api: any) => { window[apiKey] = api; }; return getter(undefined, target, p as any); }, set(target, p, newValue) { return setter(undefined, target, p as any, newValue); }, }); } export function patchModuleLoader() { const patchedElectron: typeof Electron.CrossProcessExports = { ...require("electron"), ipcRenderer: patchIpcRenderer(), contextBridge: patchContextBridge(), }; defineModules({ electron: patchedElectron, react: React, "react/jsx-runtime": ReactJSXRuntime, "react-dom": ReactDOM, "react-dom/client": ReactDOMClient }); const loadBackend = (Module as any)._load; (Module as any)._load = (request: string, parent: NodeModule, isMain: boolean) => { // 重写模块加载以隐藏 `vm` 模块弃用提示 if (request == "vm") request = "node:vm"; return getModule(request) || loadBackend(request, parent, isMain); }; } export function patchLogger() { if (env.config.useNativeDevTools) return; const log = (level: number, ...args: any[]) => { const serializedArgs: any[] = []; for (const arg of args) { serializedArgs.push(typeof arg == "string" ? arg : printObject(arg, hasColorSupport)); } ipcRenderer.send("___!log", level, ...serializedArgs); }; ( [ ["debug", 0], ["log", 1], ["info", 2], ["warn", 3], ["error", 4], ] as [string, number][] ).forEach(([method, level]) => { console[method] = (...args: any[]) => log(level, ...args); }); } ================================================ FILE: src/renderer/vueHelper.ts ================================================ interface Component { vnode: { el: VueElement; component: Component; }; bum: Function[]; uid: number; } interface VueElement extends HTMLElement { __VUE__?: Component[]; } // Modified from https://greasyfork.org/zh-CN/scripts/449444-hook-vue3-app // Thanks to DreamNya & Cesaryuan ;) const elements = new WeakMap(); (window as any).__VUE_ELEMENTS__ = elements; function watchComponentUnmount(component: Component) { if (!component.bum) component.bum = []; component.bum.push(() => { const element = component.vnode.el; if (element) { const components = elements.get(element); if (components?.length == 1) elements.delete(element); else components?.splice(components.indexOf(component)); if (element.__VUE__?.length == 1) element.__VUE__ = undefined; else element.__VUE__?.splice(element.__VUE__.indexOf(component)); } }); } function watchComponentMount(component: Component) { let value: HTMLElement; Object.defineProperty(component.vnode, "el", { get() { return value; }, set(newValue) { value = newValue; if (value) recordComponent(component); }, }); } function recordComponent(component: Component) { let element = component.vnode.el; while (!(element instanceof HTMLElement)) element = (element as VueElement).parentElement!; // Expose component to element's __VUE__ property if (element.__VUE__) element.__VUE__.push(component); else element.__VUE__ = [component]; // Add class to element element.classList.add("vue-component"); // Map element to components const components = elements.get(element); if (components) components.push(component); else elements.set(element, [component]); watchComponentUnmount(component); } export function hookVue3() { window.Proxy = new Proxy(window.Proxy, { construct(target, [proxyTarget, proxyHandler]) { const component = proxyTarget?._ as Component; if (component?.uid >= 0) { const element = component.vnode.el; if (element) recordComponent(component); else watchComponentMount(component); } return new target(proxyTarget, proxyHandler); }, }); console.log("[!VueHelper] 输入 `__VUE_ELEMENTS__` 查看所有已挂载的 Vue 组件"); } ================================================ FILE: src/typings/COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: src/typings/COPYING.LESSER ================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: src/typings/electron.d.ts ================================================ // Type definitions for Electron 25.2.0 // Project: http://electronjs.org/ // Definitions by: The Electron Team // Definitions: https://github.com/electron/typescript-definitions /// type DOMEvent = Event; type GlobalResponse = Response; type GlobalRequest = Request; declare namespace Electron { const NodeEventEmitter: typeof import("events").EventEmitter; type Accelerator = string; type Event = { preventDefault: () => void; readonly defaultPrevented: boolean; } & Params; interface App extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/app /** * Emitted when Chrome's accessibility support changes. This event fires when * assistive technologies, such as screen readers, are enabled or disabled. See * https://www.chromium.org/developers/design-documents/accessibility for more * details. * * @platform darwin,win32 */ on( event: "accessibility-support-changed", listener: ( event: Event, /** * `true` when Chrome's accessibility support is enabled, `false` otherwise. */ accessibilitySupportEnabled: boolean, ) => void, ): this; once( event: "accessibility-support-changed", listener: ( event: Event, /** * `true` when Chrome's accessibility support is enabled, `false` otherwise. */ accessibilitySupportEnabled: boolean, ) => void, ): this; addListener( event: "accessibility-support-changed", listener: ( event: Event, /** * `true` when Chrome's accessibility support is enabled, `false` otherwise. */ accessibilitySupportEnabled: boolean, ) => void, ): this; removeListener( event: "accessibility-support-changed", listener: ( event: Event, /** * `true` when Chrome's accessibility support is enabled, `false` otherwise. */ accessibilitySupportEnabled: boolean, ) => void, ): this; /** * Emitted when the application is activated. Various actions can trigger this * event, such as launching the application for the first time, attempting to * re-launch the application when it's already running, or clicking on the * application's dock or taskbar icon. * * @platform darwin */ on(event: "activate", listener: (event: Event, hasVisibleWindows: boolean) => void): this; once(event: "activate", listener: (event: Event, hasVisibleWindows: boolean) => void): this; addListener(event: "activate", listener: (event: Event, hasVisibleWindows: boolean) => void): this; removeListener(event: "activate", listener: (event: Event, hasVisibleWindows: boolean) => void): this; /** * Emitted during Handoff after an activity from this device was successfully * resumed on another one. * * @platform darwin */ on( event: "activity-was-continued", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; once( event: "activity-was-continued", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; addListener( event: "activity-was-continued", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; removeListener( event: "activity-was-continued", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; /** * Emitted before the application starts closing its windows. Calling * `event.preventDefault()` will prevent the default behavior, which is terminating * the application. * * **Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`, * then `before-quit` is emitted _after_ emitting `close` event on all windows and * closing them. * * **Note:** On Windows, this event will not be emitted if the app is closed due to * a shutdown/restart of the system or a user logout. */ on(event: "before-quit", listener: (event: Event) => void): this; once(event: "before-quit", listener: (event: Event) => void): this; addListener(event: "before-quit", listener: (event: Event) => void): this; removeListener(event: "before-quit", listener: (event: Event) => void): this; /** * Emitted when a browserWindow gets blurred. */ on(event: "browser-window-blur", listener: (event: Event, window: BrowserWindow) => void): this; once(event: "browser-window-blur", listener: (event: Event, window: BrowserWindow) => void): this; addListener(event: "browser-window-blur", listener: (event: Event, window: BrowserWindow) => void): this; removeListener(event: "browser-window-blur", listener: (event: Event, window: BrowserWindow) => void): this; /** * Emitted when a new browserWindow is created. */ on(event: "browser-window-created", listener: (event: Event, window: BrowserWindow) => void): this; once(event: "browser-window-created", listener: (event: Event, window: BrowserWindow) => void): this; addListener(event: "browser-window-created", listener: (event: Event, window: BrowserWindow) => void): this; removeListener(event: "browser-window-created", listener: (event: Event, window: BrowserWindow) => void): this; /** * Emitted when a browserWindow gets focused. */ on(event: "browser-window-focus", listener: (event: Event, window: BrowserWindow) => void): this; once(event: "browser-window-focus", listener: (event: Event, window: BrowserWindow) => void): this; addListener(event: "browser-window-focus", listener: (event: Event, window: BrowserWindow) => void): this; removeListener(event: "browser-window-focus", listener: (event: Event, window: BrowserWindow) => void): this; /** * Emitted when failed to verify the `certificate` for `url`, to trust the * certificate you should prevent the default behavior with * `event.preventDefault()` and call `callback(true)`. */ on( event: "certificate-error", listener: ( event: Event, webContents: WebContents, url: string, /** * The error code */ error: string, certificate: Certificate, callback: (isTrusted: boolean) => void, isMainFrame: boolean, ) => void, ): this; once( event: "certificate-error", listener: ( event: Event, webContents: WebContents, url: string, /** * The error code */ error: string, certificate: Certificate, callback: (isTrusted: boolean) => void, isMainFrame: boolean, ) => void, ): this; addListener( event: "certificate-error", listener: ( event: Event, webContents: WebContents, url: string, /** * The error code */ error: string, certificate: Certificate, callback: (isTrusted: boolean) => void, isMainFrame: boolean, ) => void, ): this; removeListener( event: "certificate-error", listener: ( event: Event, webContents: WebContents, url: string, /** * The error code */ error: string, certificate: Certificate, callback: (isTrusted: boolean) => void, isMainFrame: boolean, ) => void, ): this; /** * Emitted when the child process unexpectedly disappears. This is normally because * it was crashed or killed. It does not include renderer processes. */ on(event: "child-process-gone", listener: (event: Event, details: Details) => void): this; once(event: "child-process-gone", listener: (event: Event, details: Details) => void): this; addListener(event: "child-process-gone", listener: (event: Event, details: Details) => void): this; removeListener(event: "child-process-gone", listener: (event: Event, details: Details) => void): this; /** * Emitted during Handoff when an activity from a different device wants to be * resumed. You should call `event.preventDefault()` if you want to handle this * event. * * A user activity can be continued only in an app that has the same developer Team * ID as the activity's source app and that supports the activity's type. Supported * activity types are specified in the app's `Info.plist` under the * `NSUserActivityTypes` key. * * @platform darwin */ on( event: "continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity on another device. */ userInfo: unknown, details: ContinueActivityDetails, ) => void, ): this; once( event: "continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity on another device. */ userInfo: unknown, details: ContinueActivityDetails, ) => void, ): this; addListener( event: "continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity on another device. */ userInfo: unknown, details: ContinueActivityDetails, ) => void, ): this; removeListener( event: "continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity on another device. */ userInfo: unknown, details: ContinueActivityDetails, ) => void, ): this; /** * Emitted during Handoff when an activity from a different device fails to be * resumed. * * @platform darwin */ on( event: "continue-activity-error", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * A string with the error's localized description. */ error: string, ) => void, ): this; once( event: "continue-activity-error", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * A string with the error's localized description. */ error: string, ) => void, ): this; addListener( event: "continue-activity-error", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * A string with the error's localized description. */ error: string, ) => void, ): this; removeListener( event: "continue-activity-error", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * A string with the error's localized description. */ error: string, ) => void, ): this; /** * Emitted when the application becomes active. This differs from the `activate` * event in that `did-become-active` is emitted every time the app becomes active, * not only when Dock icon is clicked or application is re-launched. It is also * emitted when a user switches to the app via the macOS App Switcher. * * @platform darwin */ on(event: "did-become-active", listener: (event: Event) => void): this; once(event: "did-become-active", listener: (event: Event) => void): this; addListener(event: "did-become-active", listener: (event: Event) => void): this; removeListener(event: "did-become-active", listener: (event: Event) => void): this; /** * Emitted when the app is no longer active and doesn’t have focus. This can be * triggered, for example, by clicking on another application or by using the macOS * App Switcher to switch to another application. * * @platform darwin */ on(event: "did-resign-active", listener: (event: Event) => void): this; once(event: "did-resign-active", listener: (event: Event) => void): this; addListener(event: "did-resign-active", listener: (event: Event) => void): this; removeListener(event: "did-resign-active", listener: (event: Event) => void): this; /** * Emitted whenever there is a GPU info update. */ on(event: "gpu-info-update", listener: Function): this; once(event: "gpu-info-update", listener: Function): this; addListener(event: "gpu-info-update", listener: Function): this; removeListener(event: "gpu-info-update", listener: Function): this; /** * Emitted when the GPU process crashes or is killed. * * **Deprecated:** This event is superceded by the `child-process-gone` event which * contains more information about why the child process disappeared. It isn't * always because it crashed. The `killed` boolean can be replaced by checking * `reason === 'killed'` when you switch to that event. * * @deprecated */ on(event: "gpu-process-crashed", listener: (event: Event, killed: boolean) => void): this; once(event: "gpu-process-crashed", listener: (event: Event, killed: boolean) => void): this; addListener(event: "gpu-process-crashed", listener: (event: Event, killed: boolean) => void): this; removeListener(event: "gpu-process-crashed", listener: (event: Event, killed: boolean) => void): this; /** * Emitted when `webContents` wants to do basic auth. * * The default behavior is to cancel all authentications. To override this you * should prevent the default behavior with `event.preventDefault()` and call * `callback(username, password)` with the credentials. * * If `callback` is called without a username or password, the authentication * request will be cancelled and the authentication error will be returned to the * page. */ on(event: "login", listener: (event: Event, webContents: WebContents, authenticationResponseDetails: AuthenticationResponseDetails, authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; once(event: "login", listener: (event: Event, webContents: WebContents, authenticationResponseDetails: AuthenticationResponseDetails, authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; addListener(event: "login", listener: (event: Event, webContents: WebContents, authenticationResponseDetails: AuthenticationResponseDetails, authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; removeListener(event: "login", listener: (event: Event, webContents: WebContents, authenticationResponseDetails: AuthenticationResponseDetails, authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; /** * Emitted when the user clicks the native macOS new tab button. The new tab button * is only visible if the current `BrowserWindow` has a `tabbingIdentifier` * * @platform darwin */ on(event: "new-window-for-tab", listener: (event: Event) => void): this; once(event: "new-window-for-tab", listener: (event: Event) => void): this; addListener(event: "new-window-for-tab", listener: (event: Event) => void): this; removeListener(event: "new-window-for-tab", listener: (event: Event) => void): this; /** * Emitted when the user wants to open a file with the application. The `open-file` * event is usually emitted when the application is already open and the OS wants * to reuse the application to open the file. `open-file` is also emitted when a * file is dropped onto the dock and the application is not yet running. Make sure * to listen for the `open-file` event very early in your application startup to * handle this case (even before the `ready` event is emitted). * * You should call `event.preventDefault()` if you want to handle this event. * * On Windows, you have to parse `process.argv` (in the main process) to get the * filepath. * * @platform darwin */ on(event: "open-file", listener: (event: Event, path: string) => void): this; once(event: "open-file", listener: (event: Event, path: string) => void): this; addListener(event: "open-file", listener: (event: Event, path: string) => void): this; removeListener(event: "open-file", listener: (event: Event, path: string) => void): this; /** * Emitted when the user wants to open a URL with the application. Your * application's `Info.plist` file must define the URL scheme within the * `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. * * As with the `open-file` event, be sure to register a listener for the `open-url` * event early in your application startup to detect if the the application being * is being opened to handle a URL. If you register the listener in response to a * `ready` event, you'll miss URLs that trigger the launch of your application. * * @platform darwin */ on(event: "open-url", listener: (event: Event, url: string) => void): this; once(event: "open-url", listener: (event: Event, url: string) => void): this; addListener(event: "open-url", listener: (event: Event, url: string) => void): this; removeListener(event: "open-url", listener: (event: Event, url: string) => void): this; /** * Emitted when the application is quitting. * * **Note:** On Windows, this event will not be emitted if the app is closed due to * a shutdown/restart of the system or a user logout. */ on(event: "quit", listener: (event: Event, exitCode: number) => void): this; once(event: "quit", listener: (event: Event, exitCode: number) => void): this; addListener(event: "quit", listener: (event: Event, exitCode: number) => void): this; removeListener(event: "quit", listener: (event: Event, exitCode: number) => void): this; /** * Emitted once, when Electron has finished initializing. On macOS, `launchInfo` * holds the `userInfo` of the `NSUserNotification` or information from * `UNNotificationResponse` that was used to open the application, if it was * launched from Notification Center. You can also call `app.isReady()` to check if * this event has already fired and `app.whenReady()` to get a Promise that is * fulfilled when Electron is initialized. */ on( event: "ready", listener: ( event: Event, /** * @platform darwin */ launchInfo: Record | NotificationResponse, ) => void, ): this; once( event: "ready", listener: ( event: Event, /** * @platform darwin */ launchInfo: Record | NotificationResponse, ) => void, ): this; addListener( event: "ready", listener: ( event: Event, /** * @platform darwin */ launchInfo: Record | NotificationResponse, ) => void, ): this; removeListener( event: "ready", listener: ( event: Event, /** * @platform darwin */ launchInfo: Record | NotificationResponse, ) => void, ): this; /** * Emitted when the renderer process unexpectedly disappears. This is normally * because it was crashed or killed. */ on(event: "render-process-gone", listener: (event: Event, webContents: WebContents, details: RenderProcessGoneDetails) => void): this; once(event: "render-process-gone", listener: (event: Event, webContents: WebContents, details: RenderProcessGoneDetails) => void): this; addListener(event: "render-process-gone", listener: (event: Event, webContents: WebContents, details: RenderProcessGoneDetails) => void): this; removeListener(event: "render-process-gone", listener: (event: Event, webContents: WebContents, details: RenderProcessGoneDetails) => void): this; /** * Emitted when the renderer process of `webContents` crashes or is killed. * * **Deprecated:** This event is superceded by the `render-process-gone` event * which contains more information about why the render process disappeared. It * isn't always because it crashed. The `killed` boolean can be replaced by * checking `reason === 'killed'` when you switch to that event. * * @deprecated */ on(event: "renderer-process-crashed", listener: (event: Event, webContents: WebContents, killed: boolean) => void): this; once(event: "renderer-process-crashed", listener: (event: Event, webContents: WebContents, killed: boolean) => void): this; addListener(event: "renderer-process-crashed", listener: (event: Event, webContents: WebContents, killed: boolean) => void): this; removeListener(event: "renderer-process-crashed", listener: (event: Event, webContents: WebContents, killed: boolean) => void): this; /** * This event will be emitted inside the primary instance of your application when * a second instance has been executed and calls `app.requestSingleInstanceLock()`. * * `argv` is an Array of the second instance's command line arguments, and * `workingDirectory` is its current working directory. Usually applications * respond to this by making their primary window focused and non-minimized. * * **Note:** `argv` will not be exactly the same list of arguments as those passed * to the second instance. The order might change and additional arguments might be * appended. If you need to maintain the exact same arguments, it's advised to use * `additionalData` instead. * * **Note:** If the second instance is started by a different user than the first, * the `argv` array will not include the arguments. * * This event is guaranteed to be emitted after the `ready` event of `app` gets * emitted. * * **Note:** Extra command line arguments might be added by Chromium, such as * `--original-process-start-time`. */ on( event: "second-instance", listener: ( event: Event, /** * An array of the second instance's command line arguments */ argv: string[], /** * The second instance's working directory */ workingDirectory: string, /** * A JSON object of additional data passed from the second instance */ additionalData: unknown, ) => void, ): this; once( event: "second-instance", listener: ( event: Event, /** * An array of the second instance's command line arguments */ argv: string[], /** * The second instance's working directory */ workingDirectory: string, /** * A JSON object of additional data passed from the second instance */ additionalData: unknown, ) => void, ): this; addListener( event: "second-instance", listener: ( event: Event, /** * An array of the second instance's command line arguments */ argv: string[], /** * The second instance's working directory */ workingDirectory: string, /** * A JSON object of additional data passed from the second instance */ additionalData: unknown, ) => void, ): this; removeListener( event: "second-instance", listener: ( event: Event, /** * An array of the second instance's command line arguments */ argv: string[], /** * The second instance's working directory */ workingDirectory: string, /** * A JSON object of additional data passed from the second instance */ additionalData: unknown, ) => void, ): this; /** * Emitted when a client certificate is requested. * * The `url` corresponds to the navigation entry requesting the client certificate * and `callback` can be called with an entry filtered from the list. Using * `event.preventDefault()` prevents the application from using the first * certificate from the store. */ on(event: "select-client-certificate", listener: (event: Event, webContents: WebContents, url: string, certificateList: Certificate[], callback: (certificate?: Certificate) => void) => void): this; once(event: "select-client-certificate", listener: (event: Event, webContents: WebContents, url: string, certificateList: Certificate[], callback: (certificate?: Certificate) => void) => void): this; addListener(event: "select-client-certificate", listener: (event: Event, webContents: WebContents, url: string, certificateList: Certificate[], callback: (certificate?: Certificate) => void) => void): this; removeListener(event: "select-client-certificate", listener: (event: Event, webContents: WebContents, url: string, certificateList: Certificate[], callback: (certificate?: Certificate) => void) => void): this; /** * Emitted when Electron has created a new `session`. */ on(event: "session-created", listener: (session: Session) => void): this; once(event: "session-created", listener: (session: Session) => void): this; addListener(event: "session-created", listener: (session: Session) => void): this; removeListener(event: "session-created", listener: (session: Session) => void): this; /** * Emitted when Handoff is about to be resumed on another device. If you need to * update the state to be transferred, you should call `event.preventDefault()` * immediately, construct a new `userInfo` dictionary and call * `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will * fail and `continue-activity-error` will be called. * * @platform darwin */ on( event: "update-activity-state", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; once( event: "update-activity-state", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; addListener( event: "update-activity-state", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; removeListener( event: "update-activity-state", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, /** * Contains app-specific state stored by the activity. */ userInfo: unknown, ) => void, ): this; /** * Emitted when a new webContents is created. */ on(event: "web-contents-created", listener: (event: Event, webContents: WebContents) => void): this; once(event: "web-contents-created", listener: (event: Event, webContents: WebContents) => void): this; addListener(event: "web-contents-created", listener: (event: Event, webContents: WebContents) => void): this; removeListener(event: "web-contents-created", listener: (event: Event, webContents: WebContents) => void): this; /** * Emitted during Handoff before an activity from a different device wants to be * resumed. You should call `event.preventDefault()` if you want to handle this * event. * * @platform darwin */ on( event: "will-continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, ) => void, ): this; once( event: "will-continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, ) => void, ): this; addListener( event: "will-continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, ) => void, ): this; removeListener( event: "will-continue-activity", listener: ( event: Event, /** * A string identifying the activity. Maps to `NSUserActivity.activityType`. */ type: string, ) => void, ): this; /** * Emitted when the application has finished basic startup. On Windows and Linux, * the `will-finish-launching` event is the same as the `ready` event; on macOS, * this event represents the `applicationWillFinishLaunching` notification of * `NSApplication`. * * In most cases, you should do everything in the `ready` event handler. */ on(event: "will-finish-launching", listener: Function): this; once(event: "will-finish-launching", listener: Function): this; addListener(event: "will-finish-launching", listener: Function): this; removeListener(event: "will-finish-launching", listener: Function): this; /** * Emitted when all windows have been closed and the application will quit. Calling * `event.preventDefault()` will prevent the default behavior, which is terminating * the application. * * See the description of the `window-all-closed` event for the differences between * the `will-quit` and `window-all-closed` events. * * **Note:** On Windows, this event will not be emitted if the app is closed due to * a shutdown/restart of the system or a user logout. */ on(event: "will-quit", listener: (event: Event) => void): this; once(event: "will-quit", listener: (event: Event) => void): this; addListener(event: "will-quit", listener: (event: Event) => void): this; removeListener(event: "will-quit", listener: (event: Event) => void): this; /** * Emitted when all windows have been closed. * * If you do not subscribe to this event and all windows are closed, the default * behavior is to quit the app; however, if you subscribe, you control whether the * app quits or not. If the user pressed `Cmd + Q`, or the developer called * `app.quit()`, Electron will first try to close all the windows and then emit the * `will-quit` event, and in this case the `window-all-closed` event would not be * emitted. */ on(event: "window-all-closed", listener: Function): this; once(event: "window-all-closed", listener: Function): this; addListener(event: "window-all-closed", listener: Function): this; removeListener(event: "window-all-closed", listener: Function): this; /** * Adds `path` to the recent documents list. * * This list is managed by the OS. On Windows, you can visit the list from the task * bar, and on macOS, you can visit it from dock menu. * * @platform darwin,win32 */ addRecentDocument(path: string): void; /** * Clears the recent documents list. * * @platform darwin,win32 */ clearRecentDocuments(): void; /** * Configures host resolution (DNS and DNS-over-HTTPS). By default, the following * resolvers will be used, in order: * * * DNS-over-HTTPS, if the DNS provider supports it, then * * the built-in resolver (enabled on macOS only by default), then * * the system's resolver (e.g. `getaddrinfo`). * * This can be configured to either restrict usage of non-encrypted DNS * (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). * It is also possible to enable or disable the built-in resolver. * * To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you * do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, * in case the user's DNS configuration does not include a provider that supports * DoH. * * This API must be called after the `ready` event is emitted. */ configureHostResolver(options: ConfigureHostResolverOptions): void; /** * By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain * basis if the GPU processes crashes too frequently. This function disables that * behavior. * * This method can only be called before app is ready. */ disableDomainBlockingFor3DAPIs(): void; /** * Disables hardware acceleration for current app. * * This method can only be called before app is ready. */ disableHardwareAcceleration(): void; /** * Enables full sandbox mode on the app. This means that all renderers will be * launched sandboxed, regardless of the value of the `sandbox` flag in * WebPreferences. * * This method can only be called before app is ready. */ enableSandbox(): void; /** * Exits immediately with `exitCode`. `exitCode` defaults to 0. * * All windows will be closed immediately without asking the user, and the * `before-quit` and `will-quit` events will not be emitted. */ exit(exitCode?: number): void; /** * On Linux, focuses on the first visible window. On macOS, makes the application * the active app. On Windows, focuses on the application's first window. * * You should seek to use the `steal` option as sparingly as possible. */ focus(options?: FocusOptions): void; /** * Resolve with an object containing the following: * * * `icon` NativeImage - the display icon of the app handling the protocol. * * `path` string - installation path of the app handling the protocol. * * `name` string - display name of the app handling the protocol. * * This method returns a promise that contains the application name, icon and path * of the default handler for the protocol (aka URI scheme) of a URL. * * @platform darwin,win32 */ getApplicationInfoForProtocol(url: string): Promise; /** * Name of the application handling the protocol, or an empty string if there is no * handler. For instance, if Electron is the default handler of the URL, this could * be `Electron` on Windows and Mac. However, don't rely on the precise format * which is not guaranteed to remain unchanged. Expect a different format on Linux, * possibly with a `.desktop` suffix. * * This method returns the application name of the default handler for the protocol * (aka URI scheme) of a URL. */ getApplicationNameForProtocol(url: string): string; /** * Array of `ProcessMetric` objects that correspond to memory and CPU usage * statistics of all the processes associated with the app. */ getAppMetrics(): ProcessMetric[]; /** * The current application directory. */ getAppPath(): string; /** * The current value displayed in the counter badge. * * @platform linux,darwin */ getBadgeCount(): number; /** * The type of the currently running activity. * * @platform darwin */ getCurrentActivityType(): string; /** * fulfilled with the app's icon, which is a NativeImage. * * Fetches a path's associated icon. * * On _Windows_, there a 2 kinds of icons: * * * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. * * On _Linux_ and _macOS_, icons depend on the application associated with file * mime type. */ getFileIcon(path: string, options?: FileIconOptions): Promise; /** * The Graphics Feature Status from `chrome://gpu/`. * * **Note:** This information is only usable after the `gpu-info-update` event is * emitted. */ getGPUFeatureStatus(): GPUFeatureStatus; /** * For `infoType` equal to `complete`: Promise is fulfilled with `Object` * containing all the GPU Information as in chromium's GPUInfo object. This * includes the version and driver information that's shown on `chrome://gpu` page. * * For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing * fewer attributes than when requested with `complete`. Here's an example of basic * response: * * Using `basic` should be preferred if only basic information like `vendorId` or * `deviceId` is needed. */ getGPUInfo(infoType: "basic" | "complete"): Promise; /** * * `minItems` Integer - The minimum number of items that will be shown in the * Jump List (for a more detailed description of this value see the MSDN docs). * * `removedItems` JumpListItem[] - Array of `JumpListItem` objects that * correspond to items that the user has explicitly removed from custom categories * in the Jump List. These items must not be re-added to the Jump List in the * **next** call to `app.setJumpList()`, Windows will not display any custom * category that contains any of the removed items. * * @platform win32 */ getJumpListSettings(): JumpListSettings; /** * The current application locale, fetched using Chromium's `l10n_util` library. * Possible return values are documented here. * * To set the locale, you'll want to use a command line switch at app startup, * which may be found here. * * **Note:** When distributing your packaged app, you have to also ship the * `locales` folder. * * **Note:** This API must be called after the `ready` event is emitted. * * **Note:** To see example return values of this API compared to other locale and * language APIs, see `app.getPreferredSystemLanguages()`. */ getLocale(): string; /** * User operating system's locale two-letter ISO 3166 country code. The value is * taken from native OS APIs. * * **Note:** When unable to detect locale country code, it returns empty string. */ getLocaleCountryCode(): string; /** * If you provided `path` and `args` options to `app.setLoginItemSettings`, then * you need to pass the same arguments here for `openAtLogin` to be set correctly. * * * * `openAtLogin` boolean - `true` if the app is set to open at login. * * `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at * login. This setting is not available on MAS builds. * * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login * automatically. This setting is not available on MAS builds. * * `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden * login item. This indicates that the app should not open any windows at startup. * This setting is not available on MAS builds. * * `restoreState` boolean _macOS_ - `true` if the app was opened as a login item * that should restore the state from the previous session. This indicates that the * app should restore the windows that were open the last time the app was closed. * This setting is not available on MAS builds. * * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open * at login and its run key is not deactivated. This differs from `openAtLogin` as * it ignores the `args` option, this property will be true if the given executable * would be launched at login with **any** arguments. * * `launchItems` Object[] _Windows_ * * `name` string _Windows_ - name value of a registry entry. * * `path` string _Windows_ - The executable to an app that corresponds to a * registry entry. * * `args` string[] _Windows_ - the command-line arguments to pass to the * executable. * * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the * registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * * `enabled` boolean _Windows_ - `true` if the app registry key is startup * approved and therefore shows as `enabled` in Task Manager and Windows settings. * * @platform darwin,win32 */ getLoginItemSettings(options?: LoginItemSettingsOptions): LoginItemSettings; /** * The current application's name, which is the name in the application's * `package.json` file. * * Usually the `name` field of `package.json` is a short lowercase name, according * to the npm modules spec. You should usually also specify a `productName` field, * which is your application's full capitalized name, and which will be preferred * over `name` by Electron. */ getName(): string; /** * A path to a special directory or file associated with `name`. On failure, an * `Error` is thrown. * * If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being * called first, a default log directory will be created equivalent to calling * `app.setAppLogsPath()` without a `path` parameter. */ getPath(name: "home" | "appData" | "userData" | "sessionData" | "temp" | "exe" | "module" | "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos" | "recent" | "logs" | "crashDumps"): string; /** * The user's preferred system languages from most preferred to least preferred, * including the country codes if applicable. A user can modify and add to this * list on Windows or macOS through the Language and Region settings. * * The API uses `GlobalizationPreferences` (with a fallback to * `GetSystemPreferredUILanguages`) on Windows, `\[NSLocale preferredLanguages\]` * on macOS, and `g_get_language_names` on Linux. * * This API can be used for purposes such as deciding what language to present the * application in. * * Here are some examples of return values of the various language and locale APIs * with different configurations: * * On Windows, given application locale is German, the regional format is Finnish * (Finland), and the preferred system languages from most to least preferred are * French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish * (Latin America): * * On macOS, given the application locale is German, the region is Finland, and the * preferred system languages from most to least preferred are French (Canada), * English (US), Simplified Chinese, and Spanish (Latin America): * * Both the available languages and regions and the possible return values differ * between the two operating systems. * * As can be seen with the example above, on Windows, it is possible that a * preferred system language has no country code, and that one of the preferred * system languages corresponds with the language used for the regional format. On * macOS, the region serves more as a default country code: the user doesn't need * to have Finnish as a preferred language to use Finland as the region,and the * country code `FI` is used as the country code for preferred system languages * that do not have associated countries in the language name. */ getPreferredSystemLanguages(): string[]; /** * The current system locale. On Windows and Linux, it is fetched using Chromium's * `i18n` library. On macOS, `[NSLocale currentLocale]` is used instead. To get the * user's current system language, which is not always the same as the locale, it * is better to use `app.getPreferredSystemLanguages()`. * * Different operating systems also use the regional data differently: * * * Windows 11 uses the regional format for numbers, dates, and times. * * macOS Monterey uses the region for formatting numbers, dates, times, and for * selecting the currency symbol to use. * * Therefore, this API can be used for purposes such as choosing a format for * rendering dates and times in a calendar app, especially when the developer wants * the format to be consistent with the OS. * * **Note:** This API must be called after the `ready` event is emitted. * * **Note:** To see example return values of this API compared to other locale and * language APIs, see `app.getPreferredSystemLanguages()`. */ getSystemLocale(): string; /** * The version of the loaded application. If no version is found in the * application's `package.json` file, the version of the current bundle or * executable is returned. */ getVersion(): string; /** * This method returns whether or not this instance of your app is currently * holding the single instance lock. You can request the lock with * `app.requestSingleInstanceLock()` and release with * `app.releaseSingleInstanceLock()` */ hasSingleInstanceLock(): boolean; /** * Hides all application windows without minimizing them. * * @platform darwin */ hide(): void; /** * Imports the certificate in pkcs12 format into the platform certificate store. * `callback` is called with the `result` of import operation, a value of `0` * indicates success while any other value indicates failure according to Chromium * net_error_list. * * @platform linux */ importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void; /** * Invalidates the current Handoff user activity. * * @platform darwin */ invalidateCurrentActivity(): void; /** * `true` if Chrome's accessibility support is enabled, `false` otherwise. This API * will return `true` if the use of assistive technologies, such as screen readers, * has been detected. See * https://www.chromium.org/developers/design-documents/accessibility for more * details. * * @platform darwin,win32 */ isAccessibilitySupportEnabled(): boolean; /** * Whether the current executable is the default handler for a protocol (aka URI * scheme). * * **Note:** On macOS, you can use this method to check if the app has been * registered as the default protocol handler for a protocol. You can also verify * this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the * macOS machine. Please refer to Apple's documentation for details. * * The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` * internally. */ isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * whether or not the current OS version allows for native emoji pickers. */ isEmojiPanelSupported(): boolean; /** * `true` if the application—including all of its windows—is hidden (e.g. with * `Command-H`), `false` otherwise. * * @platform darwin */ isHidden(): boolean; /** * Whether the application is currently running from the systems Application * folder. Use in combination with `app.moveToApplicationsFolder()` * * @platform darwin */ isInApplicationsFolder(): boolean; /** * `true` if Electron has finished initializing, `false` otherwise. See also * `app.whenReady()`. */ isReady(): boolean; /** * whether `Secure Keyboard Entry` is enabled. * * By default this API will return `false`. * * @platform darwin */ isSecureKeyboardEntryEnabled(): boolean; /** * Whether the current desktop environment is Unity launcher. * * @platform linux */ isUnityRunning(): boolean; /** * Whether the move was successful. Please note that if the move is successful, * your application will quit and relaunch. * * No confirmation dialog will be presented by default. If you wish to allow the * user to confirm the operation, you may do so using the `dialog` API. * * **NOTE:** This method throws errors if anything other than the user causes the * move to fail. For instance if the user cancels the authorization dialog, this * method returns false. If we fail to perform the copy, then this method will * throw an error. The message in the error should be informative and tell you * exactly what went wrong. * * By default, if an app of the same name as the one being moved exists in the * Applications directory and is _not_ running, the existing app will be trashed * and the active app moved into its place. If it _is_ running, the preexisting * running app will assume focus and the previously active app will quit itself. * This behavior can be changed by providing the optional conflict handler, where * the boolean returned by the handler determines whether or not the move conflict * is resolved with default behavior. i.e. returning `false` will ensure no * further action is taken, returning `true` will result in the default behavior * and the method continuing. * * For example: * * Would mean that if an app already exists in the user directory, if the user * chooses to 'Continue Move' then the function would continue with its default * behavior and the existing app will be trashed and the active app moved into its * place. * * @platform darwin */ moveToApplicationsFolder(options?: MoveToApplicationsFolderOptions): boolean; /** * Try to close all windows. The `before-quit` event will be emitted first. If all * windows are successfully closed, the `will-quit` event will be emitted and by * default the application will terminate. * * This method guarantees that all `beforeunload` and `unload` event handlers are * correctly executed. It is possible that a window cancels the quitting by * returning `false` in the `beforeunload` event handler. */ quit(): void; /** * Relaunches the app when current instance exits. * * By default, the new instance will use the same working directory and command * line arguments with current instance. When `args` is specified, the `args` will * be passed as command line arguments instead. When `execPath` is specified, the * `execPath` will be executed for relaunch instead of current app. * * Note that this method does not quit the app when executed, you have to call * `app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. * * When `app.relaunch` is called for multiple times, multiple instances will be * started after current instance exited. * * An example of restarting current instance immediately and adding a new command * line argument to the new instance: */ relaunch(options?: RelaunchOptions): void; /** * Releases all locks that were created by `requestSingleInstanceLock`. This will * allow multiple instances of the application to once again run side by side. */ releaseSingleInstanceLock(): void; /** * Whether the call succeeded. * * This method checks if the current executable as the default handler for a * protocol (aka URI scheme). If so, it will remove the app as the default handler. * * @platform darwin,win32 */ removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * The return value of this method indicates whether or not this instance of your * application successfully obtained the lock. If it failed to obtain the lock, * you can assume that another instance of your application is already running with * the lock and exit immediately. * * I.e. This method returns `true` if your process is the primary instance of your * application and your app should continue loading. It returns `false` if your * process should immediately quit as it has sent its parameters to another * instance that has already acquired the lock. * * On macOS, the system enforces single instance automatically when users try to * open a second instance of your app in Finder, and the `open-file` and `open-url` * events will be emitted for that. However when users start your app in command * line, the system's single instance mechanism will be bypassed, and you have to * use this method to ensure single instance. * * An example of activating the window of primary instance when a second instance * starts: */ requestSingleInstanceLock(additionalData?: Record): boolean; /** * Marks the current Handoff user activity as inactive without invalidating it. * * @platform darwin */ resignCurrentActivity(): void; /** * Set the about panel options. This will override the values defined in the app's * `.plist` file on macOS. See the Apple docs for more details. On Linux, values * must be set in order to be shown; there are no defaults. * * If you do not set `credits` but still wish to surface them in your app, AppKit * will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in * that order, in the bundle returned by the NSBundle class method main. The first * file found is used, and if none is found, the info area is left blank. See Apple * documentation for more information. */ setAboutPanelOptions(options: AboutPanelOptionsOptions): void; /** * Manually enables Chrome's accessibility support, allowing to expose * accessibility switch to users in application settings. See Chromium's * accessibility docs for more details. Disabled by default. * * This API must be called after the `ready` event is emitted. * * **Note:** Rendering accessibility tree can significantly affect the performance * of your app. It should not be enabled by default. * * @platform darwin,win32 */ setAccessibilitySupportEnabled(enabled: boolean): void; /** * Sets the activation policy for a given app. * * Activation policy types: * * * 'regular' - The application is an ordinary app that appears in the Dock and * may have a user interface. * * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a * menu bar, but it may be activated programmatically or by clicking on one of its * windows. * * 'prohibited' - The application doesn’t appear in the Dock and may not create * windows or be activated. * * @platform darwin */ setActivationPolicy(policy: "regular" | "accessory" | "prohibited"): void; /** * Sets or creates a directory your app's logs which can then be manipulated with * `app.getPath()` or `app.setPath(pathName, newPath)`. * * Calling `app.setAppLogsPath()` without a `path` parameter will result in this * directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the * `userData` directory on _Linux_ and _Windows_. */ setAppLogsPath(path?: string): void; /** * Changes the Application User Model ID to `id`. * * @platform win32 */ setAppUserModelId(id: string): void; /** * Whether the call succeeded. * * Sets the current executable as the default handler for a protocol (aka URI * scheme). It allows you to integrate your app deeper into the operating system. * Once registered, all links with `your-protocol://` will be opened with the * current executable. The whole link, including protocol, will be passed to your * application as a parameter. * * **Note:** On macOS, you can only register protocols that have been added to your * app's `info.plist`, which cannot be modified at runtime. However, you can change * the file during build time via Electron Forge, Electron Packager, or by editing * `info.plist` with a text editor. Please refer to Apple's documentation for * details. * * **Note:** In a Windows Store environment (when packaged as an `appx`) this API * will return `true` for all calls but the registry key it sets won't be * accessible by other applications. In order to register your Windows Store * application as a default protocol handler you must declare the protocol in your * manifest. * * The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` * internally. */ setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * Whether the call succeeded. * * Sets the counter badge for current app. Setting the count to `0` will hide the * badge. * * On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. * * **Note:** Unity launcher requires a `.desktop` file to work. For more * information, please read the Unity integration documentation. * * @platform linux,darwin */ setBadgeCount(count?: number): boolean; /** * Sets or removes a custom Jump List for the application, and returns one of the * following strings: * * * `ok` - Nothing went wrong. * * `error` - One or more errors occurred, enable runtime logging to figure out * the likely cause. * * `invalidSeparatorError` - An attempt was made to add a separator to a custom * category in the Jump List. Separators are only allowed in the standard `Tasks` * category. * * `fileTypeRegistrationError` - An attempt was made to add a file link to the * Jump List for a file type the app isn't registered to handle. * * `customCategoryAccessDeniedError` - Custom categories can't be added to the * Jump List due to user privacy or group policy settings. * * If `categories` is `null` the previously set custom Jump List (if any) will be * replaced by the standard Jump List for the app (managed by Windows). * * **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` * property set then its `type` is assumed to be `tasks`. If the `name` property is * set but the `type` property is omitted then the `type` is assumed to be * `custom`. * * **Note:** Users can remove items from custom categories, and Windows will not * allow a removed item to be added back into a custom category until **after** the * next successful call to `app.setJumpList(categories)`. Any attempt to re-add a * removed item to a custom category earlier than that will result in the entire * custom category being omitted from the Jump List. The list of removed items can * be obtained using `app.getJumpListSettings()`. * * **Note:** The maximum length of a Jump List item's `description` property is 260 * characters. Beyond this limit, the item will not be added to the Jump List, nor * will it be displayed. * * Here's a very simple example of creating a custom Jump List: * * @platform win32 */ setJumpList(categories: JumpListCategory[] | null): "ok" | "error" | "invalidSeparatorError" | "fileTypeRegistrationError" | "customCategoryAccessDeniedError"; /** * To work with Electron's `autoUpdater` on Windows, which uses Squirrel, you'll * want to set the launch path to Update.exe, and pass arguments that specify your * application name. For example: * * @platform darwin,win32 */ setLoginItemSettings(settings: Settings): void; /** * Overrides the current application's name. * * **Note:** This function overrides the name used internally by Electron; it does * not affect the name that the OS uses. */ setName(name: string): void; /** * Overrides the `path` to a special directory or file associated with `name`. If * the path specifies a directory that does not exist, an `Error` is thrown. In * that case, the directory should be created with `fs.mkdirSync` or similar. * * You can only override paths of a `name` defined in `app.getPath`. * * By default, web pages' cookies and caches will be stored under the `sessionData` * directory. If you want to change this location, you have to override the * `sessionData` path before the `ready` event of the `app` module is emitted. */ setPath(name: string, path: string): void; /** * Set the `Secure Keyboard Entry` is enabled in your application. * * By using this API, important information such as password and other sensitive * information can be prevented from being intercepted by other processes. * * See Apple's documentation for more details. * * **Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it * when it is no longer needed. * * @platform darwin */ setSecureKeyboardEntryEnabled(enabled: boolean): void; /** * Creates an `NSUserActivity` and sets it as the current activity. The activity is * eligible for Handoff to another device afterward. * * @platform darwin */ setUserActivity(type: string, userInfo: any, webpageURL?: string): void; /** * Adds `tasks` to the Tasks category of the Jump List on Windows. * * `tasks` is an array of `Task` objects. * * Whether the call succeeded. * * **Note:** If you'd like to customize the Jump List even more use * `app.setJumpList(categories)` instead. * * @platform win32 */ setUserTasks(tasks: Task[]): boolean; /** * Shows application windows after they were hidden. Does not automatically focus * them. * * @platform darwin */ show(): void; /** * Show the app's about panel options. These options can be overridden with * `app.setAboutPanelOptions(options)`. This function runs asynchronously. */ showAboutPanel(): void; /** * Show the platform's native emoji picker. * * @platform darwin,win32 */ showEmojiPanel(): void; /** * This function **must** be called once you have finished accessing the security * scoped file. If you do not remember to stop accessing the bookmark, kernel * resources will be leaked and your app will lose its ability to reach outside the * sandbox completely, until your app is restarted. * * Start accessing a security scoped resource. With this method Electron * applications that are packaged for the Mac App Store may reach outside their * sandbox to access files chosen by the user. See Apple's documentation for a * description of how this system works. * * @platform mas */ startAccessingSecurityScopedResource(bookmarkData: string): Function; /** * Updates the current activity if its type matches `type`, merging the entries * from `userInfo` into its current `userInfo` dictionary. * * @platform darwin */ updateCurrentActivity(type: string, userInfo: any): void; /** * fulfilled when Electron is initialized. May be used as a convenient alternative * to checking `app.isReady()` and subscribing to the `ready` event if the app is * not ready yet. */ whenReady(): Promise; /** * A `boolean` property that's `true` if Chrome's accessibility support is enabled, * `false` otherwise. This property will be `true` if the use of assistive * technologies, such as screen readers, has been detected. Setting this property * to `true` manually enables Chrome's accessibility support, allowing developers * to expose accessibility switch to users in application settings. * * See Chromium's accessibility docs for more details. Disabled by default. * * This API must be called after the `ready` event is emitted. * * **Note:** Rendering accessibility tree can significantly affect the performance * of your app. It should not be enabled by default. * * @platform darwin,win32 */ accessibilitySupportEnabled: boolean; /** * A `Menu | null` property that returns `Menu` if one has been set and `null` * otherwise. Users can pass a Menu to set this property. */ applicationMenu: Menu | null; /** * An `Integer` property that returns the badge count for current app. Setting the * count to `0` will hide the badge. * * On macOS, setting this with any nonzero integer shows on the dock icon. On * Linux, this property only works for Unity launcher. * * **Note:** Unity launcher requires a `.desktop` file to work. For more * information, please read the Unity integration documentation. * * **Note:** On macOS, you need to ensure that your application has the permission * to display notifications for this property to take effect. * * @platform linux,darwin */ badgeCount: number; /** * A `CommandLine` object that allows you to read and manipulate the command line * arguments that Chromium uses. * */ readonly commandLine: CommandLine; /** * A `Dock` `| undefined` object that allows you to perform actions on your app * icon in the user's dock on macOS. * * @platform darwin */ readonly dock: Dock; /** * A `boolean` property that returns `true` if the app is packaged, `false` * otherwise. For many apps, this property can be used to distinguish development * and production environments. * */ readonly isPackaged: boolean; /** * A `string` property that indicates the current application's name, which is the * name in the application's `package.json` file. * * Usually the `name` field of `package.json` is a short lowercase name, according * to the npm modules spec. You should usually also specify a `productName` field, * which is your application's full capitalized name, and which will be preferred * over `name` by Electron. */ name: string; /** * A `boolean` which when `true` indicates that the app is currently running under * an ARM64 translator (like the macOS Rosetta Translator Environment or Windows * WOW). * * You can use this property to prompt users to download the arm64 version of your * application when they are mistakenly running the x64 version under Rosetta or * WOW. * * @platform darwin,win32 */ readonly runningUnderARM64Translation: boolean; /** * A `boolean` which when `true` indicates that the app is currently running under * the Rosetta Translator Environment. * * You can use this property to prompt users to download the arm64 version of your * application when they are running the x64 version under Rosetta incorrectly. * * **Deprecated:** This property is superceded by the * `runningUnderARM64Translation` property which detects when the app is being * translated to ARM64 in both macOS and Windows. * * @deprecated * @platform darwin */ readonly runningUnderRosettaTranslation: boolean; /** * A `string` which is the user agent string Electron will use as a global * fallback. * * This is the user agent that will be used when no user agent is set at the * `webContents` or `session` level. It is useful for ensuring that your entire * app has the same user agent. Set to a custom value as early as possible in your * app's initialization to ensure that your overridden value is used. */ userAgentFallback: string; } interface AutoUpdater extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/auto-updater /** * This event is emitted after a user calls `quitAndInstall()`. * * When this API is called, the `before-quit` event is not emitted before all * windows are closed. As a result you should listen to this event if you wish to * perform actions before the windows are closed while a process is quitting, as * well as listening to `before-quit`. */ on(event: "before-quit-for-update", listener: Function): this; once(event: "before-quit-for-update", listener: Function): this; addListener(event: "before-quit-for-update", listener: Function): this; removeListener(event: "before-quit-for-update", listener: Function): this; /** * Emitted when checking if an update has started. */ on(event: "checking-for-update", listener: Function): this; once(event: "checking-for-update", listener: Function): this; addListener(event: "checking-for-update", listener: Function): this; removeListener(event: "checking-for-update", listener: Function): this; /** * Emitted when there is an error while updating. */ on(event: "error", listener: (error: Error) => void): this; once(event: "error", listener: (error: Error) => void): this; addListener(event: "error", listener: (error: Error) => void): this; removeListener(event: "error", listener: (error: Error) => void): this; /** * Emitted when there is an available update. The update is downloaded * automatically. */ on(event: "update-available", listener: Function): this; once(event: "update-available", listener: Function): this; addListener(event: "update-available", listener: Function): this; removeListener(event: "update-available", listener: Function): this; /** * Emitted when an update has been downloaded. * * On Windows only `releaseName` is available. * * **Note:** It is not strictly necessary to handle this event. A successfully * downloaded update will still be applied the next time the application starts. */ on(event: "update-downloaded", listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; once(event: "update-downloaded", listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; addListener(event: "update-downloaded", listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; removeListener(event: "update-downloaded", listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; /** * Emitted when there is no available update. */ on(event: "update-not-available", listener: Function): this; once(event: "update-not-available", listener: Function): this; addListener(event: "update-not-available", listener: Function): this; removeListener(event: "update-not-available", listener: Function): this; /** * Asks the server whether there is an update. You must call `setFeedURL` before * using this API. * * **Note:** If an update is available it will be downloaded automatically. Calling * `autoUpdater.checkForUpdates()` twice will download the update two times. */ checkForUpdates(): void; /** * The current update feed URL. */ getFeedURL(): string; /** * Restarts the app and installs the update after it has been downloaded. It should * only be called after `update-downloaded` has been emitted. * * Under the hood calling `autoUpdater.quitAndInstall()` will close all application * windows first, and automatically call `app.quit()` after all windows have been * closed. * * **Note:** It is not strictly necessary to call this function to apply an update, * as a successfully downloaded update will always be applied the next time the * application starts. */ quitAndInstall(): void; /** * Sets the `url` and initialize the auto updater. */ setFeedURL(options: FeedURLOptions): void; } interface BluetoothDevice { // Docs: https://electronjs.org/docs/api/structures/bluetooth-device deviceId: string; deviceName: string; } class BrowserView { // Docs: https://electronjs.org/docs/api/browser-view /** * BrowserView */ constructor(options?: BrowserViewConstructorOptions); /** * The `bounds` of this BrowserView instance as `Object`. * * @experimental */ getBounds(): Rectangle; /** * @experimental */ setAutoResize(options: AutoResizeOptions): void; /** * Examples of valid `color` values: * * * Hex * * #fff (RGB) * * #ffff (ARGB) * * #ffffff (RRGGBB) * * #ffffffff (AARRGGBB) * * RGB * * rgb(([\d]+),\s*([\d]+),\s*([\d]+)) * * e.g. rgb(255, 255, 255) * * RGBA * * rgba(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)) * * e.g. rgba(255, 255, 255, 1.0) * * HSL * * hsl((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%) * * e.g. hsl(200, 20%, 50%) * * HSLA * * hsla((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)) * * e.g. hsla(200, 20%, 50%, 0.5) * * Color name * * Options are listed in SkParseColor.cpp * * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * * e.g. `blueviolet` or `red` * * **Note:** Hex format with alpha takes `AARRGGBB` or `ARGB`, _not_ `RRGGBBA` or * `RGA`. * * @experimental */ setBackgroundColor(color: string): void; /** * Resizes and moves the view to the supplied bounds relative to the window. * * @experimental */ setBounds(bounds: Rectangle): void; /** * A `WebContents` object owned by this view. * * @experimental */ webContents: WebContents; } class BrowserWindow extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/browser-window /** * Emitted when the window is set or unset to show always on top of other windows. */ on(event: "always-on-top-changed", listener: (event: Event, isAlwaysOnTop: boolean) => void): this; once(event: "always-on-top-changed", listener: (event: Event, isAlwaysOnTop: boolean) => void): this; addListener(event: "always-on-top-changed", listener: (event: Event, isAlwaysOnTop: boolean) => void): this; removeListener(event: "always-on-top-changed", listener: (event: Event, isAlwaysOnTop: boolean) => void): this; /** * Emitted when an App Command is invoked. These are typically related to keyboard * media keys or browser commands, as well as the "Back" button built into some * mice on Windows. * * Commands are lowercased, underscores are replaced with hyphens, and the * `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is * emitted as `browser-backward`. * * The following app commands are explicitly supported on Linux: * * * `browser-backward` * * `browser-forward` * * @platform win32,linux */ on(event: "app-command", listener: (event: Event, command: string) => void): this; once(event: "app-command", listener: (event: Event, command: string) => void): this; addListener(event: "app-command", listener: (event: Event, command: string) => void): this; removeListener(event: "app-command", listener: (event: Event, command: string) => void): this; /** * Emitted when the window loses focus. */ on(event: "blur", listener: Function): this; once(event: "blur", listener: Function): this; addListener(event: "blur", listener: Function): this; removeListener(event: "blur", listener: Function): this; /** * Emitted when the window is going to be closed. It's emitted before the * `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` * will cancel the close. * * Usually you would want to use the `beforeunload` handler to decide whether the * window should be closed, which will also be called when the window is reloaded. * In Electron, returning any value other than `undefined` would cancel the close. * For example: * * _**Note**: There is a subtle difference between the behaviors of * `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', * handler)`. It is recommended to always set the `event.returnValue` explicitly, * instead of only returning a value, as the former works more consistently within * Electron._ */ on(event: "close", listener: (event: Event) => void): this; once(event: "close", listener: (event: Event) => void): this; addListener(event: "close", listener: (event: Event) => void): this; removeListener(event: "close", listener: (event: Event) => void): this; /** * Emitted when the window is closed. After you have received this event you should * remove the reference to the window and avoid using it any more. */ on(event: "closed", listener: Function): this; once(event: "closed", listener: Function): this; addListener(event: "closed", listener: Function): this; removeListener(event: "closed", listener: Function): this; /** * Emitted when the window enters a full-screen state. */ on(event: "enter-full-screen", listener: Function): this; once(event: "enter-full-screen", listener: Function): this; addListener(event: "enter-full-screen", listener: Function): this; removeListener(event: "enter-full-screen", listener: Function): this; /** * Emitted when the window enters a full-screen state triggered by HTML API. */ on(event: "enter-html-full-screen", listener: Function): this; once(event: "enter-html-full-screen", listener: Function): this; addListener(event: "enter-html-full-screen", listener: Function): this; removeListener(event: "enter-html-full-screen", listener: Function): this; /** * Emitted when the window gains focus. */ on(event: "focus", listener: Function): this; once(event: "focus", listener: Function): this; addListener(event: "focus", listener: Function): this; removeListener(event: "focus", listener: Function): this; /** * Emitted when the window is hidden. */ on(event: "hide", listener: Function): this; once(event: "hide", listener: Function): this; addListener(event: "hide", listener: Function): this; removeListener(event: "hide", listener: Function): this; /** * Emitted when the window leaves a full-screen state. */ on(event: "leave-full-screen", listener: Function): this; once(event: "leave-full-screen", listener: Function): this; addListener(event: "leave-full-screen", listener: Function): this; removeListener(event: "leave-full-screen", listener: Function): this; /** * Emitted when the window leaves a full-screen state triggered by HTML API. */ on(event: "leave-html-full-screen", listener: Function): this; once(event: "leave-html-full-screen", listener: Function): this; addListener(event: "leave-html-full-screen", listener: Function): this; removeListener(event: "leave-html-full-screen", listener: Function): this; /** * Emitted when window is maximized. */ on(event: "maximize", listener: Function): this; once(event: "maximize", listener: Function): this; addListener(event: "maximize", listener: Function): this; removeListener(event: "maximize", listener: Function): this; /** * Emitted when the window is minimized. */ on(event: "minimize", listener: Function): this; once(event: "minimize", listener: Function): this; addListener(event: "minimize", listener: Function): this; removeListener(event: "minimize", listener: Function): this; /** * Emitted when the window is being moved to a new position. */ on(event: "move", listener: Function): this; once(event: "move", listener: Function): this; addListener(event: "move", listener: Function): this; removeListener(event: "move", listener: Function): this; /** * Emitted once when the window is moved to a new position. * * **Note**: On macOS this event is an alias of `move`. * * @platform darwin,win32 */ on(event: "moved", listener: Function): this; once(event: "moved", listener: Function): this; addListener(event: "moved", listener: Function): this; removeListener(event: "moved", listener: Function): this; /** * Emitted when the native new tab button is clicked. * * @platform darwin */ on(event: "new-window-for-tab", listener: Function): this; once(event: "new-window-for-tab", listener: Function): this; addListener(event: "new-window-for-tab", listener: Function): this; removeListener(event: "new-window-for-tab", listener: Function): this; /** * Emitted when the document changed its title, calling `event.preventDefault()` * will prevent the native window's title from changing. `explicitSet` is false * when title is synthesized from file URL. */ on(event: "page-title-updated", listener: (event: Event, title: string, explicitSet: boolean) => void): this; once(event: "page-title-updated", listener: (event: Event, title: string, explicitSet: boolean) => void): this; addListener(event: "page-title-updated", listener: (event: Event, title: string, explicitSet: boolean) => void): this; removeListener(event: "page-title-updated", listener: (event: Event, title: string, explicitSet: boolean) => void): this; /** * Emitted when the web page has been rendered (while not being shown) and window * can be displayed without a visual flash. * * Please note that using this event implies that the renderer will be considered * "visible" and paint even though `show` is false. This event will never fire if * you use `paintWhenInitiallyHidden: false` */ on(event: "ready-to-show", listener: Function): this; once(event: "ready-to-show", listener: Function): this; addListener(event: "ready-to-show", listener: Function): this; removeListener(event: "ready-to-show", listener: Function): this; /** * Emitted after the window has been resized. */ on(event: "resize", listener: Function): this; once(event: "resize", listener: Function): this; addListener(event: "resize", listener: Function): this; removeListener(event: "resize", listener: Function): this; /** * Emitted once when the window has finished being resized. * * This is usually emitted when the window has been resized manually. On macOS, * resizing the window with `setBounds`/`setSize` and setting the `animate` * parameter to `true` will also emit this event once resizing has finished. * * @platform darwin,win32 */ on(event: "resized", listener: Function): this; once(event: "resized", listener: Function): this; addListener(event: "resized", listener: Function): this; removeListener(event: "resized", listener: Function): this; /** * Emitted when the unresponsive web page becomes responsive again. */ on(event: "responsive", listener: Function): this; once(event: "responsive", listener: Function): this; addListener(event: "responsive", listener: Function): this; removeListener(event: "responsive", listener: Function): this; /** * Emitted when the window is restored from a minimized state. */ on(event: "restore", listener: Function): this; once(event: "restore", listener: Function): this; addListener(event: "restore", listener: Function): this; removeListener(event: "restore", listener: Function): this; /** * Emitted on trackpad rotation gesture. Continually emitted until rotation gesture * is ended. The `rotation` value on each emission is the angle in degrees rotated * since the last emission. The last emitted event upon a rotation gesture will * always be of value `0`. Counter-clockwise rotation values are positive, while * clockwise ones are negative. * * @platform darwin */ on(event: "rotate-gesture", listener: (event: Event, rotation: number) => void): this; once(event: "rotate-gesture", listener: (event: Event, rotation: number) => void): this; addListener(event: "rotate-gesture", listener: (event: Event, rotation: number) => void): this; removeListener(event: "rotate-gesture", listener: (event: Event, rotation: number) => void): this; /** * Emitted when scroll wheel event phase has begun. * * > **Note** This event is deprecated beginning in Electron 22.0.0. See Breaking * Changes for details of how to migrate to using the WebContents `input-event` * event. * * @deprecated * @platform darwin */ on(event: "scroll-touch-begin", listener: Function): this; once(event: "scroll-touch-begin", listener: Function): this; addListener(event: "scroll-touch-begin", listener: Function): this; removeListener(event: "scroll-touch-begin", listener: Function): this; /** * Emitted when scroll wheel event phase filed upon reaching the edge of element. * * > **Note** This event is deprecated beginning in Electron 22.0.0. See Breaking * Changes for details of how to migrate to using the WebContents `input-event` * event. * * @deprecated * @platform darwin */ on(event: "scroll-touch-edge", listener: Function): this; once(event: "scroll-touch-edge", listener: Function): this; addListener(event: "scroll-touch-edge", listener: Function): this; removeListener(event: "scroll-touch-edge", listener: Function): this; /** * Emitted when scroll wheel event phase has ended. * * > **Note** This event is deprecated beginning in Electron 22.0.0. See Breaking * Changes for details of how to migrate to using the WebContents `input-event` * event. * * @deprecated * @platform darwin */ on(event: "scroll-touch-end", listener: Function): this; once(event: "scroll-touch-end", listener: Function): this; addListener(event: "scroll-touch-end", listener: Function): this; removeListener(event: "scroll-touch-end", listener: Function): this; /** * Emitted when window session is going to end due to force shutdown or machine * restart or session log off. * * @platform win32 */ on(event: "session-end", listener: Function): this; once(event: "session-end", listener: Function): this; addListener(event: "session-end", listener: Function): this; removeListener(event: "session-end", listener: Function): this; /** * Emitted when the window opens a sheet. * * @platform darwin */ on(event: "sheet-begin", listener: Function): this; once(event: "sheet-begin", listener: Function): this; addListener(event: "sheet-begin", listener: Function): this; removeListener(event: "sheet-begin", listener: Function): this; /** * Emitted when the window has closed a sheet. * * @platform darwin */ on(event: "sheet-end", listener: Function): this; once(event: "sheet-end", listener: Function): this; addListener(event: "sheet-end", listener: Function): this; removeListener(event: "sheet-end", listener: Function): this; /** * Emitted when the window is shown. */ on(event: "show", listener: Function): this; once(event: "show", listener: Function): this; addListener(event: "show", listener: Function): this; removeListener(event: "show", listener: Function): this; /** * Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, * `left`. * * The method underlying this event is built to handle older macOS-style trackpad * swiping, where the content on the screen doesn't move with the swipe. Most macOS * trackpads are not configured to allow this kind of swiping anymore, so in order * for it to emit properly the 'Swipe between pages' preference in `System * Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three * fingers'. * * @platform darwin */ on(event: "swipe", listener: (event: Event, direction: string) => void): this; once(event: "swipe", listener: (event: Event, direction: string) => void): this; addListener(event: "swipe", listener: (event: Event, direction: string) => void): this; removeListener(event: "swipe", listener: (event: Event, direction: string) => void): this; /** * Emitted when the system context menu is triggered on the window, this is * normally only triggered when the user right clicks on the non-client area of * your window. This is the window titlebar or any area you have declared as * `-webkit-app-region: drag` in a frameless window. * * Calling `event.preventDefault()` will prevent the menu from being displayed. * * @platform win32 */ on( event: "system-context-menu", listener: ( event: Event, /** * The screen coordinates the context menu was triggered at */ point: Point, ) => void, ): this; once( event: "system-context-menu", listener: ( event: Event, /** * The screen coordinates the context menu was triggered at */ point: Point, ) => void, ): this; addListener( event: "system-context-menu", listener: ( event: Event, /** * The screen coordinates the context menu was triggered at */ point: Point, ) => void, ): this; removeListener( event: "system-context-menu", listener: ( event: Event, /** * The screen coordinates the context menu was triggered at */ point: Point, ) => void, ): this; /** * Emitted when the window exits from a maximized state. */ on(event: "unmaximize", listener: Function): this; once(event: "unmaximize", listener: Function): this; addListener(event: "unmaximize", listener: Function): this; removeListener(event: "unmaximize", listener: Function): this; /** * Emitted when the web page becomes unresponsive. */ on(event: "unresponsive", listener: Function): this; once(event: "unresponsive", listener: Function): this; addListener(event: "unresponsive", listener: Function): this; removeListener(event: "unresponsive", listener: Function): this; /** * Emitted before the window is moved. On Windows, calling `event.preventDefault()` * will prevent the window from being moved. * * Note that this is only emitted when the window is being moved manually. Moving * the window with `setPosition`/`setBounds`/`center` will not emit this event. * * @platform darwin,win32 */ on( event: "will-move", listener: ( event: Event, /** * Location the window is being moved to. */ newBounds: Rectangle, ) => void, ): this; once( event: "will-move", listener: ( event: Event, /** * Location the window is being moved to. */ newBounds: Rectangle, ) => void, ): this; addListener( event: "will-move", listener: ( event: Event, /** * Location the window is being moved to. */ newBounds: Rectangle, ) => void, ): this; removeListener( event: "will-move", listener: ( event: Event, /** * Location the window is being moved to. */ newBounds: Rectangle, ) => void, ): this; /** * Emitted before the window is resized. Calling `event.preventDefault()` will * prevent the window from being resized. * * Note that this is only emitted when the window is being resized manually. * Resizing the window with `setBounds`/`setSize` will not emit this event. * * The possible values and behaviors of the `edge` option are platform dependent. * Possible values are: * * * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, * `top-right`, `bottom-left`, `bottom-right`. * * On macOS, possible values are `bottom` and `right`. * * The value `bottom` is used to denote vertical resizing. * * The value `right` is used to denote horizontal resizing. * * @platform darwin,win32 */ on( event: "will-resize", listener: ( event: Event, /** * Size the window is being resized to. */ newBounds: Rectangle, details: WillResizeDetails, ) => void, ): this; once( event: "will-resize", listener: ( event: Event, /** * Size the window is being resized to. */ newBounds: Rectangle, details: WillResizeDetails, ) => void, ): this; addListener( event: "will-resize", listener: ( event: Event, /** * Size the window is being resized to. */ newBounds: Rectangle, details: WillResizeDetails, ) => void, ): this; removeListener( event: "will-resize", listener: ( event: Event, /** * Size the window is being resized to. */ newBounds: Rectangle, details: WillResizeDetails, ) => void, ): this; /** * BrowserWindow */ constructor(options?: BrowserWindowConstructorOptions); /** * The window that owns the given `browserView`. If the given view is not attached * to any window, returns `null`. */ static fromBrowserView(browserView: BrowserView): BrowserWindow | null; /** * The window with the given `id`. */ static fromId(id: number): BrowserWindow | null; /** * The window that owns the given `webContents` or `null` if the contents are not * owned by a window. */ static fromWebContents(webContents: WebContents): BrowserWindow | null; /** * An array of all opened browser windows. */ static getAllWindows(): BrowserWindow[]; /** * The window that is focused in this application, otherwise returns `null`. */ static getFocusedWindow(): BrowserWindow | null; /** * Replacement API for setBrowserView supporting work with multi browser views. * * @experimental */ addBrowserView(browserView: BrowserView): void; /** * Adds a window as a tab on this window, after the tab for the window instance. * * @platform darwin */ addTabbedWindow(browserWindow: BrowserWindow): void; /** * Removes focus from the window. */ blur(): void; blurWebView(): void; /** * Resolves with a NativeImage * * Captures a snapshot of the page within `rect`. Omitting `rect` will capture the * whole visible page. If the page is not visible, `rect` may be empty. The page is * considered visible when its browser window is hidden and the capturer count is * non-zero. If you would like the page to stay hidden, you should ensure that * `stayHidden` is set to true. */ capturePage(rect?: Rectangle, opts?: Opts): Promise; /** * Moves window to the center of the screen. */ center(): void; /** * Try to close the window. This has the same effect as a user manually clicking * the close button of the window. The web page may cancel the close though. See * the close event. */ close(): void; /** * Closes the currently open Quick Look panel. * * @platform darwin */ closeFilePreview(): void; /** * Force closing the window, the `unload` and `beforeunload` event won't be emitted * for the web page, and `close` event will also not be emitted for this window, * but it guarantees the `closed` event will be emitted. */ destroy(): void; /** * Starts or stops flashing the window to attract user's attention. */ flashFrame(flag: boolean): void; /** * Focuses on the window. */ focus(): void; focusOnWebView(): void; /** * Gets the background color of the window in Hex (`#RRGGBB`) format. * * See Setting `backgroundColor`. * * **Note:** The alpha value is _not_ returned alongside the red, green, and blue * values. */ getBackgroundColor(): string; /** * The `bounds` of the window as `Object`. */ getBounds(): Rectangle; /** * The `BrowserView` attached to `win`. Returns `null` if one is not attached. * Throws an error if multiple `BrowserView`s are attached. * * @experimental */ getBrowserView(): BrowserView | null; /** * an array of all BrowserViews that have been attached with `addBrowserView` or * `setBrowserView`. * * **Note:** The BrowserView API is currently experimental and may change or be * removed in future Electron releases. * * @experimental */ getBrowserViews(): BrowserView[]; /** * All child windows. */ getChildWindows(): BrowserWindow[]; /** * The `bounds` of the window's client area as `Object`. */ getContentBounds(): Rectangle; /** * Contains the window's client area's width and height. */ getContentSize(): number[]; /** * Contains the window's maximum width and height. */ getMaximumSize(): number[]; /** * Window id in the format of DesktopCapturerSource's id. For example * "window:1324:0". * * More precisely the format is `window:id:other_id` where `id` is `HWND` on * Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on * Linux. `other_id` is used to identify web contents (tabs) so within the same top * level window. */ getMediaSourceId(): string; /** * Contains the window's minimum width and height. */ getMinimumSize(): number[]; /** * The platform-specific handle of the window. * * The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and * `Window` (`unsigned long`) on Linux. */ getNativeWindowHandle(): Buffer; /** * Contains the window bounds of the normal state * * **Note:** whatever the current state of the window : maximized, minimized or in * fullscreen, this function always returns the position and size of the window in * normal state. In normal state, getBounds and getNormalBounds returns the same * `Rectangle`. */ getNormalBounds(): Rectangle; /** * between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns * 1. */ getOpacity(): number; /** * The parent window or `null` if there is no parent. */ getParentWindow(): BrowserWindow | null; /** * Contains the window's current position. */ getPosition(): number[]; /** * The pathname of the file the window represents. * * @platform darwin */ getRepresentedFilename(): string; /** * Contains the window's width and height. */ getSize(): number[]; /** * The title of the native window. * * **Note:** The title of the web page can be different from the title of the * native window. */ getTitle(): string; /** * The custom position for the traffic light buttons in frameless window, `{ x: 0, * y: 0 }` will be returned when there is no custom position. * * > **Note** This function is deprecated. Use getWindowButtonPosition instead. * * @deprecated * @platform darwin */ getTrafficLightPosition(): Point; /** * The custom position for the traffic light buttons in frameless window, `null` * will be returned when there is no custom position. * * @platform darwin */ getWindowButtonPosition(): Point | null; /** * Whether the window has a shadow. */ hasShadow(): boolean; /** * Hides the window. */ hide(): void; /** * Hooks a windows message. The `callback` is called when the message is received * in the WndProc. * * @platform win32 */ hookWindowMessage(message: number, callback: (wParam: Buffer, lParam: Buffer) => void): void; /** * Invalidates the window shadow so that it is recomputed based on the current * window shape. * * `BrowserWindows` that are transparent can sometimes leave behind visual * artifacts on macOS. This method can be used to clear these artifacts when, for * example, performing an animation. * * @platform darwin */ invalidateShadow(): void; /** * Whether the window is always on top of other windows. */ isAlwaysOnTop(): boolean; /** * Whether the window can be manually closed by user. * * On Linux always returns `true`. * * @platform darwin,win32 */ isClosable(): boolean; /** * Whether the window is destroyed. */ isDestroyed(): boolean; /** * Whether the window's document has been edited. * * @platform darwin */ isDocumentEdited(): boolean; /** * whether the window is enabled. */ isEnabled(): boolean; /** * Whether the window can be focused. * * @platform darwin,win32 */ isFocusable(): boolean; /** * Whether the window is focused. */ isFocused(): boolean; /** * Whether the window is in fullscreen mode. */ isFullScreen(): boolean; /** * Whether the maximize/zoom window button toggles fullscreen mode or maximizes the * window. */ isFullScreenable(): boolean; /** * Whether the window will be hidden when the user toggles into mission control. * * @platform darwin */ isHiddenInMissionControl(): boolean; /** * Whether the window is in kiosk mode. */ isKiosk(): boolean; /** * Whether the window can be manually maximized by user. * * On Linux always returns `true`. * * @platform darwin,win32 */ isMaximizable(): boolean; /** * Whether the window is maximized. */ isMaximized(): boolean; /** * Whether menu bar automatically hides itself. * * @platform win32,linux */ isMenuBarAutoHide(): boolean; /** * Whether the menu bar is visible. * * @platform win32,linux */ isMenuBarVisible(): boolean; /** * Whether the window can be manually minimized by the user. * * On Linux always returns `true`. * * @platform darwin,win32 */ isMinimizable(): boolean; /** * Whether the window is minimized. */ isMinimized(): boolean; /** * Whether current window is a modal window. */ isModal(): boolean; /** * Whether the window can be moved by user. * * On Linux always returns `true`. * * @platform darwin,win32 */ isMovable(): boolean; /** * Whether the window is in normal state (not maximized, not minimized, not in * fullscreen mode). */ isNormal(): boolean; /** * Whether the window can be manually resized by the user. */ isResizable(): boolean; /** * Whether the window is in simple (pre-Lion) fullscreen mode. * * @platform darwin */ isSimpleFullScreen(): boolean; /** * Whether the window is in Windows 10 tablet mode. * * Since Windows 10 users can use their PC as tablet, under this mode apps can * choose to optimize their UI for tablets, such as enlarging the titlebar and * hiding titlebar buttons. * * This API returns whether the window is in tablet mode, and the `resize` event * can be be used to listen to changes to tablet mode. * * @platform win32 */ isTabletMode(): boolean; /** * Whether the window is visible to the user in the foreground of the app. */ isVisible(): boolean; /** * Whether the window is visible on all workspaces. * * **Note:** This API always returns false on Windows. * * @platform darwin,linux */ isVisibleOnAllWorkspaces(): boolean; /** * `true` or `false` depending on whether the message is hooked. * * @platform win32 */ isWindowMessageHooked(message: number): boolean; /** * the promise will resolve when the page has finished loading (see * `did-finish-load`), and rejects if the page fails to load (see `did-fail-load`). * * Same as `webContents.loadFile`, `filePath` should be a path to an HTML file * relative to the root of your application. See the `webContents` docs for more * information. */ loadFile(filePath: string, options?: LoadFileOptions): Promise; /** * the promise will resolve when the page has finished loading (see * `did-finish-load`), and rejects if the page fails to load (see `did-fail-load`). * * Same as `webContents.loadURL(url[, options])`. * * The `url` can be a remote address (e.g. `http://`) or a path to a local HTML * file using the `file://` protocol. * * To ensure that file URLs are properly formatted, it is recommended to use Node's * `url.format` method: * * You can load a URL using a `POST` request with URL-encoded data by doing the * following: */ loadURL(url: string, options?: LoadURLOptions): Promise; /** * Maximizes the window. This will also show (but not focus) the window if it isn't * being displayed already. */ maximize(): void; /** * Merges all windows into one window with multiple tabs when native tabs are * enabled and there is more than one open window. * * @platform darwin */ mergeAllWindows(): void; /** * Minimizes the window. On some platforms the minimized window will be shown in * the Dock. */ minimize(): void; /** * Moves window above the source window in the sense of z-order. If the * `mediaSourceId` is not of type window or if the window does not exist then this * method throws an error. */ moveAbove(mediaSourceId: string): void; /** * Moves the current tab into a new window if native tabs are enabled and there is * more than one tab in the current window. * * @platform darwin */ moveTabToNewWindow(): void; /** * Moves window to top(z-order) regardless of focus */ moveTop(): void; /** * Uses Quick Look to preview a file at a given path. * * @platform darwin */ previewFile(path: string, displayName?: string): void; /** * Same as `webContents.reload`. */ reload(): void; /** * @experimental */ removeBrowserView(browserView: BrowserView): void; /** * Remove the window's menu bar. * * @platform linux,win32 */ removeMenu(): void; /** * Restores the window from minimized state to its previous state. */ restore(): void; /** * Selects the next tab when native tabs are enabled and there are other tabs in * the window. * * @platform darwin */ selectNextTab(): void; /** * Selects the previous tab when native tabs are enabled and there are other tabs * in the window. * * @platform darwin */ selectPreviousTab(): void; /** * Sets whether the window should show always on top of other windows. After * setting this, the window is still a normal window, not a toolbox window which * can not be focused on. */ setAlwaysOnTop(flag: boolean, level?: "normal" | "floating" | "torn-off-menu" | "modal-panel" | "main-menu" | "status" | "pop-up-menu" | "screen-saver", relativeLevel?: number): void; /** * Sets the properties for the window's taskbar button. * * **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set * together. If one of those properties is not set, then neither will be used. * * @platform win32 */ setAppDetails(options: AppDetailsOptions): void; /** * This will make a window maintain an aspect ratio. The extra size allows a * developer to have space, specified in pixels, not included within the aspect * ratio calculations. This API already takes into account the difference between a * window's size and its content size. * * Consider a normal window with an HD video player and associated controls. * Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls * on the right edge and 50 pixels of controls below the player. In order to * maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within * the player itself we would call this function with arguments of 16/9 and { * width: 40, height: 50 }. The second argument doesn't care where the extra width * and height are within the content view--only that they exist. Sum any extra * width and height areas you have within the overall content view. * * The aspect ratio is not respected when window is resized programmatically with * APIs like `win.setSize`. * * To reset an aspect ratio, pass 0 as the `aspectRatio` value: * `win.setAspectRatio(0)`. */ setAspectRatio(aspectRatio: number, extraSize?: Size): void; /** * Controls whether to hide cursor when typing. * * @platform darwin */ setAutoHideCursor(autoHide: boolean): void; /** * Sets whether the window menu bar should hide itself automatically. Once set the * menu bar will only show when users press the single `Alt` key. * * If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't * hide it immediately. * * @platform win32,linux */ setAutoHideMenuBar(hide: boolean): void; /** * Examples of valid `backgroundColor` values: * * * Hex * * #fff (shorthand RGB) * * #ffff (shorthand ARGB) * * #ffffff (RGB) * * #ffffffff (ARGB) * * RGB * * rgb(([\d]+),\s*([\d]+),\s*([\d]+)) * * e.g. rgb(255, 255, 255) * * RGBA * * rgba(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)) * * e.g. rgba(255, 255, 255, 1.0) * * HSL * * hsl((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%) * * e.g. hsl(200, 20%, 50%) * * HSLA * * hsla((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)) * * e.g. hsla(200, 20%, 50%, 0.5) * * Color name * * Options are listed in SkParseColor.cpp * * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * * e.g. `blueviolet` or `red` * * Sets the background color of the window. See Setting `backgroundColor`. */ setBackgroundColor(backgroundColor: string): void; /** * This method sets the browser window's system-drawn background material, * including behind the non-client area. * * See the Windows documentation for more details. * * **Note:** This method is only supported on Windows 11 22H2 and up. * * @platform win32 */ setBackgroundMaterial(material: "auto" | "none" | "mica" | "acrylic" | "tabbed"): void; /** * Resizes and moves the window to the supplied bounds. Any properties that are not * supplied will default to their current values. */ setBounds(bounds: Partial, animate?: boolean): void; /** * @experimental */ setBrowserView(browserView: BrowserView | null): void; /** * Sets whether the window can be manually closed by user. On Linux does nothing. * * @platform darwin,win32 */ setClosable(closable: boolean): void; /** * Resizes and moves the window's client area (e.g. the web page) to the supplied * bounds. */ setContentBounds(bounds: Rectangle, animate?: boolean): void; /** * Prevents the window contents from being captured by other apps. * * On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows * it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 * version 2004 and up the window will be removed from capture entirely, older * Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. * * @platform darwin,win32 */ setContentProtection(enable: boolean): void; /** * Resizes the window's client area (e.g. the web page) to `width` and `height`. */ setContentSize(width: number, height: number, animate?: boolean): void; /** * Specifies whether the window’s document has been edited, and the icon in title * bar will become gray when set to `true`. * * @platform darwin */ setDocumentEdited(edited: boolean): void; /** * Disable or enable the window. */ setEnabled(enable: boolean): void; /** * Changes whether the window can be focused. * * On macOS it does not remove the focus from the window. * * @platform darwin,win32 */ setFocusable(focusable: boolean): void; /** * Sets whether the window should be in fullscreen mode. * * **Note:** On macOS, fullscreen transitions take place asynchronously. If further * actions depend on the fullscreen state, use the 'enter-full-screen' or * 'leave-full-screen' events. */ setFullScreen(flag: boolean): void; /** * Sets whether the maximize/zoom window button toggles fullscreen mode or * maximizes the window. */ setFullScreenable(fullscreenable: boolean): void; /** * Sets whether the window should have a shadow. */ setHasShadow(hasShadow: boolean): void; /** * Sets whether the window will be hidden when the user toggles into mission * control. * * @platform darwin */ setHiddenInMissionControl(hidden: boolean): void; /** * Changes window icon. * * @platform win32,linux */ setIcon(icon: NativeImage | string): void; /** * Makes the window ignore all mouse events. * * All mouse events happened in this window will be passed to the window below this * window, but if this window has focus, it will still receive keyboard events. */ setIgnoreMouseEvents(ignore: boolean, options?: IgnoreMouseEventsOptions): void; /** * Enters or leaves kiosk mode. */ setKiosk(flag: boolean): void; /** * Sets whether the window can be manually maximized by user. On Linux does * nothing. * * @platform darwin,win32 */ setMaximizable(maximizable: boolean): void; /** * Sets the maximum size of window to `width` and `height`. */ setMaximumSize(width: number, height: number): void; /** * Sets the `menu` as the window's menu bar. * * @platform linux,win32 */ setMenu(menu: Menu | null): void; /** * Sets whether the menu bar should be visible. If the menu bar is auto-hide, users * can still bring up the menu bar by pressing the single `Alt` key. * * @platform win32,linux */ setMenuBarVisibility(visible: boolean): void; /** * Sets whether the window can be manually minimized by user. On Linux does * nothing. * * @platform darwin,win32 */ setMinimizable(minimizable: boolean): void; /** * Sets the minimum size of window to `width` and `height`. */ setMinimumSize(width: number, height: number): void; /** * Sets whether the window can be moved by user. On Linux does nothing. * * @platform darwin,win32 */ setMovable(movable: boolean): void; /** * Sets the opacity of the window. On Linux, does nothing. Out of bound number * values are clamped to the [0, 1] range. * * @platform win32,darwin */ setOpacity(opacity: number): void; /** * Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to * convey some sort of application status or to passively notify the user. * * @platform win32 */ setOverlayIcon(overlay: NativeImage | null, description: string): void; /** * Sets `parent` as current window's parent window, passing `null` will turn * current window into a top-level window. */ setParentWindow(parent: BrowserWindow | null): void; /** * Moves window to `x` and `y`. */ setPosition(x: number, y: number, animate?: boolean): void; /** * Sets progress value in progress bar. Valid range is [0, 1.0]. * * Remove progress bar when progress < 0; Change to indeterminate mode when * progress > 1. * * On Linux platform, only supports Unity desktop environment, you need to specify * the `*.desktop` file name to `desktopName` field in `package.json`. By default, * it will assume `{app.name}.desktop`. * * On Windows, a mode can be passed. Accepted values are `none`, `normal`, * `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a * mode set (but with a value within the valid range), `normal` will be assumed. */ setProgressBar(progress: number, options?: ProgressBarOptions): void; /** * Sets the pathname of the file the window represents, and the icon of the file * will show in window's title bar. * * @platform darwin */ setRepresentedFilename(filename: string): void; /** * Sets whether the window can be manually resized by the user. */ setResizable(resizable: boolean): void; /** * Setting a window shape determines the area within the window where the system * permits drawing and user interaction. Outside of the given region, no pixels * will be drawn and no mouse events will be registered. Mouse events outside of * the region will not be received by that window, but will fall through to * whatever is behind the window. * * @experimental * @platform win32,linux */ setShape(rects: Rectangle[]): void; /** * Changes the attachment point for sheets on macOS. By default, sheets are * attached just below the window frame, but you may want to display them beneath a * HTML-rendered toolbar. For example: * * @platform darwin */ setSheetOffset(offsetY: number, offsetX?: number): void; /** * Enters or leaves simple fullscreen mode. * * Simple fullscreen mode emulates the native fullscreen behavior found in versions * of macOS prior to Lion (10.7). * * @platform darwin */ setSimpleFullScreen(flag: boolean): void; /** * Resizes the window to `width` and `height`. If `width` or `height` are below any * set minimum size constraints the window will snap to its minimum size. */ setSize(width: number, height: number, animate?: boolean): void; /** * Makes the window not show in the taskbar. * * @platform darwin,win32 */ setSkipTaskbar(skip: boolean): void; /** * Whether the buttons were added successfully * * Add a thumbnail toolbar with a specified set of buttons to the thumbnail image * of a window in a taskbar button layout. Returns a `boolean` object indicates * whether the thumbnail has been added successfully. * * The number of buttons in thumbnail toolbar should be no greater than 7 due to * the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be * removed due to the platform's limitation. But you can call the API with an empty * array to clean the buttons. * * The `buttons` is an array of `Button` objects: * * * `Button` Object * * `icon` NativeImage - The icon showing in thumbnail toolbar. * * `click` Function * * `tooltip` string (optional) - The text of the button's tooltip. * * `flags` string[] (optional) - Control specific states and behaviors of the * button. By default, it is `['enabled']`. * * The `flags` is an array that can include following `string`s: * * * `enabled` - The button is active and available to the user. * * `disabled` - The button is disabled. It is present, but has a visual state * indicating it will not respond to user action. * * `dismissonclick` - When the button is clicked, the thumbnail window closes * immediately. * * `nobackground` - Do not draw a button border, use only the image. * * `hidden` - The button is not shown to the user. * * `noninteractive` - The button is enabled but not interactive; no pressed * button state is drawn. This value is intended for instances where the button is * used in a notification. * * @platform win32 */ setThumbarButtons(buttons: ThumbarButton[]): boolean; /** * Sets the region of the window to show as the thumbnail image displayed when * hovering over the window in the taskbar. You can reset the thumbnail to be the * entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 * }`. * * @platform win32 */ setThumbnailClip(region: Rectangle): void; /** * Sets the toolTip that is displayed when hovering over the window thumbnail in * the taskbar. * * @platform win32 */ setThumbnailToolTip(toolTip: string): void; /** * Changes the title of native window to `title`. */ setTitle(title: string): void; /** * On a Window with Window Controls Overlay already enabled, this method updates * the style of the title bar overlay. * * @platform win32 */ setTitleBarOverlay(options: TitleBarOverlayOptions): void; /** * Raises `browserView` above other `BrowserView`s attached to `win`. Throws an * error if `browserView` is not attached to `win`. * * @experimental */ setTopBrowserView(browserView: BrowserView): void; /** * Sets the touchBar layout for the current window. Specifying `null` or * `undefined` clears the touch bar. This method only has an effect if the machine * has a touch bar. * * **Note:** The TouchBar API is currently experimental and may change or be * removed in future Electron releases. * * @platform darwin */ setTouchBar(touchBar: TouchBar | null): void; /** * Set a custom position for the traffic light buttons in frameless window. Passing * `{ x: 0, y: 0 }` will reset the position to default. * * > **Note** This function is deprecated. Use setWindowButtonPosition instead. * * @deprecated * @platform darwin */ setTrafficLightPosition(position: Point): void; /** * Adds a vibrancy effect to the browser window. Passing `null` or an empty string * will remove the vibrancy effect on the window. * * Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` * have been deprecated and will be removed in an upcoming version of macOS. * * @platform darwin */ setVibrancy(type: ("appearance-based" | "light" | "dark" | "titlebar" | "selection" | "menu" | "popover" | "sidebar" | "medium-light" | "ultra-dark" | "header" | "sheet" | "window" | "hud" | "fullscreen-ui" | "tooltip" | "content" | "under-window" | "under-page") | null): void; /** * Sets whether the window should be visible on all workspaces. * * **Note:** This API does nothing on Windows. * * @platform darwin,linux */ setVisibleOnAllWorkspaces(visible: boolean, options?: VisibleOnAllWorkspacesOptions): void; /** * Set a custom position for the traffic light buttons in frameless window. Passing * `null` will reset the position to default. * * @platform darwin */ setWindowButtonPosition(position: Point | null): void; /** * Sets whether the window traffic light buttons should be visible. * * @platform darwin */ setWindowButtonVisibility(visible: boolean): void; /** * Shows and gives focus to the window. */ show(): void; /** * Same as `webContents.showDefinitionForSelection()`. * * @platform darwin */ showDefinitionForSelection(): void; /** * Shows the window but doesn't focus on it. */ showInactive(): void; /** * Toggles the visibility of the tab bar if native tabs are enabled and there is * only one tab in the current window. * * @platform darwin */ toggleTabBar(): void; /** * Unhooks all of the window messages. * * @platform win32 */ unhookAllWindowMessages(): void; /** * Unhook the window message. * * @platform win32 */ unhookWindowMessage(message: number): void; /** * Unmaximizes the window. */ unmaximize(): void; /** * A `string` property that defines an alternative title provided only to * accessibility tools such as screen readers. This string is not directly visible * to users. */ accessibleTitle: string; /** * A `boolean` property that determines whether the window menu bar should hide * itself automatically. Once set, the menu bar will only show when users press the * single `Alt` key. * * If the menu bar is already visible, setting this property to `true` won't hide * it immediately. */ autoHideMenuBar: boolean; /** * A `boolean` property that determines whether the window can be manually closed * by user. * * On Linux the setter is a no-op, although the getter returns `true`. * * @platform darwin,win32 */ closable: boolean; /** * A `boolean` property that specifies whether the window’s document has been * edited. * * The icon in title bar will become gray when set to `true`. * * @platform darwin */ documentEdited: boolean; /** * A `boolean` property that determines whether the window is excluded from the * application’s Windows menu. `false` by default. * * @platform darwin */ excludedFromShownWindowsMenu: boolean; /** * A `boolean` property that determines whether the window is focusable. * * @platform win32,darwin */ focusable: boolean; /** * A `boolean` property that determines whether the window is in fullscreen mode. */ fullScreen: boolean; /** * A `boolean` property that determines whether the maximize/zoom window button * toggles fullscreen mode or maximizes the window. */ fullScreenable: boolean; /** * A `Integer` property representing the unique ID of the window. Each ID is unique * among all `BrowserWindow` instances of the entire Electron application. * */ readonly id: number; /** * A `boolean` property that determines whether the window is in kiosk mode. */ kiosk: boolean; /** * A `boolean` property that determines whether the window can be manually * maximized by user. * * On Linux the setter is a no-op, although the getter returns `true`. * * @platform darwin,win32 */ maximizable: boolean; /** * A `boolean` property that determines whether the menu bar should be visible. * * **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by * pressing the single `Alt` key. * * @platform win32,linux */ menuBarVisible: boolean; /** * A `boolean` property that determines whether the window can be manually * minimized by user. * * On Linux the setter is a no-op, although the getter returns `true`. * * @platform darwin,win32 */ minimizable: boolean; /** * A `boolean` property that determines Whether the window can be moved by user. * * On Linux the setter is a no-op, although the getter returns `true`. * * @platform darwin,win32 */ movable: boolean; /** * A `string` property that determines the pathname of the file the window * represents, and the icon of the file will show in window's title bar. * * @platform darwin */ representedFilename: string; /** * A `boolean` property that determines whether the window can be manually resized * by user. */ resizable: boolean; /** * A `boolean` property that determines whether the window has a shadow. */ shadow: boolean; /** * A `boolean` property that determines whether the window is in simple (pre-Lion) * fullscreen mode. */ simpleFullScreen: boolean; /** * A `string` property that determines the title of the native window. * * **Note:** The title of the web page can be different from the title of the * native window. */ title: string; /** * A `boolean` property that determines whether the window is visible on all * workspaces. * * **Note:** Always returns false on Windows. * * @platform darwin,linux */ visibleOnAllWorkspaces: boolean; /** * A `WebContents` object this window owns. All web page related events and * operations will be done via it. * * See the `webContents` documentation for its methods and events. * */ readonly webContents: WebContents; } interface Certificate { // Docs: https://electronjs.org/docs/api/structures/certificate /** * PEM encoded data */ data: string; /** * Fingerprint of the certificate */ fingerprint: string; /** * Issuer principal */ issuer: CertificatePrincipal; /** * Issuer certificate (if not self-signed) */ issuerCert: Certificate; /** * Issuer's Common Name */ issuerName: string; /** * Hex value represented string */ serialNumber: string; /** * Subject principal */ subject: CertificatePrincipal; /** * Subject's Common Name */ subjectName: string; /** * End date of the certificate being valid in seconds */ validExpiry: number; /** * Start date of the certificate being valid in seconds */ validStart: number; } interface CertificatePrincipal { // Docs: https://electronjs.org/docs/api/structures/certificate-principal /** * Common Name. */ commonName: string; /** * Country or region. */ country: string; /** * Locality. */ locality: string; /** * Organization names. */ organizations: string[]; /** * Organization Unit names. */ organizationUnits: string[]; /** * State or province. */ state: string; } class ClientRequest extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/client-request /** * Emitted when the `request` is aborted. The `abort` event will not be fired if * the `request` is already closed. */ on(event: "abort", listener: Function): this; once(event: "abort", listener: Function): this; addListener(event: "abort", listener: Function): this; removeListener(event: "abort", listener: Function): this; /** * Emitted as the last event in the HTTP request-response transaction. The `close` * event indicates that no more events will be emitted on either the `request` or * `response` objects. */ on(event: "close", listener: Function): this; once(event: "close", listener: Function): this; addListener(event: "close", listener: Function): this; removeListener(event: "close", listener: Function): this; /** * Emitted when the `net` module fails to issue a network request. Typically when * the `request` object emits an `error` event, a `close` event will subsequently * follow and no response object will be provided. */ on( event: "error", listener: ( /** * an error object providing some information about the failure. */ error: Error, ) => void, ): this; once( event: "error", listener: ( /** * an error object providing some information about the failure. */ error: Error, ) => void, ): this; addListener( event: "error", listener: ( /** * an error object providing some information about the failure. */ error: Error, ) => void, ): this; removeListener( event: "error", listener: ( /** * an error object providing some information about the failure. */ error: Error, ) => void, ): this; /** * Emitted just after the last chunk of the `request`'s data has been written into * the `request` object. */ on(event: "finish", listener: Function): this; once(event: "finish", listener: Function): this; addListener(event: "finish", listener: Function): this; removeListener(event: "finish", listener: Function): this; /** * Emitted when an authenticating proxy is asking for user credentials. * * The `callback` function is expected to be called back with user credentials: * * * `username` string * * `password` string * * Providing empty credentials will cancel the request and report an authentication * error on the response object: */ on(event: "login", listener: (authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; once(event: "login", listener: (authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; addListener(event: "login", listener: (authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; removeListener(event: "login", listener: (authInfo: AuthInfo, callback: (username?: string, password?: string) => void) => void): this; /** * Emitted when the server returns a redirect response (e.g. 301 Moved * Permanently). Calling `request.followRedirect` will continue with the * redirection. If this event is handled, `request.followRedirect` must be called * **synchronously**, otherwise the request will be cancelled. */ on(event: "redirect", listener: (statusCode: number, method: string, redirectUrl: string, responseHeaders: Record) => void): this; once(event: "redirect", listener: (statusCode: number, method: string, redirectUrl: string, responseHeaders: Record) => void): this; addListener(event: "redirect", listener: (statusCode: number, method: string, redirectUrl: string, responseHeaders: Record) => void): this; removeListener(event: "redirect", listener: (statusCode: number, method: string, redirectUrl: string, responseHeaders: Record) => void): this; on( event: "response", listener: ( /** * An object representing the HTTP response message. */ response: IncomingMessage, ) => void, ): this; once( event: "response", listener: ( /** * An object representing the HTTP response message. */ response: IncomingMessage, ) => void, ): this; addListener( event: "response", listener: ( /** * An object representing the HTTP response message. */ response: IncomingMessage, ) => void, ): this; removeListener( event: "response", listener: ( /** * An object representing the HTTP response message. */ response: IncomingMessage, ) => void, ): this; /** * ClientRequest */ constructor(options: ClientRequestConstructorOptions | string); /** * Cancels an ongoing HTTP transaction. If the request has already emitted the * `close` event, the abort operation will have no effect. Otherwise an ongoing * event will emit `abort` and `close` events. Additionally, if there is an ongoing * response object,it will emit the `aborted` event. */ abort(): void; /** * Sends the last chunk of the request data. Subsequent write or end operations * will not be allowed. The `finish` event is emitted just after the end operation. */ end(chunk?: string | Buffer, encoding?: string, callback?: () => void): this; /** * Continues any pending redirection. Can only be called during a `'redirect'` * event. */ followRedirect(): void; /** * The value of a previously set extra header name. */ getHeader(name: string): string; /** * * `active` boolean - Whether the request is currently active. If this is false * no other properties will be set * * `started` boolean - Whether the upload has started. If this is false both * `current` and `total` will be set to 0. * * `current` Integer - The number of bytes that have been uploaded so far * * `total` Integer - The number of bytes that will be uploaded this request * * You can use this method in conjunction with `POST` requests to get the progress * of a file upload or other data transfer. */ getUploadProgress(): UploadProgress; /** * Removes a previously set extra header name. This method can be called only * before first write. Trying to call it after the first write will throw an error. */ removeHeader(name: string): void; /** * Adds an extra HTTP header. The header name will be issued as-is without * lowercasing. It can be called only before first write. Calling this method after * the first write will throw an error. If the passed value is not a `string`, its * `toString()` method will be called to obtain the final value. * * Certain headers are restricted from being set by apps. These headers are listed * below. More information on restricted headers can be found in Chromium's header * utils. * * * `Content-Length` * * `Host` * * `Trailer` or `Te` * * `Upgrade` * * `Cookie2` * * `Keep-Alive` * * `Transfer-Encoding` * * Additionally, setting the `Connection` header to the value `upgrade` is also * disallowed. */ setHeader(name: string, value: string): void; /** * `callback` is essentially a dummy function introduced in the purpose of keeping * similarity with the Node.js API. It is called asynchronously in the next tick * after `chunk` content have been delivered to the Chromium networking layer. * Contrary to the Node.js implementation, it is not guaranteed that `chunk` * content have been flushed on the wire before `callback` is called. * * Adds a chunk of data to the request body. The first write operation may cause * the request headers to be issued on the wire. After the first write operation, * it is not allowed to add or remove a custom header. */ write(chunk: string | Buffer, encoding?: string, callback?: () => void): void; /** * A `boolean` specifying whether the request will use HTTP chunked transfer * encoding or not. Defaults to false. The property is readable and writable, * however it can be set only before the first write operation as the HTTP headers * are not yet put on the wire. Trying to set the `chunkedEncoding` property after * the first write will throw an error. * * Using chunked encoding is strongly recommended if you need to send a large * request body as data will be streamed in small chunks instead of being * internally buffered inside Electron process memory. */ chunkedEncoding: boolean; } interface Clipboard { // Docs: https://electronjs.org/docs/api/clipboard /** * An array of supported formats for the clipboard `type`. */ availableFormats(type?: "selection" | "clipboard"): string[]; /** * Clears the clipboard content. */ clear(type?: "selection" | "clipboard"): void; /** * Whether the clipboard supports the specified `format`. * * @experimental */ has(format: string, type?: "selection" | "clipboard"): boolean; /** * Reads `format` type from the clipboard. * * `format` should contain valid ASCII characters and have `/` separator. `a/c`, * `a/bc` are valid formats while `/abc`, `abc/`, `a/`, `/a`, `a` are not valid. * * @experimental */ read(format: string): string; /** * * `title` string * * `url` string * * Returns an Object containing `title` and `url` keys representing the bookmark in * the clipboard. The `title` and `url` values will be empty strings when the * bookmark is unavailable. The `title` value will always be empty on Windows. * * @platform darwin,win32 */ readBookmark(): ReadBookmark; /** * Reads `format` type from the clipboard. * * @experimental */ readBuffer(format: string): Buffer; /** * The text on the find pasteboard, which is the pasteboard that holds information * about the current state of the active application’s find panel. * * This method uses synchronous IPC when called from the renderer process. The * cached value is reread from the find pasteboard whenever the application is * activated. * * @platform darwin */ readFindText(): string; /** * The content in the clipboard as markup. */ readHTML(type?: "selection" | "clipboard"): string; /** * The image content in the clipboard. */ readImage(type?: "selection" | "clipboard"): NativeImage; /** * The content in the clipboard as RTF. */ readRTF(type?: "selection" | "clipboard"): string; /** * The content in the clipboard as plain text. */ readText(type?: "selection" | "clipboard"): string; /** * Writes `data` to the clipboard. */ write(data: Data, type?: "selection" | "clipboard"): void; /** * Writes the `title` (macOS only) and `url` into the clipboard as a bookmark. * * **Note:** Most apps on Windows don't support pasting bookmarks into them so you * can use `clipboard.write` to write both a bookmark and fallback text to the * clipboard. * * @platform darwin,win32 */ writeBookmark(title: string, url: string, type?: "selection" | "clipboard"): void; /** * Writes the `buffer` into the clipboard as `format`. * * @experimental */ writeBuffer(format: string, buffer: Buffer, type?: "selection" | "clipboard"): void; /** * Writes the `text` into the find pasteboard (the pasteboard that holds * information about the current state of the active application’s find panel) as * plain text. This method uses synchronous IPC when called from the renderer * process. * * @platform darwin */ writeFindText(text: string): void; /** * Writes `markup` to the clipboard. */ writeHTML(markup: string, type?: "selection" | "clipboard"): void; /** * Writes `image` to the clipboard. */ writeImage(image: NativeImage, type?: "selection" | "clipboard"): void; /** * Writes the `text` into the clipboard in RTF. */ writeRTF(text: string, type?: "selection" | "clipboard"): void; /** * Writes the `text` into the clipboard as plain text. */ writeText(text: string, type?: "selection" | "clipboard"): void; } class CommandLine { // Docs: https://electronjs.org/docs/api/command-line /** * Append an argument to Chromium's command line. The argument will be quoted * correctly. Switches will precede arguments regardless of appending order. * * If you're appending an argument like `--switch=value`, consider using * `appendSwitch('switch', 'value')` instead. * * **Note:** This will not affect `process.argv`. The intended usage of this * function is to control Chromium's behavior. */ appendArgument(value: string): void; /** * Append a switch (with optional `value`) to Chromium's command line. * * **Note:** This will not affect `process.argv`. The intended usage of this * function is to control Chromium's behavior. */ appendSwitch(the_switch: string, value?: string): void; /** * The command-line switch value. * * **Note:** When the switch is not present or has no value, it returns empty * string. */ getSwitchValue(the_switch: string): string; /** * Whether the command-line switch is present. */ hasSwitch(the_switch: string): boolean; /** * Removes the specified switch from Chromium's command line. * * **Note:** This will not affect `process.argv`. The intended usage of this * function is to control Chromium's behavior. */ removeSwitch(the_switch: string): void; } interface ContentTracing { // Docs: https://electronjs.org/docs/api/content-tracing /** * resolves with an array of category groups once all child processes have * acknowledged the `getCategories` request * * Get a set of category groups. The category groups can change as new code paths * are reached. See also the list of built-in tracing categories. * * > **NOTE:** Electron adds a non-default tracing category called `"electron"`. * This category can be used to capture Electron-specific tracing events. */ getCategories(): Promise; /** * Resolves with an object containing the `value` and `percentage` of trace buffer * maximum usage * * * `value` number * * `percentage` number * * Get the maximum usage across processes of trace buffer as a percentage of the * full state. */ getTraceBufferUsage(): Promise; /** * resolved once all child processes have acknowledged the `startRecording` * request. * * Start recording on all processes. * * Recording begins immediately locally and asynchronously on child processes as * soon as they receive the EnableRecording request. * * If a recording is already running, the promise will be immediately resolved, as * only one trace operation can be in progress at a time. */ startRecording(options: TraceConfig | TraceCategoriesAndOptions): Promise; /** * resolves with a path to a file that contains the traced data once all child * processes have acknowledged the `stopRecording` request * * Stop recording on all processes. * * Child processes typically cache trace data and only rarely flush and send trace * data back to the main process. This helps to minimize the runtime overhead of * tracing since sending trace data over IPC can be an expensive operation. So, to * end tracing, Chromium asynchronously asks all child processes to flush any * pending trace data. * * Trace data will be written into `resultFilePath`. If `resultFilePath` is empty * or not provided, trace data will be written to a temporary file, and the path * will be returned in the promise. */ stopRecording(resultFilePath?: string): Promise; } interface ContextBridge { // Docs: https://electronjs.org/docs/api/context-bridge exposeInIsolatedWorld(worldId: number, apiKey: string, api: any): void; exposeInMainWorld(apiKey: string, api: any): void; } interface Cookie { // Docs: https://electronjs.org/docs/api/structures/cookie /** * The domain of the cookie; this will be normalized with a preceding dot so that * it's also valid for subdomains. */ domain?: string; /** * The expiration date of the cookie as the number of seconds since the UNIX epoch. * Not provided for session cookies. */ expirationDate?: number; /** * Whether the cookie is a host-only cookie; this will only be `true` if no domain * was passed. */ hostOnly?: boolean; /** * Whether the cookie is marked as HTTP only. */ httpOnly?: boolean; /** * The name of the cookie. */ name: string; /** * The path of the cookie. */ path?: string; /** * The Same Site policy applied to this cookie. Can be `unspecified`, * `no_restriction`, `lax` or `strict`. */ sameSite: "unspecified" | "no_restriction" | "lax" | "strict"; /** * Whether the cookie is marked as secure. */ secure?: boolean; /** * Whether the cookie is a session cookie or a persistent cookie with an expiration * date. */ session?: boolean; /** * The value of the cookie. */ value: string; } class Cookies extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/cookies /** * Emitted when a cookie is changed because it was added, edited, removed, or * expired. */ on( event: "changed", listener: ( event: Event, /** * The cookie that was changed. */ cookie: Cookie, /** * The cause of the change with one of the following values: */ cause: "explicit" | "overwrite" | "expired" | "evicted" | "expired-overwrite", /** * `true` if the cookie was removed, `false` otherwise. */ removed: boolean, ) => void, ): this; once( event: "changed", listener: ( event: Event, /** * The cookie that was changed. */ cookie: Cookie, /** * The cause of the change with one of the following values: */ cause: "explicit" | "overwrite" | "expired" | "evicted" | "expired-overwrite", /** * `true` if the cookie was removed, `false` otherwise. */ removed: boolean, ) => void, ): this; addListener( event: "changed", listener: ( event: Event, /** * The cookie that was changed. */ cookie: Cookie, /** * The cause of the change with one of the following values: */ cause: "explicit" | "overwrite" | "expired" | "evicted" | "expired-overwrite", /** * `true` if the cookie was removed, `false` otherwise. */ removed: boolean, ) => void, ): this; removeListener( event: "changed", listener: ( event: Event, /** * The cookie that was changed. */ cookie: Cookie, /** * The cause of the change with one of the following values: */ cause: "explicit" | "overwrite" | "expired" | "evicted" | "expired-overwrite", /** * `true` if the cookie was removed, `false` otherwise. */ removed: boolean, ) => void, ): this; /** * A promise which resolves when the cookie store has been flushed * * Writes any unwritten cookies data to disk. */ flushStore(): Promise; /** * A promise which resolves an array of cookie objects. * * Sends a request to get all cookies matching `filter`, and resolves a promise * with the response. */ get(filter: CookiesGetFilter): Promise; /** * A promise which resolves when the cookie has been removed * * Removes the cookies matching `url` and `name` */ remove(url: string, name: string): Promise; /** * A promise which resolves when the cookie has been set * * Sets a cookie with `details`. */ set(details: CookiesSetDetails): Promise; } interface CPUUsage { // Docs: https://electronjs.org/docs/api/structures/cpu-usage /** * The number of average idle CPU wakeups per second since the last call to * getCPUUsage. First call returns 0. Will always return 0 on Windows. */ idleWakeupsPerSecond: number; /** * Percentage of CPU used since the last call to getCPUUsage. First call returns 0. */ percentCPUUsage: number; } interface CrashReport { // Docs: https://electronjs.org/docs/api/structures/crash-report date: Date; id: string; } interface CrashReporter { // Docs: https://electronjs.org/docs/api/crash-reporter /** * Set an extra parameter to be sent with the crash report. The values specified * here will be sent in addition to any values set via the `extra` option when * `start` was called. * * Parameters added in this fashion (or via the `extra` parameter to * `crashReporter.start`) are specific to the calling process. Adding extra * parameters in the main process will not cause those parameters to be sent along * with crashes from renderer or other child processes. Similarly, adding extra * parameters in a renderer process will not result in those parameters being sent * with crashes that occur in other renderer processes or in the main process. * * **Note:** Parameters have limits on the length of the keys and values. Key names * must be no longer than 39 bytes, and values must be no longer than 20320 bytes. * Keys with names longer than the maximum will be silently ignored. Key values * longer than the maximum length will be truncated. */ addExtraParameter(key: string, value: string): void; /** * The date and ID of the last crash report. Only crash reports that have been * uploaded will be returned; even if a crash report is present on disk it will not * be returned until it is uploaded. In the case that there are no uploaded * reports, `null` is returned. * * **Note:** This method is only available in the main process. */ getLastCrashReport(): CrashReport; /** * The current 'extra' parameters of the crash reporter. */ getParameters(): Record; /** * Returns all uploaded crash reports. Each report contains the date and uploaded * ID. * * **Note:** This method is only available in the main process. */ getUploadedReports(): CrashReport[]; /** * Whether reports should be submitted to the server. Set through the `start` * method or `setUploadToServer`. * * **Note:** This method is only available in the main process. */ getUploadToServer(): boolean; /** * Remove an extra parameter from the current set of parameters. Future crashes * will not include this parameter. */ removeExtraParameter(key: string): void; /** * This would normally be controlled by user preferences. This has no effect if * called before `start` is called. * * **Note:** This method is only available in the main process. */ setUploadToServer(uploadToServer: boolean): void; /** * This method must be called before using any other `crashReporter` APIs. Once * initialized this way, the crashpad handler collects crashes from all * subsequently created processes. The crash reporter cannot be disabled once * started. * * This method should be called as early as possible in app startup, preferably * before `app.on('ready')`. If the crash reporter is not initialized at the time a * renderer process is created, then that renderer process will not be monitored by * the crash reporter. * * **Note:** You can test out the crash reporter by generating a crash using * `process.crash()`. * * **Note:** If you need to send additional/updated `extra` parameters after your * first call `start` you can call `addExtraParameter`. * * **Note:** Parameters passed in `extra`, `globalExtra` or set with * `addExtraParameter` have limits on the length of the keys and values. Key names * must be at most 39 bytes long, and values must be no longer than 127 bytes. Keys * with names longer than the maximum will be silently ignored. Key values longer * than the maximum length will be truncated. * * **Note:** This method is only available in the main process. */ start(options: CrashReporterStartOptions): void; } interface CustomScheme { // Docs: https://electronjs.org/docs/api/structures/custom-scheme privileges?: Privileges; /** * Custom schemes to be registered with options. */ scheme: string; } class Debugger extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/debugger /** * Emitted when the debugging session is terminated. This happens either when * `webContents` is closed or devtools is invoked for the attached `webContents`. */ on( event: "detach", listener: ( event: Event, /** * Reason for detaching debugger. */ reason: string, ) => void, ): this; once( event: "detach", listener: ( event: Event, /** * Reason for detaching debugger. */ reason: string, ) => void, ): this; addListener( event: "detach", listener: ( event: Event, /** * Reason for detaching debugger. */ reason: string, ) => void, ): this; removeListener( event: "detach", listener: ( event: Event, /** * Reason for detaching debugger. */ reason: string, ) => void, ): this; /** * Emitted whenever the debugging target issues an instrumentation event. */ on( event: "message", listener: ( event: Event, /** * Method name. */ method: string, /** * Event parameters defined by the 'parameters' attribute in the remote debugging * protocol. */ params: any, /** * Unique identifier of attached debugging session, will match the value sent from * `debugger.sendCommand`. */ sessionId: string, ) => void, ): this; once( event: "message", listener: ( event: Event, /** * Method name. */ method: string, /** * Event parameters defined by the 'parameters' attribute in the remote debugging * protocol. */ params: any, /** * Unique identifier of attached debugging session, will match the value sent from * `debugger.sendCommand`. */ sessionId: string, ) => void, ): this; addListener( event: "message", listener: ( event: Event, /** * Method name. */ method: string, /** * Event parameters defined by the 'parameters' attribute in the remote debugging * protocol. */ params: any, /** * Unique identifier of attached debugging session, will match the value sent from * `debugger.sendCommand`. */ sessionId: string, ) => void, ): this; removeListener( event: "message", listener: ( event: Event, /** * Method name. */ method: string, /** * Event parameters defined by the 'parameters' attribute in the remote debugging * protocol. */ params: any, /** * Unique identifier of attached debugging session, will match the value sent from * `debugger.sendCommand`. */ sessionId: string, ) => void, ): this; /** * Attaches the debugger to the `webContents`. */ attach(protocolVersion?: string): void; /** * Detaches the debugger from the `webContents`. */ detach(): void; /** * Whether a debugger is attached to the `webContents`. */ isAttached(): boolean; /** * A promise that resolves with the response defined by the 'returns' attribute of * the command description in the remote debugging protocol or is rejected * indicating the failure of the command. * * Send given command to the debugging target. */ sendCommand(method: string, commandParams?: any, sessionId?: string): Promise; } interface DesktopCapturer { // Docs: https://electronjs.org/docs/api/desktop-capturer /** * Resolves with an array of `DesktopCapturerSource` objects, each * `DesktopCapturerSource` represents a screen or an individual window that can be * captured. * * **Note** Capturing the screen contents requires user consent on macOS 10.15 * Catalina or higher, which can detected by * `systemPreferences.getMediaAccessStatus`. */ getSources(options: SourcesOptions): Promise; } interface DesktopCapturerSource { // Docs: https://electronjs.org/docs/api/structures/desktop-capturer-source /** * An icon image of the application that owns the window or null if the source has * a type screen. The size of the icon is not known in advance and depends on what * the application provides. */ appIcon: NativeImage; /** * A unique identifier that will correspond to the `id` of the matching Display * returned by the Screen API. On some platforms, this is equivalent to the `XX` * portion of the `id` field above and on others it will differ. It will be an * empty string if not available. */ display_id: string; /** * The identifier of a window or screen that can be used as a `chromeMediaSourceId` * constraint when calling `navigator.getUserMedia`. The format of the identifier * will be `window:XX:YY` or `screen:ZZ:0`. XX is the windowID/handle. YY is 1 for * the current process, and 0 for all others. ZZ is a sequential number that * represents the screen, and it does not equal to the index in the source's name. */ id: string; /** * A screen source will be named either `Entire Screen` or `Screen `, while * the name of a window source will match the window title. */ name: string; /** * A thumbnail image. **Note:** There is no guarantee that the size of the * thumbnail is the same as the `thumbnailSize` specified in the `options` passed * to `desktopCapturer.getSources`. The actual size depends on the scale of the * screen or window. */ thumbnail: NativeImage; } interface Dialog { // Docs: https://electronjs.org/docs/api/dialog /** * resolves when the certificate trust dialog is shown. * * On macOS, this displays a modal dialog that shows a message and certificate * information, and gives the user the option of trusting/importing the * certificate. If you provide a `browserWindow` argument the dialog will be * attached to the parent window, making it modal. * * On Windows the options are more limited, due to the Win32 APIs used: * * * The `message` argument is not used, as the OS provides its own confirmation * dialog. * * The `browserWindow` argument is ignored since it is not possible to make this * confirmation dialog modal. * * @platform darwin,win32 */ showCertificateTrustDialog(browserWindow: BrowserWindow, options: CertificateTrustDialogOptions): Promise; /** * resolves when the certificate trust dialog is shown. * * On macOS, this displays a modal dialog that shows a message and certificate * information, and gives the user the option of trusting/importing the * certificate. If you provide a `browserWindow` argument the dialog will be * attached to the parent window, making it modal. * * On Windows the options are more limited, due to the Win32 APIs used: * * * The `message` argument is not used, as the OS provides its own confirmation * dialog. * * The `browserWindow` argument is ignored since it is not possible to make this * confirmation dialog modal. * * @platform darwin,win32 */ showCertificateTrustDialog(options: CertificateTrustDialogOptions): Promise; /** * Displays a modal dialog that shows an error message. * * This API can be called safely before the `ready` event the `app` module emits, * it is usually used to report errors in early stage of startup. If called before * the app `ready`event on Linux, the message will be emitted to stderr, and no GUI * dialog will appear. */ showErrorBox(title: string, content: string): void; /** * resolves with a promise containing the following properties: * * * `response` number - The index of the clicked button. * * `checkboxChecked` boolean - The checked state of the checkbox if * `checkboxLabel` was set. Otherwise `false`. * * Shows a message box. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. */ showMessageBox(browserWindow: BrowserWindow, options: MessageBoxOptions): Promise; /** * resolves with a promise containing the following properties: * * * `response` number - The index of the clicked button. * * `checkboxChecked` boolean - The checked state of the checkbox if * `checkboxLabel` was set. Otherwise `false`. * * Shows a message box. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. */ showMessageBox(options: MessageBoxOptions): Promise; /** * the index of the clicked button. * * Shows a message box, it will block the process until the message box is closed. * It returns the index of the clicked button. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. If `browserWindow` is not shown dialog will not be * attached to it. In such case it will be displayed as an independent window. */ showMessageBoxSync(browserWindow: BrowserWindow, options: MessageBoxSyncOptions): number; /** * the index of the clicked button. * * Shows a message box, it will block the process until the message box is closed. * It returns the index of the clicked button. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. If `browserWindow` is not shown dialog will not be * attached to it. In such case it will be displayed as an independent window. */ showMessageBoxSync(options: MessageBoxSyncOptions): number; /** * Resolve with an object containing the following: * * * `canceled` boolean - whether or not the dialog was canceled. * * `filePaths` string[] - An array of file paths chosen by the user. If the * dialog is cancelled this will be an empty array. * * `bookmarks` string[] (optional) _macOS_ _mas_ - An array matching the * `filePaths` array of base64 encoded strings which contains security scoped * bookmark data. `securityScopedBookmarks` must be enabled for this to be * populated. (For return values, see table here.) * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed or selected * when you want to limit the user to a specific type. For example: * * The `extensions` array should contain extensions without wildcards or dots (e.g. * `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the * `'*'` wildcard (no other wildcard is supported). * * **Note:** On Windows and Linux an open dialog can not be both a file selector * and a directory selector, so if you set `properties` to `['openFile', * 'openDirectory']` on these platforms, a directory selector will be shown. */ showOpenDialog(browserWindow: BrowserWindow, options: OpenDialogOptions): Promise; /** * Resolve with an object containing the following: * * * `canceled` boolean - whether or not the dialog was canceled. * * `filePaths` string[] - An array of file paths chosen by the user. If the * dialog is cancelled this will be an empty array. * * `bookmarks` string[] (optional) _macOS_ _mas_ - An array matching the * `filePaths` array of base64 encoded strings which contains security scoped * bookmark data. `securityScopedBookmarks` must be enabled for this to be * populated. (For return values, see table here.) * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed or selected * when you want to limit the user to a specific type. For example: * * The `extensions` array should contain extensions without wildcards or dots (e.g. * `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the * `'*'` wildcard (no other wildcard is supported). * * **Note:** On Windows and Linux an open dialog can not be both a file selector * and a directory selector, so if you set `properties` to `['openFile', * 'openDirectory']` on these platforms, a directory selector will be shown. */ showOpenDialog(options: OpenDialogOptions): Promise; /** * the file paths chosen by the user; if the dialog is cancelled it returns * `undefined`. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed or selected * when you want to limit the user to a specific type. For example: * * The `extensions` array should contain extensions without wildcards or dots (e.g. * `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the * `'*'` wildcard (no other wildcard is supported). * * **Note:** On Windows and Linux an open dialog can not be both a file selector * and a directory selector, so if you set `properties` to `['openFile', * 'openDirectory']` on these platforms, a directory selector will be shown. */ showOpenDialogSync(browserWindow: BrowserWindow, options: OpenDialogSyncOptions): string[] | undefined; /** * the file paths chosen by the user; if the dialog is cancelled it returns * `undefined`. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed or selected * when you want to limit the user to a specific type. For example: * * The `extensions` array should contain extensions without wildcards or dots (e.g. * `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the * `'*'` wildcard (no other wildcard is supported). * * **Note:** On Windows and Linux an open dialog can not be both a file selector * and a directory selector, so if you set `properties` to `['openFile', * 'openDirectory']` on these platforms, a directory selector will be shown. */ showOpenDialogSync(options: OpenDialogSyncOptions): string[] | undefined; /** * Resolve with an object containing the following: * * * `canceled` boolean - whether or not the dialog was canceled. * * `filePath` string (optional) - If the dialog is canceled, this will be * `undefined`. * * `bookmark` string (optional) _macOS_ _mas_ - Base64 encoded string which * contains the security scoped bookmark data for the saved file. * `securityScopedBookmarks` must be enabled for this to be present. (For return * values, see table here.) * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed, see * `dialog.showOpenDialog` for an example. * * **Note:** On macOS, using the asynchronous version is recommended to avoid * issues when expanding and collapsing the dialog. */ showSaveDialog(browserWindow: BrowserWindow, options: SaveDialogOptions): Promise; /** * Resolve with an object containing the following: * * * `canceled` boolean - whether or not the dialog was canceled. * * `filePath` string (optional) - If the dialog is canceled, this will be * `undefined`. * * `bookmark` string (optional) _macOS_ _mas_ - Base64 encoded string which * contains the security scoped bookmark data for the saved file. * `securityScopedBookmarks` must be enabled for this to be present. (For return * values, see table here.) * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed, see * `dialog.showOpenDialog` for an example. * * **Note:** On macOS, using the asynchronous version is recommended to avoid * issues when expanding and collapsing the dialog. */ showSaveDialog(options: SaveDialogOptions): Promise; /** * the path of the file chosen by the user; if the dialog is cancelled it returns * `undefined`. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed, see * `dialog.showOpenDialog` for an example. */ showSaveDialogSync(browserWindow: BrowserWindow, options: SaveDialogSyncOptions): string | undefined; /** * the path of the file chosen by the user; if the dialog is cancelled it returns * `undefined`. * * The `browserWindow` argument allows the dialog to attach itself to a parent * window, making it modal. * * The `filters` specifies an array of file types that can be displayed, see * `dialog.showOpenDialog` for an example. */ showSaveDialogSync(options: SaveDialogSyncOptions): string | undefined; } interface Display { // Docs: https://electronjs.org/docs/api/structures/display /** * Can be `available`, `unavailable`, `unknown`. */ accelerometerSupport: "available" | "unavailable" | "unknown"; /** * the bounds of the display in DIP points. */ bounds: Rectangle; /** * The number of bits per pixel. */ colorDepth: number; /** * represent a color space (three-dimensional object which contains all realizable * color combinations) for the purpose of color conversions */ colorSpace: string; /** * The number of bits per color component. */ depthPerComponent: number; /** * The display refresh rate. */ displayFrequency: number; /** * Unique identifier associated with the display. */ id: number; /** * `true` for an internal display and `false` for an external display */ internal: boolean; /** * User-friendly label, determined by the platform. */ label: string; /** * Whether or not the display is a monochrome display. */ monochrome: boolean; /** * Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees. */ rotation: number; /** * Output device's pixel scale factor. */ scaleFactor: number; size: Size; /** * Can be `available`, `unavailable`, `unknown`. */ touchSupport: "available" | "unavailable" | "unknown"; /** * the work area of the display in DIP points. */ workArea: Rectangle; workAreaSize: Size; } class Dock { // Docs: https://electronjs.org/docs/api/dock /** * an ID representing the request. * * When `critical` is passed, the dock icon will bounce until either the * application becomes active or the request is canceled. * * When `informational` is passed, the dock icon will bounce for one second. * However, the request remains active until either the application becomes active * or the request is canceled. * * **Note:** This method can only be used while the app is not focused; when the * app is focused it will return -1. * * @platform darwin */ bounce(type?: "critical" | "informational"): number; /** * Cancel the bounce of `id`. * * @platform darwin */ cancelBounce(id: number): void; /** * Bounces the Downloads stack if the filePath is inside the Downloads folder. * * @platform darwin */ downloadFinished(filePath: string): void; /** * The badge string of the dock. * * @platform darwin */ getBadge(): string; /** * The application's dock menu. * * @platform darwin */ getMenu(): Menu | null; /** * Hides the dock icon. * * @platform darwin */ hide(): void; /** * Whether the dock icon is visible. * * @platform darwin */ isVisible(): boolean; /** * Sets the string to be displayed in the dock’s badging area. * * @platform darwin */ setBadge(text: string): void; /** * Sets the `image` associated with this dock icon. * * @platform darwin */ setIcon(image: NativeImage | string): void; /** * Sets the application's dock menu. * * @platform darwin */ setMenu(menu: Menu): void; /** * Resolves when the dock icon is shown. * * @platform darwin */ show(): Promise; } class DownloadItem extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/download-item /** * Emitted when the download is in a terminal state. This includes a completed * download, a cancelled download (via `downloadItem.cancel()`), and interrupted * download that can't be resumed. * * The `state` can be one of following: * * * `completed` - The download completed successfully. * * `cancelled` - The download has been cancelled. * * `interrupted` - The download has interrupted and can not resume. */ on( event: "done", listener: ( event: Event, /** * Can be `completed`, `cancelled` or `interrupted`. */ state: "completed" | "cancelled" | "interrupted", ) => void, ): this; once( event: "done", listener: ( event: Event, /** * Can be `completed`, `cancelled` or `interrupted`. */ state: "completed" | "cancelled" | "interrupted", ) => void, ): this; addListener( event: "done", listener: ( event: Event, /** * Can be `completed`, `cancelled` or `interrupted`. */ state: "completed" | "cancelled" | "interrupted", ) => void, ): this; removeListener( event: "done", listener: ( event: Event, /** * Can be `completed`, `cancelled` or `interrupted`. */ state: "completed" | "cancelled" | "interrupted", ) => void, ): this; /** * Emitted when the download has been updated and is not done. * * The `state` can be one of following: * * * `progressing` - The download is in-progress. * * `interrupted` - The download has interrupted and can be resumed. */ on( event: "updated", listener: ( event: Event, /** * Can be `progressing` or `interrupted`. */ state: "progressing" | "interrupted", ) => void, ): this; once( event: "updated", listener: ( event: Event, /** * Can be `progressing` or `interrupted`. */ state: "progressing" | "interrupted", ) => void, ): this; addListener( event: "updated", listener: ( event: Event, /** * Can be `progressing` or `interrupted`. */ state: "progressing" | "interrupted", ) => void, ): this; removeListener( event: "updated", listener: ( event: Event, /** * Can be `progressing` or `interrupted`. */ state: "progressing" | "interrupted", ) => void, ): this; /** * Cancels the download operation. */ cancel(): void; /** * Whether the download can resume. */ canResume(): boolean; /** * The Content-Disposition field from the response header. */ getContentDisposition(): string; /** * ETag header value. */ getETag(): string; /** * The file name of the download item. * * **Note:** The file name is not always the same as the actual one saved in local * disk. If user changes the file name in a prompted download saving dialog, the * actual name of saved file will be different. */ getFilename(): string; /** * Last-Modified header value. */ getLastModifiedTime(): string; /** * The files mime type. */ getMimeType(): string; /** * The received bytes of the download item. */ getReceivedBytes(): number; /** * Returns the object previously set by * `downloadItem.setSaveDialogOptions(options)`. */ getSaveDialogOptions(): SaveDialogOptions; /** * The save path of the download item. This will be either the path set via * `downloadItem.setSavePath(path)` or the path selected from the shown save * dialog. */ getSavePath(): string; /** * Number of seconds since the UNIX epoch when the download was started. */ getStartTime(): number; /** * The current state. Can be `progressing`, `completed`, `cancelled` or * `interrupted`. * * **Note:** The following methods are useful specifically to resume a `cancelled` * item when session is restarted. */ getState(): "progressing" | "completed" | "cancelled" | "interrupted"; /** * The total size in bytes of the download item. * * If the size is unknown, it returns 0. */ getTotalBytes(): number; /** * The origin URL where the item is downloaded from. */ getURL(): string; /** * The complete URL chain of the item including any redirects. */ getURLChain(): string[]; /** * Whether the download has user gesture. */ hasUserGesture(): boolean; /** * Whether the download is paused. */ isPaused(): boolean; /** * Pauses the download. */ pause(): void; /** * Resumes the download that has been paused. * * **Note:** To enable resumable downloads the server you are downloading from must * support range requests and provide both `Last-Modified` and `ETag` header * values. Otherwise `resume()` will dismiss previously received bytes and restart * the download from the beginning. */ resume(): void; /** * This API allows the user to set custom options for the save dialog that opens * for the download item by default. The API is only available in session's * `will-download` callback function. */ setSaveDialogOptions(options: SaveDialogOptions): void; /** * The API is only available in session's `will-download` callback function. If * `path` doesn't exist, Electron will try to make the directory recursively. If * user doesn't set the save path via the API, Electron will use the original * routine to determine the save path; this usually prompts a save dialog. */ setSavePath(path: string): void; /** * A `string` property that determines the save file path of the download item. * * The property is only available in session's `will-download` callback function. * If user doesn't set the save path via the property, Electron will use the * original routine to determine the save path; this usually prompts a save dialog. */ savePath: string; } interface Extension { // Docs: https://electronjs.org/docs/api/structures/extension id: string; /** * Copy of the extension's manifest data. */ manifest: any; name: string; /** * The extension's file path. */ path: string; /** * The extension's `chrome-extension://` URL. */ url: string; version: string; } interface ExtensionInfo { // Docs: https://electronjs.org/docs/api/structures/extension-info name: string; version: string; } interface FileFilter { // Docs: https://electronjs.org/docs/api/structures/file-filter extensions: string[]; name: string; } interface FilePathWithHeaders { // Docs: https://electronjs.org/docs/api/structures/file-path-with-headers /** * Additional headers to be sent. */ headers?: Record; /** * The path to the file to send. */ path: string; } interface GlobalShortcut { // Docs: https://electronjs.org/docs/api/global-shortcut /** * Whether this application has registered `accelerator`. * * When the accelerator is already taken by other applications, this call will * still return `false`. This behavior is intended by operating systems, since they * don't want applications to fight for global shortcuts. */ isRegistered(accelerator: Accelerator): boolean; /** * Whether or not the shortcut was registered successfully. * * Registers a global shortcut of `accelerator`. The `callback` is called when the * registered shortcut is pressed by the user. * * When the accelerator is already taken by other applications, this call will * silently fail. This behavior is intended by operating systems, since they don't * want applications to fight for global shortcuts. * * The following accelerators will not be registered successfully on macOS 10.14 * Mojave unless the app has been authorized as a trusted accessibility client: * * * "Media Play/Pause" * * "Media Next Track" * * "Media Previous Track" * * "Media Stop" */ register(accelerator: Accelerator, callback: () => void): boolean; /** * Registers a global shortcut of all `accelerator` items in `accelerators`. The * `callback` is called when any of the registered shortcuts are pressed by the * user. * * When a given accelerator is already taken by other applications, this call will * silently fail. This behavior is intended by operating systems, since they don't * want applications to fight for global shortcuts. * * The following accelerators will not be registered successfully on macOS 10.14 * Mojave unless the app has been authorized as a trusted accessibility client: * * * "Media Play/Pause" * * "Media Next Track" * * "Media Previous Track" * * "Media Stop" */ registerAll(accelerators: Accelerator[], callback: () => void): void; /** * Unregisters the global shortcut of `accelerator`. */ unregister(accelerator: Accelerator): void; /** * Unregisters all of the global shortcuts. */ unregisterAll(): void; } interface GPUFeatureStatus { // Docs: https://electronjs.org/docs/api/structures/gpu-feature-status /** * Canvas. */ "2d_canvas": string; /** * Flash. */ flash_3d: string; /** * Flash Stage3D. */ flash_stage3d: string; /** * Flash Stage3D Baseline profile. */ flash_stage3d_baseline: string; /** * Compositing. */ gpu_compositing: string; /** * Multiple Raster Threads. */ multiple_raster_threads: string; /** * Native GpuMemoryBuffers. */ native_gpu_memory_buffers: string; /** * Rasterization. */ rasterization: string; /** * Video Decode. */ video_decode: string; /** * Video Encode. */ video_encode: string; /** * VPx Video Decode. */ vpx_decode: string; /** * WebGL. */ webgl: string; /** * WebGL2. */ webgl2: string; } interface HIDDevice { // Docs: https://electronjs.org/docs/api/structures/hid-device /** * Unique identifier for the device. */ deviceId: string; /** * Unique identifier for the HID interface. A device may have multiple HID * interfaces. */ guid?: string; /** * Name of the device. */ name: string; /** * The USB product ID. */ productId: number; /** * The USB device serial number. */ serialNumber?: string; /** * The USB vendor ID. */ vendorId: number; } interface InAppPurchase extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/in-app-purchase on(event: "transactions-updated", listener: Function): this; once(event: "transactions-updated", listener: Function): this; addListener(event: "transactions-updated", listener: Function): this; removeListener(event: "transactions-updated", listener: Function): this; /** * whether a user can make a payment. */ canMakePayments(): boolean; /** * Completes all pending transactions. */ finishAllTransactions(): void; /** * Completes the pending transactions corresponding to the date. */ finishTransactionByDate(date: string): void; /** * Resolves with an array of `Product` objects. * * Retrieves the product descriptions. */ getProducts(productIDs: string[]): Promise; /** * the path to the receipt. */ getReceiptURL(): string; /** * Returns `true` if the product is valid and added to the payment queue. * * You should listen for the `transactions-updated` event as soon as possible and * certainly before you call `purchaseProduct`. */ purchaseProduct(productID: string, opts?: number | PurchaseProductOpts): Promise; /** * Restores finished transactions. This method can be called either to install * purchases on additional devices, or to restore purchases for an application that * the user deleted and reinstalled. * * The payment queue delivers a new transaction for each previously completed * transaction that can be restored. Each transaction includes a copy of the * original transaction. */ restoreCompletedTransactions(): void; } class IncomingMessage extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/incoming-message /** * Emitted when a request has been canceled during an ongoing HTTP transaction. */ on(event: "aborted", listener: Function): this; once(event: "aborted", listener: Function): this; addListener(event: "aborted", listener: Function): this; removeListener(event: "aborted", listener: Function): this; /** * The `data` event is the usual method of transferring response data into * applicative code. */ on( event: "data", listener: ( /** * A chunk of response body's data. */ chunk: Buffer, ) => void, ): this; once( event: "data", listener: ( /** * A chunk of response body's data. */ chunk: Buffer, ) => void, ): this; addListener( event: "data", listener: ( /** * A chunk of response body's data. */ chunk: Buffer, ) => void, ): this; removeListener( event: "data", listener: ( /** * A chunk of response body's data. */ chunk: Buffer, ) => void, ): this; /** * Indicates that response body has ended. Must be placed before 'data' event. */ on(event: "end", listener: Function): this; once(event: "end", listener: Function): this; addListener(event: "end", listener: Function): this; removeListener(event: "end", listener: Function): this; /** * Returns: * * `error` Error - Typically holds an error string identifying failure root cause. * * Emitted when an error was encountered while streaming response data events. For * instance, if the server closes the underlying while the response is still * streaming, an `error` event will be emitted on the response object and a `close` * event will subsequently follow on the request object. */ on(event: "error", listener: Function): this; once(event: "error", listener: Function): this; addListener(event: "error", listener: Function): this; removeListener(event: "error", listener: Function): this; /** * A `Record` representing the HTTP response headers. * The `headers` object is formatted as follows: * * * All header names are lowercased. * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, * `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, * `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, * `retry-after`, `server`, or `user-agent` are discarded. * * `set-cookie` is always an array. Duplicates are added to the array. * * For duplicate `cookie` headers, the values are joined together with '; '. * * For all other headers, the values are joined together with ', '. */ headers: Record; /** * A `string` indicating the HTTP protocol version number. Typical values are '1.0' * or '1.1'. Additionally `httpVersionMajor` and `httpVersionMinor` are two * Integer-valued readable properties that return respectively the HTTP major and * minor version numbers. */ httpVersion: string; /** * An `Integer` indicating the HTTP protocol major version number. */ httpVersionMajor: number; /** * An `Integer` indicating the HTTP protocol minor version number. */ httpVersionMinor: number; /** * A `string[]` containing the raw HTTP response headers exactly as they were * received. The keys and values are in the same list. It is not a list of tuples. * So, the even-numbered offsets are key values, and the odd-numbered offsets are * the associated values. Header names are not lowercased, and duplicates are not * merged. */ rawHeaders: string[]; /** * An `Integer` indicating the HTTP response status code. */ statusCode: number; /** * A `string` representing the HTTP status message. */ statusMessage: string; } interface InputEvent { // Docs: https://electronjs.org/docs/api/structures/input-event /** * An array of modifiers of the event, can be `shift`, `control`, `ctrl`, `alt`, * `meta`, `command`, `cmd`, `isKeypad`, `isAutoRepeat`, `leftButtonDown`, * `middleButtonDown`, `rightButtonDown`, `capsLock`, `numLock`, `left`, `right`. */ modifiers?: Array<"shift" | "control" | "ctrl" | "alt" | "meta" | "command" | "cmd" | "isKeypad" | "isAutoRepeat" | "leftButtonDown" | "middleButtonDown" | "rightButtonDown" | "capsLock" | "numLock" | "left" | "right">; /** * Can be `undefined`, `mouseDown`, `mouseUp`, `mouseMove`, `mouseEnter`, * `mouseLeave`, `contextMenu`, `mouseWheel`, `rawKeyDown`, `keyDown`, `keyUp`, * `char`, `gestureScrollBegin`, `gestureScrollEnd`, `gestureScrollUpdate`, * `gestureFlingStart`, `gestureFlingCancel`, `gesturePinchBegin`, * `gesturePinchEnd`, `gesturePinchUpdate`, `gestureTapDown`, `gestureShowPress`, * `gestureTap`, `gestureTapCancel`, `gestureShortPress`, `gestureLongPress`, * `gestureLongTap`, `gestureTwoFingerTap`, `gestureTapUnconfirmed`, * `gestureDoubleTap`, `touchStart`, `touchMove`, `touchEnd`, `touchCancel`, * `touchScrollStarted`, `pointerDown`, `pointerUp`, `pointerMove`, * `pointerRawUpdate`, `pointerCancel` or `pointerCausedUaAction`. */ type: | "undefined" | "mouseDown" | "mouseUp" | "mouseMove" | "mouseEnter" | "mouseLeave" | "contextMenu" | "mouseWheel" | "rawKeyDown" | "keyDown" | "keyUp" | "char" | "gestureScrollBegin" | "gestureScrollEnd" | "gestureScrollUpdate" | "gestureFlingStart" | "gestureFlingCancel" | "gesturePinchBegin" | "gesturePinchEnd" | "gesturePinchUpdate" | "gestureTapDown" | "gestureShowPress" | "gestureTap" | "gestureTapCancel" | "gestureShortPress" | "gestureLongPress" | "gestureLongTap" | "gestureTwoFingerTap" | "gestureTapUnconfirmed" | "gestureDoubleTap" | "touchStart" | "touchMove" | "touchEnd" | "touchCancel" | "touchScrollStarted" | "pointerDown" | "pointerUp" | "pointerMove" | "pointerRawUpdate" | "pointerCancel" | "pointerCausedUaAction"; } interface IOCounters { // Docs: https://electronjs.org/docs/api/structures/io-counters /** * Then number of I/O other operations. */ otherOperationCount: number; /** * Then number of I/O other transfers. */ otherTransferCount: number; /** * The number of I/O read operations. */ readOperationCount: number; /** * The number of I/O read transfers. */ readTransferCount: number; /** * The number of I/O write operations. */ writeOperationCount: number; /** * The number of I/O write transfers. */ writeTransferCount: number; } interface IpcMain extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/ipc-main /** * Adds a handler for an `invoke`able IPC. This handler will be called whenever a * renderer calls `ipcRenderer.invoke(channel, ...args)`. * * If `listener` returns a Promise, the eventual result of the promise will be * returned as a reply to the remote caller. Otherwise, the return value of the * listener will be used as the value of the reply. * * The `event` that is passed as the first argument to the handler is the same as * that passed to a regular event listener. It includes information about which * WebContents is the source of the invoke request. * * Errors thrown through `handle` in the main process are not transparent as they * are serialized and only the `message` property from the original error is * provided to the renderer process. Please refer to #24427 for details. */ handle(channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => Promise | any): void; /** * Handles a single `invoke`able IPC message, then removes the listener. See * `ipcMain.handle(channel, listener)`. */ handleOnce(channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => Promise | any): void; /** * Listens to `channel`, when a new message arrives `listener` would be called with * `listener(event, args...)`. */ on(channel: string, listener: (event: IpcMainEvent, ...args: any[]) => void): this; /** * Adds a one time `listener` function for the event. This `listener` is invoked * only the next time a message is sent to `channel`, after which it is removed. */ once(channel: string, listener: (event: IpcMainEvent, ...args: any[]) => void): this; /** * Removes listeners of the specified `channel`. */ removeAllListeners(channel?: string): this; /** * Removes any handler for `channel`, if present. */ removeHandler(channel: string): void; /** * Removes the specified `listener` from the listener array for the specified * `channel`. */ removeListener(channel: string, listener: (...args: any[]) => void): this; } interface IpcMainEvent extends Event { // Docs: https://electronjs.org/docs/api/structures/ipc-main-event /** * The ID of the renderer frame that sent this message */ frameId: number; /** * A list of MessagePorts that were transferred with this message */ ports: MessagePortMain[]; /** * The internal ID of the renderer process that sent this message */ processId: number; /** * A function that will send an IPC message to the renderer frame that sent the * original message that you are currently handling. You should use this method to * "reply" to the sent message in order to guarantee the reply will go to the * correct process and frame. */ reply: (channel: string, ...args: any[]) => void; /** * Set this to the value to be returned in a synchronous message */ returnValue: any; /** * Returns the `webContents` that sent the message */ sender: WebContents; /** * The frame that sent this message * */ readonly senderFrame: WebFrameMain; } interface IpcMainInvokeEvent extends Event { // Docs: https://electronjs.org/docs/api/structures/ipc-main-invoke-event /** * The ID of the renderer frame that sent this message */ frameId: number; /** * The internal ID of the renderer process that sent this message */ processId: number; /** * Returns the `webContents` that sent the message */ sender: WebContents; /** * The frame that sent this message * */ readonly senderFrame: WebFrameMain; } interface IpcRenderer extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/ipc-renderer /** * Resolves with the response from the main process. * * Send a message to the main process via `channel` and expect a result * asynchronously. Arguments will be serialized with the Structured Clone * Algorithm, just like `window.postMessage`, so prototype chains will not be * included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw * an exception. * * The main process should listen for `channel` with `ipcMain.handle()`. * * For example: * * If you need to transfer a `MessagePort` to the main process, use * `ipcRenderer.postMessage`. * * If you do not need a response to the message, consider using `ipcRenderer.send`. * * > **Note** Sending non-standard JavaScript types such as DOM objects or special * Electron objects will throw an exception. * * Since the main process does not have support for DOM objects such as * `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over * Electron's IPC to the main process, as the main process would have no way to * decode them. Attempting to send such objects over IPC will result in an error. * * > **Note** If the handler in the main process throws an error, the promise * returned by `invoke` will reject. However, the `Error` object in the renderer * process will not be the same as the one thrown in the main process. */ invoke(channel: string, ...args: any[]): Promise; /** * Listens to `channel`, when a new message arrives `listener` would be called with * `listener(event, args...)`. */ on(channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void): this; /** * Adds a one time `listener` function for the event. This `listener` is invoked * only the next time a message is sent to `channel`, after which it is removed. */ once(channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void): this; /** * Send a message to the main process, optionally transferring ownership of zero or * more `MessagePort` objects. * * The transferred `MessagePort` objects will be available in the main process as * `MessagePortMain` objects by accessing the `ports` property of the emitted * event. * * For example: * * For more information on using `MessagePort` and `MessageChannel`, see the MDN * documentation. */ postMessage(channel: string, message: any, transfer?: MessagePort[]): void; /** * Removes all listeners, or those of the specified `channel`. */ removeAllListeners(channel: string): this; /** * Removes the specified `listener` from the listener array for the specified * `channel`. */ removeListener(channel: string, listener: (...args: any[]) => void): this; /** * Send an asynchronous message to the main process via `channel`, along with * arguments. Arguments will be serialized with the Structured Clone Algorithm, * just like `window.postMessage`, so prototype chains will not be included. * Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an * exception. * * > **NOTE:** Sending non-standard JavaScript types such as DOM objects or special * Electron objects will throw an exception. * * Since the main process does not have support for DOM objects such as * `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over * Electron's IPC to the main process, as the main process would have no way to * decode them. Attempting to send such objects over IPC will result in an error. * * The main process handles it by listening for `channel` with the `ipcMain` * module. * * If you need to transfer a `MessagePort` to the main process, use * `ipcRenderer.postMessage`. * * If you want to receive a single response from the main process, like the result * of a method call, consider using `ipcRenderer.invoke`. */ send(channel: string, ...args: any[]): void; /** * The value sent back by the `ipcMain` handler. * * Send a message to the main process via `channel` and expect a result * synchronously. Arguments will be serialized with the Structured Clone Algorithm, * just like `window.postMessage`, so prototype chains will not be included. * Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an * exception. * * > **NOTE:** Sending non-standard JavaScript types such as DOM objects or special * Electron objects will throw an exception. * * Since the main process does not have support for DOM objects such as * `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over * Electron's IPC to the main process, as the main process would have no way to * decode them. Attempting to send such objects over IPC will result in an error. * * The main process handles it by listening for `channel` with `ipcMain` module, * and replies by setting `event.returnValue`. * * > :warning: **WARNING**: Sending a synchronous message will block the whole * renderer process until the reply is received, so use this method only as a last * resort. It's much better to use the asynchronous version, `invoke()`. */ sendSync(channel: string, ...args: any[]): any; /** * Sends a message to a window with `webContentsId` via `channel`. */ sendTo(webContentsId: number, channel: string, ...args: any[]): void; /** * Like `ipcRenderer.send` but the event will be sent to the `` element in * the host page instead of the main process. */ sendToHost(channel: string, ...args: any[]): void; } interface IpcRendererEvent extends Event { // Docs: https://electronjs.org/docs/api/structures/ipc-renderer-event /** * A list of MessagePorts that were transferred with this message */ ports: MessagePort[]; /** * The `IpcRenderer` instance that emitted the event originally */ sender: IpcRenderer; /** * The `webContents.id` that sent the message, you can call * `event.sender.sendTo(event.senderId, ...)` to reply to the message, see * ipcRenderer.sendTo for more information. This only applies to messages sent from * a different renderer. Messages sent directly from the main process set * `event.senderId` to `0`. */ senderId: number; } interface JumpListCategory { // Docs: https://electronjs.org/docs/api/structures/jump-list-category /** * Array of `JumpListItem` objects if `type` is `tasks` or `custom`, otherwise it * should be omitted. */ items?: JumpListItem[]; /** * Must be set if `type` is `custom`, otherwise it should be omitted. */ name?: string; /** * One of the following: */ type?: "tasks" | "frequent" | "recent" | "custom"; } interface JumpListItem { // Docs: https://electronjs.org/docs/api/structures/jump-list-item /** * The command line arguments when `program` is executed. Should only be set if * `type` is `task`. */ args?: string; /** * Description of the task (displayed in a tooltip). Should only be set if `type` * is `task`. Maximum length 260 characters. */ description?: string; /** * The index of the icon in the resource file. If a resource file contains multiple * icons this value can be used to specify the zero-based index of the icon that * should be displayed for this task. If a resource file contains only one icon, * this property should be set to zero. */ iconIndex?: number; /** * The absolute path to an icon to be displayed in a Jump List, which can be an * arbitrary resource file that contains an icon (e.g. `.ico`, `.exe`, `.dll`). You * can usually specify `process.execPath` to show the program icon. */ iconPath?: string; /** * Path of the file to open, should only be set if `type` is `file`. */ path?: string; /** * Path of the program to execute, usually you should specify `process.execPath` * which opens the current program. Should only be set if `type` is `task`. */ program?: string; /** * The text to be displayed for the item in the Jump List. Should only be set if * `type` is `task`. */ title?: string; /** * One of the following: */ type?: "task" | "separator" | "file"; /** * The working directory. Default is empty. */ workingDirectory?: string; } interface KeyboardEvent { // Docs: https://electronjs.org/docs/api/structures/keyboard-event /** * whether an Alt key was used in an accelerator to trigger the Event */ altKey?: boolean; /** * whether the Control key was used in an accelerator to trigger the Event */ ctrlKey?: boolean; /** * whether a meta key was used in an accelerator to trigger the Event */ metaKey?: boolean; /** * whether a Shift key was used in an accelerator to trigger the Event */ shiftKey?: boolean; /** * whether an accelerator was used to trigger the event as opposed to another user * gesture like mouse click */ triggeredByAccelerator?: boolean; } interface KeyboardInputEvent extends InputEvent { // Docs: https://electronjs.org/docs/api/structures/keyboard-input-event /** * The character that will be sent as the keyboard event. Should only use the valid * key codes in Accelerator. */ keyCode: string; /** * The type of the event, can be `rawKeyDown`, `keyDown`, `keyUp` or `char`. */ type: "rawKeyDown" | "keyDown" | "keyUp" | "char"; } interface MemoryInfo { // Docs: https://electronjs.org/docs/api/structures/memory-info /** * The maximum amount of memory that has ever been pinned to actual physical RAM. */ peakWorkingSetSize: number; /** * The amount of memory not shared by other processes, such as JS heap or HTML * content. * * @platform win32 */ privateBytes?: number; /** * The amount of memory currently pinned to actual physical RAM. */ workingSetSize: number; } interface MemoryUsageDetails { // Docs: https://electronjs.org/docs/api/structures/memory-usage-details count: number; liveSize: number; size: number; } class Menu extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/menu /** * Emitted when a popup is closed either manually or with `menu.closePopup()`. */ on(event: "menu-will-close", listener: (event: Event) => void): this; once(event: "menu-will-close", listener: (event: Event) => void): this; addListener(event: "menu-will-close", listener: (event: Event) => void): this; removeListener(event: "menu-will-close", listener: (event: Event) => void): this; /** * Emitted when `menu.popup()` is called. */ on(event: "menu-will-show", listener: (event: Event) => void): this; once(event: "menu-will-show", listener: (event: Event) => void): this; addListener(event: "menu-will-show", listener: (event: Event) => void): this; removeListener(event: "menu-will-show", listener: (event: Event) => void): this; /** * Menu */ constructor(); /** * Generally, the `template` is an array of `options` for constructing a MenuItem. * The usage can be referenced above. * * You can also attach other fields to the element of the `template` and they will * become properties of the constructed menu items. */ static buildFromTemplate(template: Array): Menu; /** * The application menu, if set, or `null`, if not set. * * **Note:** The returned `Menu` instance doesn't support dynamic addition or * removal of menu items. Instance properties can still be dynamically modified. */ static getApplicationMenu(): Menu | null; /** * Sends the `action` to the first responder of application. This is used for * emulating default macOS menu behaviors. Usually you would use the `role` * property of a `MenuItem`. * * See the macOS Cocoa Event Handling Guide for more information on macOS' native * actions. * * @platform darwin */ static sendActionToFirstResponder(action: string): void; /** * Sets `menu` as the application menu on macOS. On Windows and Linux, the `menu` * will be set as each window's top menu. * * Also on Windows and Linux, you can use a `&` in the top-level item name to * indicate which letter should get a generated accelerator. For example, using * `&File` for the file menu would result in a generated `Alt-F` accelerator that * opens the associated menu. The indicated character in the button label then gets * an underline, and the `&` character is not displayed on the button label. * * In order to escape the `&` character in an item name, add a proceeding `&`. For * example, `&&File` would result in `&File` displayed on the button label. * * Passing `null` will suppress the default menu. On Windows and Linux, this has * the additional effect of removing the menu bar from the window. * * **Note:** The default menu will be created automatically if the app does not set * one. It contains standard items such as `File`, `Edit`, `View`, `Window` and * `Help`. */ static setApplicationMenu(menu: Menu | null): void; /** * Appends the `menuItem` to the menu. */ append(menuItem: MenuItem): void; /** * Closes the context menu in the `browserWindow`. */ closePopup(browserWindow?: BrowserWindow): void; /** * the item with the specified `id` */ getMenuItemById(id: string): MenuItem | null; /** * Inserts the `menuItem` to the `pos` position of the menu. */ insert(pos: number, menuItem: MenuItem): void; /** * Pops up this menu as a context menu in the `BrowserWindow`. */ popup(options?: PopupOptions): void; /** * A `MenuItem[]` array containing the menu's items. * * Each `Menu` consists of multiple `MenuItem`s and each `MenuItem` can have a * submenu. */ items: MenuItem[]; } class MenuItem { // Docs: https://electronjs.org/docs/api/menu-item /** * MenuItem */ constructor(options: MenuItemConstructorOptions); /** * An `Accelerator` (optional) indicating the item's accelerator, if set. */ accelerator?: Accelerator; /** * A `boolean` indicating whether the item is checked, this property can be * dynamically changed. * * A `checkbox` menu item will toggle the `checked` property on and off when * selected. * * A `radio` menu item will turn on its `checked` property when clicked, and will * turn off that property for all adjacent items in the same menu. * * You can add a `click` function for additional behavior. */ checked: boolean; /** * A `Function` that is fired when the MenuItem receives a click event. It can be * called with `menuItem.click(event, focusedWindow, focusedWebContents)`. * * * `event` KeyboardEvent * * `focusedWindow` BrowserWindow * * `focusedWebContents` WebContents */ click: Function; /** * A `number` indicating an item's sequential unique id. */ commandId: number; /** * A `boolean` indicating whether the item is enabled, this property can be * dynamically changed. */ enabled: boolean; /** * A `NativeImage | string` (optional) indicating the item's icon, if set. */ icon?: NativeImage | string; /** * A `string` indicating the item's unique id, this property can be dynamically * changed. */ id: string; /** * A `string` indicating the item's visible label. */ label: string; /** * A `Menu` that the item is a part of. */ menu: Menu; /** * A `boolean` indicating if the accelerator should be registered with the system * or just displayed. * * This property can be dynamically changed. */ registerAccelerator: boolean; /** * A `string` (optional) indicating the item's role, if set. Can be `undo`, `redo`, * `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, * `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, * `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, * `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, * `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, * `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, * `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, * `moveTabToNewWindow` or `windowMenu` */ role?: | "undo" | "redo" | "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "delete" | "selectAll" | "reload" | "forceReload" | "toggleDevTools" | "resetZoom" | "zoomIn" | "zoomOut" | "toggleSpellChecker" | "togglefullscreen" | "window" | "minimize" | "close" | "help" | "about" | "services" | "hide" | "hideOthers" | "unhide" | "quit" | "startSpeaking" | "stopSpeaking" | "zoom" | "front" | "appMenu" | "fileMenu" | "editMenu" | "viewMenu" | "shareMenu" | "recentDocuments" | "toggleTabBar" | "selectNextTab" | "selectPreviousTab" | "mergeAllWindows" | "clearRecentDocuments" | "moveTabToNewWindow" | "windowMenu"; /** * A `SharingItem` indicating the item to share when the `role` is `shareMenu`. * * This property can be dynamically changed. * * @platform darwin */ sharingItem: SharingItem; /** * A `string` indicating the item's sublabel. */ sublabel: string; /** * A `Menu` (optional) containing the menu item's submenu, if present. */ submenu?: Menu; /** * A `string` indicating the item's hover text. * * @platform darwin */ toolTip: string; /** * A `string` indicating the type of the item. Can be `normal`, `separator`, * `submenu`, `checkbox` or `radio`. */ type: "normal" | "separator" | "submenu" | "checkbox" | "radio"; /** * An `Accelerator | null` indicating the item's user-assigned accelerator for the * menu item. * * **Note:** This property is only initialized after the `MenuItem` has been added * to a `Menu`. Either via `Menu.buildFromTemplate` or via * `Menu.append()/insert()`. Accessing before initialization will just return * `null`. * * @platform darwin */ readonly userAccelerator: Accelerator | null; /** * A `boolean` indicating whether the item is visible, this property can be * dynamically changed. */ visible: boolean; } class MessageChannelMain extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/message-channel-main /** * A `MessagePortMain` property. */ port1: MessagePortMain; /** * A `MessagePortMain` property. */ port2: MessagePortMain; } class MessagePortMain extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/message-port-main /** * Emitted when the remote end of a MessagePortMain object becomes disconnected. */ on(event: "close", listener: Function): this; once(event: "close", listener: Function): this; addListener(event: "close", listener: Function): this; removeListener(event: "close", listener: Function): this; /** * Emitted when a MessagePortMain object receives a message. */ on(event: "message", listener: (messageEvent: MessageEvent) => void): this; once(event: "message", listener: (messageEvent: MessageEvent) => void): this; addListener(event: "message", listener: (messageEvent: MessageEvent) => void): this; removeListener(event: "message", listener: (messageEvent: MessageEvent) => void): this; /** * Disconnects the port, so it is no longer active. */ close(): void; /** * Sends a message from the port, and optionally, transfers ownership of objects to * other browsing contexts. */ postMessage(message: any, transfer?: MessagePortMain[]): void; /** * Starts the sending of messages queued on the port. Messages will be queued until * this method is called. */ start(): void; } interface MimeTypedBuffer { // Docs: https://electronjs.org/docs/api/structures/mime-typed-buffer /** * Charset of the buffer. */ charset?: string; /** * The actual Buffer content. */ data: Buffer; /** * MIME type of the buffer. */ mimeType?: string; } interface MouseInputEvent extends InputEvent { // Docs: https://electronjs.org/docs/api/structures/mouse-input-event /** * The button pressed, can be `left`, `middle`, `right`. */ button?: "left" | "middle" | "right"; clickCount?: number; globalX?: number; globalY?: number; movementX?: number; movementY?: number; /** * The type of the event, can be `mouseDown`, `mouseUp`, `mouseEnter`, * `mouseLeave`, `contextMenu`, `mouseWheel` or `mouseMove`. */ type: "mouseDown" | "mouseUp" | "mouseEnter" | "mouseLeave" | "contextMenu" | "mouseWheel" | "mouseMove"; x: number; y: number; } interface MouseWheelInputEvent extends MouseInputEvent { // Docs: https://electronjs.org/docs/api/structures/mouse-wheel-input-event accelerationRatioX?: number; accelerationRatioY?: number; canScroll?: boolean; deltaX?: number; deltaY?: number; hasPreciseScrollingDeltas?: boolean; /** * The type of the event, can be `mouseWheel`. */ type: "mouseWheel"; wheelTicksX?: number; wheelTicksY?: number; } class NativeImage { // Docs: https://electronjs.org/docs/api/native-image /** * Creates an empty `NativeImage` instance. */ static createEmpty(): NativeImage; /** * Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap * pixel data returned by `toBitmap()`. The specific format is platform-dependent. */ static createFromBitmap(buffer: Buffer, options: CreateFromBitmapOptions): NativeImage; /** * Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or * JPEG first. */ static createFromBuffer(buffer: Buffer, options?: CreateFromBufferOptions): NativeImage; /** * Creates a new `NativeImage` instance from `dataURL`. */ static createFromDataURL(dataURL: string): NativeImage; /** * Creates a new `NativeImage` instance from the NSImage that maps to the given * image name. See `System Icons` for a list of possible values. * * The `hslShift` is applied to the image with the following rules: * * * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0 * and 360 on the hue color wheel (red). * * `hsl_shift[1]` (saturation): A saturation shift for the image, with the * following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully * saturate the image. * * `hsl_shift[2]` (lightness): A lightness shift for the image, with the * following key values: 0 = remove all lightness (make all pixels black). 0.5 = * leave unchanged. 1 = full lightness (make all pixels white). * * This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1, * 0]` will make the image completely black. * * In some cases, the `NSImageName` doesn't match its string representation; one * example of this is `NSFolderImageName`, whose string representation would * actually be `NSFolder`. Therefore, you'll need to determine the correct string * representation for your image before passing it in. This can be done with the * following: * * `echo -e '#import \nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); * }' | clang -otest -x objective-c -framework Cocoa - && ./test` * * where `SYSTEM_IMAGE_NAME` should be replaced with any value from this list. * * @platform darwin */ static createFromNamedImage(imageName: string, hslShift?: number[]): NativeImage; /** * Creates a new `NativeImage` instance from a file located at `path`. This method * returns an empty image if the `path` does not exist, cannot be read, or is not a * valid image. */ static createFromPath(path: string): NativeImage; /** * fulfilled with the file's thumbnail preview image, which is a NativeImage. * * Note: The Windows implementation will ignore `size.height` and scale the height * according to `size.width`. * * @platform darwin,win32 */ static createThumbnailFromPath(path: string, size: Size): Promise; /** * Add an image representation for a specific scale factor. This can be used to * explicitly add different scale factor representations to an image. This can be * called on empty images. */ addRepresentation(options: AddRepresentationOptions): void; /** * The cropped image. */ crop(rect: Rectangle): NativeImage; /** * The image's aspect ratio. * * If `scaleFactor` is passed, this will return the aspect ratio corresponding to * the image representation most closely matching the passed value. */ getAspectRatio(scaleFactor?: number): number; /** * A Buffer that contains the image's raw bitmap pixel data. * * The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does * not copy the bitmap data, so you have to use the returned Buffer immediately in * current event loop tick; otherwise the data might be changed or destroyed. */ getBitmap(options?: BitmapOptions): Buffer; /** * A Buffer that stores C pointer to underlying native handle of the image. On * macOS, a pointer to `NSImage` instance would be returned. * * Notice that the returned pointer is a weak pointer to the underlying native * image instead of a copy, so you _must_ ensure that the associated `nativeImage` * instance is kept around. * * @platform darwin */ getNativeHandle(): Buffer; /** * An array of all scale factors corresponding to representations for a given * nativeImage. */ getScaleFactors(): number[]; /** * If `scaleFactor` is passed, this will return the size corresponding to the image * representation most closely matching the passed value. */ getSize(scaleFactor?: number): Size; /** * Whether the image is empty. */ isEmpty(): boolean; /** * Whether the image is a template image. */ isTemplateImage(): boolean; /** * The resized image. * * If only the `height` or the `width` are specified then the current aspect ratio * will be preserved in the resized image. */ resize(options: ResizeOptions): NativeImage; /** * Marks the image as a template image. */ setTemplateImage(option: boolean): void; /** * A Buffer that contains a copy of the image's raw bitmap pixel data. */ toBitmap(options?: ToBitmapOptions): Buffer; /** * The data URL of the image. */ toDataURL(options?: ToDataURLOptions): string; /** * A Buffer that contains the image's `JPEG` encoded data. */ toJPEG(quality: number): Buffer; /** * A Buffer that contains the image's `PNG` encoded data. */ toPNG(options?: ToPNGOptions): Buffer; /** * A `boolean` property that determines whether the image is considered a template * image. * * Please note that this property only has an effect on macOS. * * @platform darwin */ isMacTemplateImage: boolean; } interface NativeTheme extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/native-theme /** * Emitted when something in the underlying NativeTheme has changed. This normally * means that either the value of `shouldUseDarkColors`, * `shouldUseHighContrastColors` or `shouldUseInvertedColorScheme` has changed. You * will have to check them to determine which one has changed. */ on(event: "updated", listener: Function): this; once(event: "updated", listener: Function): this; addListener(event: "updated", listener: Function): this; removeListener(event: "updated", listener: Function): this; /** * A `boolean` indicating whether Chromium is in forced colors mode, controlled by * system accessibility settings. Currently, Windows high contrast is the only * system setting that triggers forced colors mode. * * @platform win32 */ readonly inForcedColorsMode: boolean; /** * A `boolean` for if the OS / Chromium currently has a dark mode enabled or is * being instructed to show a dark-style UI. If you want to modify this value you * should use `themeSource` below. * */ readonly shouldUseDarkColors: boolean; /** * A `boolean` for if the OS / Chromium currently has high-contrast mode enabled or * is being instructed to show a high-contrast UI. * * @platform darwin,win32 */ readonly shouldUseHighContrastColors: boolean; /** * A `boolean` for if the OS / Chromium currently has an inverted color scheme or * is being instructed to use an inverted color scheme. * * @platform darwin,win32 */ readonly shouldUseInvertedColorScheme: boolean; /** * A `string` property that can be `system`, `light` or `dark`. It is used to * override and supersede the value that Chromium has chosen to use internally. * * Setting this property to `system` will remove the override and everything will * be reset to the OS default. By default `themeSource` is `system`. * * Settings this property to `dark` will have the following effects: * * * `nativeTheme.shouldUseDarkColors` will be `true` when accessed * * Any UI Electron renders on Linux and Windows including context menus, * devtools, etc. will use the dark UI. * * Any UI the OS renders on macOS including menus, window frames, etc. will use * the dark UI. * * The `prefers-color-scheme` CSS query will match `dark` mode. * * The `updated` event will be emitted * * Settings this property to `light` will have the following effects: * * * `nativeTheme.shouldUseDarkColors` will be `false` when accessed * * Any UI Electron renders on Linux and Windows including context menus, * devtools, etc. will use the light UI. * * Any UI the OS renders on macOS including menus, window frames, etc. will use * the light UI. * * The `prefers-color-scheme` CSS query will match `light` mode. * * The `updated` event will be emitted * * The usage of this property should align with a classic "dark mode" state machine * in your application where the user has three options. * * * `Follow OS` --> `themeSource = 'system'` * * `Dark Mode` --> `themeSource = 'dark'` * * `Light Mode` --> `themeSource = 'light'` * * Your application should then always use `shouldUseDarkColors` to determine what * CSS to apply. */ themeSource: "system" | "light" | "dark"; } interface Net { // Docs: https://electronjs.org/docs/api/net /** * see Response. * * Sends a request, similarly to how `fetch()` works in the renderer, using * Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's * HTTP stack. * * Example: * * This method will issue requests from the default session. To send a `fetch` * request from another session, use ses.fetch(). * * See the MDN documentation for `fetch()` for more details. * * Limitations: * * * `net.fetch()` does not support the `data:` or `blob:` schemes. * * The value of the `integrity` option is ignored. * * The `.type` and `.url` values of the returned `Response` object are incorrect. * * By default, requests made with `net.fetch` can be made to custom protocols as * well as `file:`, and will trigger webRequest handlers if present. When the * non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom * protocol handlers will not be called for this request. This allows forwarding an * intercepted request to the built-in handler. webRequest handlers will still be * triggered when bypassing custom protocols. */ fetch(input: string | GlobalRequest, init?: RequestInit & { bypassCustomProtocolHandlers?: boolean }): Promise; /** * Whether there is currently internet connection. * * A return value of `false` is a pretty strong indicator that the user won't be * able to connect to remote sites. However, a return value of `true` is * inconclusive; even if some link is up, it is uncertain whether a particular * connection attempt to a particular remote site will be successful. */ isOnline(): boolean; /** * Creates a `ClientRequest` instance using the provided `options` which are * directly forwarded to the `ClientRequest` constructor. The `net.request` method * would be used to issue both secure and insecure HTTP requests according to the * specified protocol scheme in the `options` object. */ request(options: ClientRequestConstructorOptions | string): ClientRequest; /** * Resolves with the resolved IP addresses for the `host`. * * This method will resolve hosts from the default session. To resolve a host from * another session, use ses.resolveHost(). */ resolveHost(host: string, options?: ResolveHostOptions): Promise; /** * A `boolean` property. Whether there is currently internet connection. * * A return value of `false` is a pretty strong indicator that the user won't be * able to connect to remote sites. However, a return value of `true` is * inconclusive; even if some link is up, it is uncertain whether a particular * connection attempt to a particular remote site will be successful. * */ readonly online: boolean; } interface NetLog { // Docs: https://electronjs.org/docs/api/net-log /** * resolves when the net log has begun recording. * * Starts recording network events to `path`. */ startLogging(path: string, options?: StartLoggingOptions): Promise; /** * resolves when the net log has been flushed to disk. * * Stops recording network events. If not called, net logging will automatically * end when app quits. */ stopLogging(): Promise; /** * A `boolean` property that indicates whether network logs are currently being * recorded. * */ readonly currentlyLogging: boolean; } class Notification extends NodeEventEmitter { // Docs: https://electronjs.org/docs/api/notification /** * @platform darwin */ on( event: "action", listener: ( event: Event, /** * The index of the action that was activated. */ index: number, ) => void, ): this; once( event: "action", listener: ( event: Event, /** * The index of the action that was activated. */ index: number, ) => void, ): this; addListener( event: "action", listener: ( event: Event, /** * The index of the action that was activated. */ index: number, ) => void, ): this; removeListener( event: "action", listener: ( event: Event, /** * The index of the action that was activated. */ index: number, ) => void, ): this; /** * Emitted when the notification is clicked by the user. */ on(event: "click", listener: (event: Event) => void): this; once(event: "click", listener: (event: Event) => void): this; addListener(event: "click", listener: (event: Event) => void): this; removeListener(event: "click", listener: (event: Event) => void): this; /** * Emitted when the notification is closed by manual intervention from the user. * * This event is not guaranteed to be emitted in all cases where the notification * is closed. */ on(event: "close", listener: (event: Event) => void): this; once(event: "close", listener: (event: Event) => void): this; addListener(event: "close", listener: (event: Event) => void): this; removeListener(event: "close", listener: (event: Event) => void): this; /** * Emitted when an error is encountered while creating and showing the native * notification. * * @platform win32 */ on( event: "failed", listener: ( event: Event, /** * The error encountered during execution of the `show()` method. */ error: string, ) => void, ): this; once( event: "failed", listener: ( event: Event, /** * The error encountered during execution of the `show()` method. */ error: string, ) => void, ): this; addListener( event: "failed", listener: ( event: Event, /** * The error encountered during execution of the `show()` method. */ error: string, ) => void, ): this; removeListener( event: "failed", listener: ( event: Event, /** * The error encountered during execution of the `show()` method. */ error: string, ) => void, ): this; /** * Emitted when the user clicks the "Reply" button on a notification with * `hasReply: true`. * * @platform darwin */ on( event: "reply", listener: ( event: Event, /** * The string the user entered into the inline reply field. */ reply: string, ) => void, ): this; once( event: "reply", listener: ( event: Event, /** * The string the user entered into the inline reply field. */ reply: string, ) => void, ): this; addListener( event: "reply", listener: ( event: Event, /** * The string the user entered into the inline reply field. */ reply: string, ) => void, ): this; removeListener( event: "reply", listener: ( event: Event, /** * The string the user entered into the inline reply field. */ reply: string, ) => void, ): this; /** * Emitted when the notification is shown to the user. Note that this event can be * fired multiple times as a notification can be shown multiple times through the * `show()` method. */ on(event: "show", listener: (event: Event) => void): this; once(event: "show", listener: (event: Event) => void): this; addListener(event: "show", listener: (event: Event) => void): this; removeListener(event: "show", listener: (event: Event) => void): this; /** * Notification */ constructor(options?: NotificationConstructorOptions); /** * Whether or not desktop notifications are supported on the current system */ static isSupported(): boolean; /** * Dismisses the notification. */ close(): void; /** * Immediately shows the notification to the user. Unlike the web notification API, * instantiating a `new Notification()` does not immediately show it to the user. * Instead, you need to call this method before the OS will display it. * * If the notification has been shown before, this method will dismiss the * previously shown notification and create a new one with identical properties. */ show(): void; /** * A `NotificationAction[]` property representing the actions of the notification. */ actions: NotificationAction[]; /** * A `string` property representing the body of the notification. */ body: string; /** * A `string` property representing the close button text of the notification. */ closeButtonText: string; /** * A `boolean` property representing whether the notification has a reply action. */ hasReply: boolean; /** * A `string` property representing the reply placeholder of the notification. */ replyPlaceholder: string; /** * A `boolean` property representing whether the notification is silent. */ silent: boolean; /** * A `string` property representing the sound of the notification. */ sound: string; /** * A `string` property representing the subtitle of the notification. */ subtitle: string; /** * A `string` property representing the type of timeout duration for the * notification. Can be 'default' or 'never'. * * If `timeoutType` is set to 'never', the notification never expires. It stays * open until closed by the calling API or the user. * * @platform linux,win32 */ timeoutType: "default" | "never"; /** * A `string` property representing the title of the notification. */ title: string; /** * A `string` property representing the custom Toast XML of the notification. * * @platform win32 */ toastXml: string; /** * A `string` property representing the urgency level of the notification. Can be * 'normal', 'critical', or 'low'. * * Default is 'low' - see NotifyUrgency for more information. * * @platform linux */ urgency: "normal" | "critical" | "low"; } interface NotificationAction { // Docs: https://electronjs.org/docs/api/structures/notification-action /** * The label for the given action. */ text?: string; /** * The type of action, can be `button`. */ type: "button"; } interface NotificationResponse { // Docs: https://electronjs.org/docs/api/structures/notification-response /** * The identifier string of the action that the user selected. */ actionIdentifier: string; /** * The delivery date of the notification. */ date: number; /** * The unique identifier for this notification request. */ identifier: string; /** * A dictionary of custom information associated with the notification. */ userInfo: Record; /** * The text entered or chosen by the user. */ userText?: string; } interface ParentPort extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/parent-port /** * Emitted when the process receives a message. Messages received on this port will * be queued up until a handler is registered for this event. */ on(event: "message", listener: (messageEvent: MessageEvent) => void): this; once(event: "message", listener: (messageEvent: MessageEvent) => void): this; addListener(event: "message", listener: (messageEvent: MessageEvent) => void): this; removeListener(event: "message", listener: (messageEvent: MessageEvent) => void): this; /** * Sends a message from the process to its parent. */ postMessage(message: any): void; } interface PaymentDiscount { // Docs: https://electronjs.org/docs/api/structures/payment-discount /** * A string used to uniquely identify a discount offer for a product. */ identifier: string; /** * A string that identifies the key used to generate the signature. */ keyIdentifier: string; /** * A universally unique ID (UUID) value that you define. */ nonce: string; /** * A UTF-8 string representing the properties of a specific discount offer, * cryptographically signed. */ signature: string; /** * The date and time of the signature's creation in milliseconds, formatted in Unix * epoch time. */ timestamp: number; } interface Point { // Docs: https://electronjs.org/docs/api/structures/point x: number; y: number; } interface PostBody { // Docs: https://electronjs.org/docs/api/structures/post-body /** * The boundary used to separate multiple parts of the message. Only valid when * `contentType` is `multipart/form-data`. */ boundary?: string; /** * The `content-type` header used for the data. One of * `application/x-www-form-urlencoded` or `multipart/form-data`. Corresponds to the * `enctype` attribute of the submitted HTML form. */ contentType: string; /** * The post data to be sent to the new window. */ data: Array; } interface PowerMonitor extends NodeJS.EventEmitter { // Docs: https://electronjs.org/docs/api/power-monitor /** * Emitted when the system is about to lock the screen. * * @platform darwin,win32 */ on(event: "lock-screen", listener: Function): this; once(event: "lock-screen", listener: Function): this; addListener(event: "lock-screen", listener: Function): this; removeListener(event: "lock-screen", listener: Function): this; /** * Emitted when the system changes to AC power. * * @platform darwin,win32 */ on(event: "on-ac", listener: Function): this; once(event: "on-ac", listener: Function): this; addListener(event: "on-ac", listener: Function): this; removeListener(event: "on-ac", listener: Function): this; /** * Emitted when system changes to battery power. * * @platform darwin */ on(event: "on-battery", listener: Function): this; once(event: "on-battery", listener: Function): this; addListener(event: "on-battery", listener: Function): this; removeListener(event: "on-battery", listener: Function): this; /** * Emitted when system is resuming. */ on(event: "resume", listener: Function): this; once(event: "resume", listener: Function): this; addListener(event: "resume", listener: Function): this; removeListener(event: "resume", listener: Function): this; /** * Emitted when the system is about to reboot or shut down. If the event handler * invokes `e.preventDefault()`, Electron will attempt to delay system shutdown in * order for the app to exit cleanly. If `e.preventDefault()` is called, the app * should exit as soon as possible by calling something like `app.quit()`. * * @platform linux,darwin */ on(event: "shutdown", listener: Function): this; once(event: "shutdown", listener: Function): this; addListener(event: "shutdown", listener: Function): this; removeListener(event: "shutdown", listener: Function): this; /** * Notification of a change in the operating system's advertised speed limit for * CPUs, in percent. Values below 100 indicate that the system is impairing * processing power due to thermal management. * * @platform darwin,win32 */ on(event: "speed-limit-change", listener: Function): this; once(event: "speed-limit-change", listener: Function): this; addListener(event: "speed-limit-change", listener: Function): this; removeListener(event: "speed-limit-change", listener: Function): this; /** * Emitted when the system is suspending. */ on(event: "suspend", listener: Function): this; once(event: "suspend", listener: Function): this; addListener(event: "suspend", listener: Function): this; removeListener(event: "suspend", listener: Function): this; /** * Emitted when the thermal state of the system changes. Notification of a change * in the thermal status of the system, such as entering a critical temperature * range. Depending on the severity, the system might take steps to reduce said * temperature, for example, throttling the CPU or switching on the fans if * available. * * Apps may react to the new state by reducing expensive computing tasks (e.g. * video encoding), or notifying the user. The same state might be received * repeatedly. * * See * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * nce/Conceptual/power_efficiency_guidelines_osx/RespondToThermalStateChanges.html * * @platform darwin */ on(event: "thermal-state-change", listener: Function): this; once(event: "thermal-state-change", listener: Function): this; addListener(event: "thermal-state-change", listener: Function): this; removeListener(event: "thermal-state-change", listener: Function): this; /** * Emitted as soon as the systems screen is unlocked. * * @platform darwin,win32 */ on(event: "unlock-screen", listener: Function): this; once(event: "unlock-screen", listener: Function): this; addListener(event: "unlock-screen", listener: Function): this; removeListener(event: "unlock-screen", listener: Function): this; /** * Emitted when a login session is activated. See documentation for more * information. * * @platform darwin */ on(event: "user-did-become-active", listener: Function): this; once(event: "user-did-become-active", listener: Function): this; addListener(event: "user-did-become-active", listener: Function): this; removeListener(event: "user-did-become-active", listener: Function): this; /** * Emitted when a login session is deactivated. See documentation for more * information. * * @platform darwin */ on(event: "user-did-resign-active", listener: Function): this; once(event: "user-did-resign-active", listener: Function): this; addListener(event: "user-did-resign-active", listener: Function): this; removeListener(event: "user-did-resign-active", listener: Function): this; /** * The system's current thermal state. Can be `unknown`, `nominal`, `fair`, * `serious`, or `critical`. * * @platform darwin */ getCurrentThermalState(): "unknown" | "nominal" | "fair" | "serious" | "critical"; /** * The system's current idle state. Can be `active`, `idle`, `locked` or `unknown`. * * Calculate the system idle state. `idleThreshold` is the amount of time (in * seconds) before considered idle. `locked` is available on supported systems * only. */ getSystemIdleState(idleThreshold: number): "active" | "idle" | "locked" | "unknown"; /** * Idle time in seconds * * Calculate system idle time in seconds. */ getSystemIdleTime(): number; /** * Whether the system is on battery power. * * To monitor for changes in this property, use the `on-battery` and `on-ac` * events. */ isOnBatteryPower(): boolean; /** * A `boolean` property. True if the system is on battery power. * * See `powerMonitor.isOnBatteryPower()`. */ onBatteryPower: boolean; } interface PowerSaveBlocker { // Docs: https://electronjs.org/docs/api/power-save-blocker /** * Whether the corresponding `powerSaveBlocker` has started. */ isStarted(id: number): boolean; /** * The blocker ID that is assigned to this power blocker. * * Starts preventing the system from entering lower-power mode. Returns an integer * identifying the power save blocker. * * **Note:** `prevent-display-sleep` has higher precedence over * `prevent-app-suspension`. Only the highest precedence type takes effect. In * other words, `prevent-display-sleep` always takes precedence over * `prevent-app-suspension`. * * For example, an API calling A requests for `prevent-app-suspension`, and another * calling B requests for `prevent-display-sleep`. `prevent-display-sleep` will be * used until B stops its request. After that, `prevent-app-suspension` is used. */ start(type: "prevent-app-suspension" | "prevent-display-sleep"): number; /** * Stops the specified power save blocker. */ stop(id: number): void; } interface PrinterInfo { // Docs: https://electronjs.org/docs/api/structures/printer-info /** * a longer description of the printer's type. */ description: string; /** * the name of the printer as shown in Print Preview. */ displayName: string; /** * whether or not a given printer is set as the default printer on the OS. */ isDefault: boolean; /** * the name of the printer as understood by the OS. */ name: string; /** * an object containing a variable number of platform-specific printer information. */ options: Options; /** * the current status of the printer. */ status: number; } interface ProcessMemoryInfo { // Docs: https://electronjs.org/docs/api/structures/process-memory-info /** * The amount of memory not shared by other processes, such as JS heap or HTML * content in Kilobytes. */ private: number; /** * The amount of memory currently pinned to actual physical RAM in Kilobytes. * * @platform linux,win32 */ residentSet: number; /** * The amount of memory shared between processes, typically memory consumed by the * Electron code itself in Kilobytes. */ shared: number; } interface ProcessMetric { // Docs: https://electronjs.org/docs/api/structures/process-metric /** * CPU usage of the process. */ cpu: CPUUsage; /** * Creation time for this process. The time is represented as number of * milliseconds since epoch. Since the `pid` can be reused after a process dies, it * is useful to use both the `pid` and the `creationTime` to uniquely identify a * process. */ creationTime: number; /** * One of the following values: * * @platform win32 */ integrityLevel?: "untrusted" | "low" | "medium" | "high" | "unknown"; /** * Memory information for the process. */ memory: MemoryInfo; /** * The name of the process. Examples for utility: `Audio Service`, `Content * Decryption Module Service`, `Network Service`, `Video Capture`, etc. */ name?: string; /** * Process id of the process. */ pid: number; /** * Whether the process is sandboxed on OS level. * * @platform darwin,win32 */ sandboxed?: boolean; /** * The non-localized name of the process. */ serviceName?: string; /** * Process type. One of the following values: */ type: "Browser" | "Tab" | "Utility" | "Zygote" | "Sandbox helper" | "GPU" | "Pepper Plugin" | "Pepper Plugin Broker" | "Unknown"; } interface Product { // Docs: https://electronjs.org/docs/api/structures/product /** * The total size of the content, in bytes. */ contentLengths: number[]; /** * A string that identifies the version of the content. */ contentVersion: string; /** * 3 character code presenting a product's currency based on the ISO 4217 standard. */ currencyCode: string; /** * An array of discount offers */ discounts: ProductDiscount[]; /** * The total size of the content, in bytes. */ downloadContentLengths: number[]; /** * A string that identifies the version of the content. */ downloadContentVersion: string; /** * The locale formatted price of the product. */ formattedPrice: string; /** * The object containing introductory price information for the product. available * for the product. */ introductoryPrice?: ProductDiscount; /** * A boolean value that indicates whether the App Store has downloadable content * for this product. `true` if at least one file has been associated with the * product. */ isDownloadable: boolean; /** * A description of the product. */ localizedDescription: string; /** * The name of the product. */ localizedTitle: string; /** * The cost of the product in the local currency. */ price: number; /** * The string that identifies the product to the Apple App Store. */ productIdentifier: string; /** * The identifier of the subscription group to which the subscription belongs. */ subscriptionGroupIdentifier: string; /** * The period details for products that are subscriptions. */ subscriptionPeriod?: ProductSubscriptionPeriod; } interface ProductDiscount { // Docs: https://electronjs.org/docs/api/structures/product-discount /** * A string used to uniquely identify a discount offer for a product. */ identifier: string; /** * An integer that indicates the number of periods the product discount is * available. */ numberOfPeriods: number; /** * The payment mode for this product discount. Can be `payAsYouGo`, `payUpFront`, * or `freeTrial`. */ paymentMode: "payAsYouGo" | "payUpFront" | "freeTrial"; /** * The discount price of the product in the local currency. */ price: number; /** * The locale used to format the discount price of the product. */ priceLocale: string; /** * An object that defines the period for the product discount. */ subscriptionPeriod?: ProductSubscriptionPeriod; /** * The type of discount offer. */ type: number; } interface ProductSubscriptionPeriod { // Docs: https://electronjs.org/docs/api/structures/product-subscription-period /** * The number of units per subscription period. */ numberOfUnits: number; /** * The increment of time that a subscription period is specified in. Can be `day`, * `week`, `month`, `year`. */ unit: "day" | "week" | "month" | "year"; } interface Protocol { // Docs: https://electronjs.org/docs/api/protocol /** * Register a protocol handler for `scheme`. Requests made to URLs with this scheme * will delegate to this handler to determine what response should be sent. * * Either a `Response` or a `Promise` can be returned. * * Example: * * See the MDN docs for `Request` and `Response` for more details. */ handle(scheme: string, handler: (request: GlobalRequest) => GlobalResponse | Promise): void; /** * Whether the protocol was successfully intercepted * * Intercepts `scheme` protocol and uses `handler` as the protocol's new handler * which sends a `Buffer` as a response. * * @deprecated */ interceptBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: Buffer | ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully intercepted * * Intercepts `scheme` protocol and uses `handler` as the protocol's new handler * which sends a file as a response. * * @deprecated */ interceptFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: string | ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully intercepted * * Intercepts `scheme` protocol and uses `handler` as the protocol's new handler * which sends a new HTTP request as a response. * * @deprecated */ interceptHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully intercepted * * Same as `protocol.registerStreamProtocol`, except that it replaces an existing * protocol handler. * * @deprecated */ interceptStreamProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: NodeJS.ReadableStream | ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully intercepted * * Intercepts `scheme` protocol and uses `handler` as the protocol's new handler * which sends a `string` as a response. * * @deprecated */ interceptStringProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: string | ProtocolResponse) => void) => void): boolean; /** * Whether `scheme` is already handled. */ isProtocolHandled(scheme: string): boolean; /** * Whether `scheme` is already intercepted. * * @deprecated */ isProtocolIntercepted(scheme: string): boolean; /** * Whether `scheme` is already registered. * * @deprecated */ isProtocolRegistered(scheme: string): boolean; /** * Whether the protocol was successfully registered * * Registers a protocol of `scheme` that will send a `Buffer` as a response. * * The usage is the same with `registerFileProtocol`, except that the `callback` * should be called with either a `Buffer` object or an object that has the `data` * property. * * Example: * * @deprecated */ registerBufferProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: Buffer | ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully registered * * Registers a protocol of `scheme` that will send a file as the response. The * `handler` will be called with `request` and `callback` where `request` is an * incoming request for the `scheme`. * * To handle the `request`, the `callback` should be called with either the file's * path or an object that has a `path` property, e.g. `callback(filePath)` or * `callback({ path: filePath })`. The `filePath` must be an absolute path. * * By default the `scheme` is treated like `http:`, which is parsed differently * from protocols that follow the "generic URI syntax" like `file:`. * * @deprecated */ registerFileProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: string | ProtocolResponse) => void) => void): boolean; /** * Whether the protocol was successfully registered * * Registers a protocol of `scheme` that will send an HTTP request as a response. * * The usage is the same with `registerFileProtocol`, except that the `callback` * should be called with an object that has the `url` property. * * @deprecated */ registerHttpProtocol(scheme: string, handler: (request: ProtocolRequest, callback: (response: ProtocolResponse) => void) => void): boolean; /** * **Note:** This method can only be used before the `ready` event of the `app` * module gets emitted and can be called only once. * * Registers the `scheme` as standard, secure, bypasses content security policy for * resources, allows registering ServiceWorker, supports fetch API, and streaming * video/audio. Specify a privilege with the value of `true` to enable the * capability. * * An example of registering a privileged scheme, that bypasses Content Security * Policy: * * A standard scheme adheres to what RFC 3986 calls generic URI syntax. For example * `http` and `https` are standard schemes, while `file` is not. * * Registering a scheme as standard allows relative and absolute resources to be * resolved correctly when served. Otherwise the scheme will behave like the `file` * protocol, but without the ability to resolve relative URLs. * * For example when you load following page with custom protocol without * registering it as standard scheme, the image will not be loaded because * non-standard schemes can not recognize relative URLs: * * Registering a scheme as standard will allow access to files through the * FileSystem API. Otherwise the renderer will throw a security error for the * scheme. * * By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, * cookies) are disabled for non standard schemes. So in general if you want to * register a custom protocol to replace the `http` protocol, you have to register * it as a standard scheme. * * Protocols that use streams (http and stream protocols) should set `stream: * true`. The `