refactor: convert more files to typescript (#16820)

This commit is contained in:
Samuel Attard 2019-02-12 06:22:33 -08:00 коммит произвёл John Kleinschmidt
Родитель cfbdc40814
Коммит 01c442de64
16 изменённых файлов: 169 добавлений и 90 удалений

Просмотреть файл

@ -72,6 +72,9 @@ npm_action("build_electron_definitions") {
npm_action("atom_browserify_sandbox") {
script = "browserify"
deps = [
":build_electron_definitions",
]
inputs = [
# FIXME(zcbenz): The dependencies of these files are not listed here, so
@ -79,6 +82,8 @@ npm_action("atom_browserify_sandbox") {
# Use a script to generate all dependencies and put them here.
"lib/sandboxed_renderer/init.js",
"lib/sandboxed_renderer/api/exports/electron.js",
"tsconfig.electron.json",
"tsconfig.json",
]
outputs = [
@ -91,6 +96,12 @@ npm_action("atom_browserify_sandbox") {
"./lib/sandboxed_renderer/api/exports/electron.js:electron",
"-t",
"aliasify",
"-p",
"[",
"tsify",
"-p",
"tsconfig.electron.json",
"]",
"-o",
rebase_path(outputs[0]),
]
@ -98,9 +109,14 @@ npm_action("atom_browserify_sandbox") {
npm_action("atom_browserify_isolated") {
script = "browserify"
deps = [
":build_electron_definitions",
]
inputs = [
"lib/isolated_renderer/init.js",
"tsconfig.electron.json",
"tsconfig.json",
]
outputs = [
@ -111,6 +127,12 @@ npm_action("atom_browserify_isolated") {
"lib/isolated_renderer/init.js",
"-t",
"aliasify",
"-p",
"[",
"tsify",
"-p",
"tsconfig.electron.json",
"]",
"-o",
rebase_path(outputs[0]),
]

Просмотреть файл

@ -14,7 +14,7 @@ See [`Menu`](menu.md) for examples.
* `menuItem` MenuItem
* `browserWindow` [BrowserWindow](browser-window.md)
* `event` Event
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteandmatchstyle`, `delete`, `selectall`, `reload`, `forcereload`, `toggledevtools`, `resetzoom`, `zoomin`, `zoomout`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideothers`, `unhide`, `quit`, `startspeaking`, `stopspeaking`, `close`, `minimize`, `zoom` or `front` - Define the action of the menu item, when specified the
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteandmatchstyle`, `delete`, `selectall`, `reload`, `forcereload`, `toggledevtools`, `resetzoom`, `zoomin`, `zoomout`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideothers`, `unhide`, `quit`, `startspeaking`, `stopspeaking`, `close`, `minimize`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu` or `windowMenu` - Define the action of the menu item, when specified the
`click` property will be ignored. See [roles](#roles).
* `type` String (optional) - Can be `normal`, `separator`, `submenu`, `checkbox` or
`radio`.

Просмотреть файл

@ -24,7 +24,7 @@ filenames = {
"lib/browser/api/notification.js",
"lib/browser/api/power-monitor.js",
"lib/browser/api/power-save-blocker.js",
"lib/browser/api/protocol.js",
"lib/browser/api/protocol.ts",
"lib/browser/api/screen.js",
"lib/browser/api/session.js",
"lib/browser/api/system-preferences.js",
@ -37,7 +37,7 @@ filenames = {
"lib/browser/chrome-devtools.js",
"lib/browser/chrome-extension.js",
"lib/browser/crash-reporter-init.js",
"lib/browser/default-menu.js",
"lib/browser/default-menu.ts",
"lib/browser/guest-view-manager.js",
"lib/browser/guest-window-manager.js",
"lib/browser/init.ts",
@ -54,13 +54,13 @@ filenames = {
"lib/common/api/module-list.js",
"lib/common/api/native-image.js",
"lib/common/api/shell.js",
"lib/common/atom-binding-setup.js",
"lib/common/atom-binding-setup.ts",
"lib/common/buffer-utils.js",
"lib/common/crash-reporter.js",
"lib/common/error-utils.js",
"lib/common/init.js",
"lib/common/init.ts",
"lib/common/parse-features-string.js",
"lib/common/reset-search-paths.js",
"lib/common/reset-search-paths.ts",
"lib/common/web-view-methods.js",
"lib/renderer/callbacks-registry.js",
"lib/renderer/chrome-api.js",

Просмотреть файл

@ -10,6 +10,11 @@ common.defineProperties(exports)
for (const module of moduleList) {
Object.defineProperty(exports, module.name, {
enumerable: !module.private,
get: common.memoizedGetter(() => require(`@electron/internal/browser/api/${module.file}.js`))
get: common.memoizedGetter(() => {
const value = require(`@electron/internal/browser/api/${module.file}.js`)
// Handle Typescript modules with an "export default X" statement
if (value.__esModule) return value.default
return value
})
})
}

Просмотреть файл

@ -1,29 +1,29 @@
'use strict'
const { app, session } = require('electron')
import { app, session } from 'electron'
// Global protocol APIs.
module.exports = process.atomBinding('protocol')
const protocol = process.atomBinding('protocol')
// Fallback protocol APIs of default session.
Object.setPrototypeOf(module.exports, new Proxy({}, {
Object.setPrototypeOf(protocol, new Proxy({}, {
get (target, property) {
if (!app.isReady()) return
const protocol = session.defaultSession.protocol
const protocol = session.defaultSession!.protocol
if (!Object.getPrototypeOf(protocol).hasOwnProperty(property)) return
// Returning a native function directly would throw error.
return (...args) => protocol[property](...args)
return (...args: any[]) => (protocol[property as keyof Electron.Protocol] as Function)(...args)
},
ownKeys () {
if (!app.isReady()) return []
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession.protocol))
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession!.protocol))
},
getOwnPropertyDescriptor (target) {
return { configurable: true, enumerable: true }
}
}))
export default protocol

Просмотреть файл

@ -1,14 +1,13 @@
'use strict'
import { shell, Menu } from 'electron'
const { shell, Menu } = require('electron')
const v8Util = process.atomBinding('v8_util')
const isMac = process.platform === 'darwin'
const setDefaultApplicationMenu = () => {
if (v8Util.getHiddenValue(global, 'applicationMenuSet')) return
export const setDefaultApplicationMenu = () => {
if (v8Util.getHiddenValue<boolean>(global, 'applicationMenuSet')) return
const helpMenu = {
const helpMenu: Electron.MenuItemConstructorOptions = {
role: 'help',
submenu: [
{
@ -40,8 +39,9 @@ const setDefaultApplicationMenu = () => {
]
}
const template = [
...(isMac ? [{ role: 'appMenu' }] : []),
const macAppMenu: Electron.MenuItemConstructorOptions = { role: 'appMenu' }
const template: Electron.MenuItemConstructorOptions[] = [
...(isMac ? [macAppMenu] : []),
{ role: 'fileMenu' },
{ role: 'editMenu' },
{ role: 'viewMenu' },
@ -52,7 +52,3 @@ const setDefaultApplicationMenu = () => {
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
}
module.exports = {
setDefaultApplicationMenu
}

Просмотреть файл

@ -49,10 +49,15 @@ process.on('uncaughtException', function (error) {
}
// Show error in GUI.
const dialog = require('electron').dialog
const stack = error.stack ? error.stack : `${error.name}: ${error.message}`
const message = 'Uncaught Exception:\n' + stack
dialog.showErrorBox('A JavaScript error occurred in the main process', message)
// We can't import { dialog } at the top of this file as this file is
// responsible for setting up the require hook for the "electron" module
// so we import it inside the handler down here
import('electron')
.then(({ dialog }) => {
const stack = error.stack ? error.stack : `${error.name}: ${error.message}`
const message = 'Uncaught Exception:\n' + stack
dialog.showErrorBox('A JavaScript error occurred in the main process', message)
})
})
// Emit 'exit' event on quit.
@ -195,10 +200,13 @@ app.on('window-all-closed', () => {
}
})
const { setDefaultApplicationMenu } = require('@electron/internal/browser/default-menu')
// Create default menu.
app.once('ready', setDefaultApplicationMenu)
Promise.all([
import('@electron/internal/browser/default-menu'),
app.whenReady
]).then(([{ setDefaultApplicationMenu }]) => {
// Create default menu
setDefaultApplicationMenu()
})
if (packagePath) {
// Finally load app's main.js and transfer control to C++.

Просмотреть файл

@ -1,7 +1,5 @@
'use strict'
module.exports = function atomBindingSetup (binding, processType) {
return function atomBinding (name) {
export function atomBindingSetup (binding: typeof process['binding'], processType: typeof process['type']): typeof process['atomBinding'] {
return function atomBinding (name: string) {
try {
return binding(`atom_${processType}_${name}`)
} catch (error) {

Просмотреть файл

@ -1,9 +1,11 @@
'use strict'
import * as timers from 'timers'
import * as util from 'util'
const timers = require('timers')
const util = require('util')
import { atomBindingSetup } from '@electron/internal/common/atom-binding-setup'
process.atomBinding = require('@electron/internal/common/atom-binding-setup')(process.binding, process.type)
process.atomBinding = atomBindingSetup(process.binding, process.type)
type AnyFn = (...args: any[]) => any
// setImmediate and process.nextTick makes use of uv_check and uv_prepare to
// run the callbacks, however since we only run uv loop on requests, the
@ -11,19 +13,25 @@ process.atomBinding = require('@electron/internal/common/atom-binding-setup')(pr
// which would delay the callbacks for arbitrary long time. So we should
// initiatively activate the uv loop once setImmediate and process.nextTick is
// called.
const wrapWithActivateUvLoop = function (func) {
const wrapWithActivateUvLoop = function <T extends AnyFn> (func: T): T {
return wrap(func, function (func) {
return function () {
return function (this: any, ...args: any[]) {
process.activateUvLoop()
return func.apply(this, arguments)
return func.apply(this, args)
}
})
}) as T
}
function wrap (func, wrapper) {
/**
* Casts to any below for func are due to Typescript not supporting symbols
* in index signatures
*
* Refs: https://github.com/Microsoft/TypeScript/issues/1863
*/
function wrap <T extends AnyFn> (func: T, wrapper: (fn: AnyFn) => T) {
const wrapped = wrapper(func)
if (func[util.promisify.custom]) {
wrapped[util.promisify.custom] = wrapper(func[util.promisify.custom])
if ((func as any)[util.promisify.custom]) {
(wrapped as any)[util.promisify.custom] = wrapper((func as any)[util.promisify.custom])
}
return wrapped
}
@ -47,7 +55,11 @@ if (process.platform === 'win32') {
const { Readable } = require('stream')
const stdin = new Readable()
stdin.push(null)
process.__defineGetter__('stdin', function () {
return stdin
Object.defineProperty(process, 'stdin', {
configurable: false,
enumerable: true,
get () {
return stdin
}
})
}

Просмотреть файл

@ -1,6 +1,5 @@
'use strict'
import * as path from 'path'
const path = require('path')
const Module = require('module')
// Clear Node's global search paths.
@ -8,13 +7,13 @@ Module.globalPaths.length = 0
// Clear current and parent(init.js)'s search paths.
module.paths = []
module.parent.paths = []
module.parent!.paths = []
// Prevent Node from adding paths outside this app to search paths.
const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep
const originalNodeModulePaths = Module._nodeModulePaths
Module._nodeModulePaths = function (from) {
const paths = originalNodeModulePaths(from)
Module._nodeModulePaths = function (from: string) {
const paths: string[] = originalNodeModulePaths(from)
const fromPath = path.resolve(from) + path.sep
// If "from" is outside the app then we do nothing.
if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
@ -31,9 +30,9 @@ const INTERNAL_MODULE_PREFIX = '@electron/internal/'
// Patch Module._resolveFilename to always require the Electron API when
// require('electron') is done.
const electronPath = path.join(__dirname, '..', process.type, 'api', 'exports', 'electron.js')
const electronPath = path.join(__dirname, '..', process.type!, 'api', 'exports', 'electron.js')
const originalResolveFilename = Module._resolveFilename
Module._resolveFilename = function (request, parent, isMain) {
Module._resolveFilename = function (request: string, parent: NodeModule, isMain: boolean) {
if (request === 'electron') {
return electronPath
} else if (request.startsWith(INTERNAL_MODULE_PREFIX) && request.length > INTERNAL_MODULE_PREFIX.length) {

Просмотреть файл

@ -2,7 +2,7 @@
/* global nodeProcess, isolatedWorld */
const atomBinding = require('@electron/internal/common/atom-binding-setup')(nodeProcess.binding, 'renderer')
const atomBinding = require('@electron/internal/common/atom-binding-setup').atomBindingSetup(nodeProcess.binding, 'renderer')
const v8Util = atomBinding('v8_util')

Просмотреть файл

@ -5,7 +5,7 @@
const events = require('events')
const { EventEmitter } = events
process.atomBinding = require('@electron/internal/common/atom-binding-setup')(binding.get, 'renderer')
process.atomBinding = require('@electron/internal/common/atom-binding-setup').atomBindingSetup(binding.get, 'renderer')
const v8Util = process.atomBinding('v8_util')
// Expose browserify Buffer as a hidden value. This is used by C++ code to

45
package-lock.json сгенерированный
Просмотреть файл

@ -382,6 +382,12 @@
"integrity": "sha512-/FQM1EDkTsf63Ub2C6O7GuYFDsSXUwsaZDurV0np41ocwq0jthUAYCmhBX9f+KwlaCgIuWyr/4WlUQUBfKfZog==",
"dev": true
},
"any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
"integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=",
"dev": true
},
"anymatch": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz",
@ -4449,8 +4455,7 @@
"version": "2.1.1",
"resolved": false,
"integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
"dev": true,
"optional": true
"dev": true
},
"aproba": {
"version": "1.2.0",
@ -4915,8 +4920,7 @@
"version": "5.1.1",
"resolved": false,
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==",
"dev": true,
"optional": true
"dev": true
},
"safer-buffer": {
"version": "2.1.2",
@ -4980,7 +4984,6 @@
"resolved": false,
"integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
"dev": true,
"optional": true,
"requires": {
"ansi-regex": "^2.0.0"
}
@ -5029,15 +5032,13 @@
"version": "1.0.2",
"resolved": false,
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
"dev": true,
"optional": true
"dev": true
},
"yallist": {
"version": "3.0.2",
"resolved": false,
"integrity": "sha1-hFK0u36Dx8GI2AQcGoN8dz1ti7k=",
"dev": true,
"optional": true
"dev": true
}
}
},
@ -12312,6 +12313,32 @@
"integrity": "sha512-FHkoUZvG6Egrv9XZAyYGKEyb1JMsFphgPjoczkZC2y6W93U1jswcVURB8MUvtsahEPEVACyxD47JAL63vF4JsQ==",
"dev": true
},
"tsconfig": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-5.0.3.tgz",
"integrity": "sha1-X0J45wGACWeo/Dg/0ZZIh48qbjo=",
"dev": true,
"requires": {
"any-promise": "^1.3.0",
"parse-json": "^2.2.0",
"strip-bom": "^2.0.0",
"strip-json-comments": "^2.0.0"
}
},
"tsify": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/tsify/-/tsify-4.0.1.tgz",
"integrity": "sha512-ClznEI+pmwY5wmD0J7HCSVERwkD+l71ch3Dqyod2JuQLEsFaiNDI+vPjaGadsuVFVvmzgoI7HghrBtWsSmCDHQ==",
"dev": true,
"requires": {
"convert-source-map": "^1.1.0",
"fs.realpath": "^1.0.0",
"object-assign": "^4.1.0",
"semver": "^5.6.0",
"through2": "^2.0.0",
"tsconfig": "^5.0.3"
}
},
"tslib": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz",

Просмотреть файл

@ -36,6 +36,7 @@
"standard-markdown": "^5.0.0",
"sumchecker": "^2.0.2",
"temp": "^0.8.3",
"tsify": "^4.0.1",
"typescript": "~3.1.1",
"typescript-eslint-parser": "^21.0.0"
},

Просмотреть файл

@ -1,23 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"lib": [
"es2017",
"dom",
"dom.iterable"
],
"sourceMap": true,
"experimentalDecorators": false,
"strict": true,
"baseUrl": ".",
"allowJs": true,
"outDir": "ts-gen",
"paths": {
"@electron-internal/*": ["lib"]
}
},
"exclude": [
"electron.d.ts"
]
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"lib": [
"es2017",
"dom",
"dom.iterable"
],
"sourceMap": true,
"experimentalDecorators": false,
"strict": true,
"baseUrl": ".",
"allowJs": true,
"outDir": "ts-gen",
"paths": {
"@electron/internal/*": ["lib/*"]
}
},
"exclude": [
"electron.d.ts"
],
}

11
typings/internal-ambient.d.ts поставляемый
Просмотреть файл

@ -9,9 +9,20 @@ declare namespace NodeJS {
isTtsEnabled(): boolean;
isPrintingEnabled(): boolean;
}
interface V8UtilBinding {
getHiddenValue<T>(obj: any, key: string): T;
setHiddenValue<T>(obj: any, key: string, value: T): void;
}
interface Process {
/**
* DO NOT USE DIRECTLY, USE process.atomBinding
*/
binding(name: string): any;
atomBinding(name: string): any;
atomBinding(name: 'features'): FeaturesBinding;
atomBinding(name: 'v8_util'): V8UtilBinding;
log: NodeJS.WriteStream['write'];
activateUvLoop(): void;
}
}