refactor: replace .forEach() with for-of (#39691)

* refactor: replace `.forEach()` with `for-of`

* refactor docs/fiddles/features/web-hid/renderer.js
This commit is contained in:
Milan Burda 2023-08-31 16:36:43 +02:00 committed by GitHub
parent 7858921a1f
commit 0b0707145b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 144 additions and 132 deletions

View file

@ -1,19 +1,10 @@
async function testIt () { function formatDevices (devices) {
const grantedDevices = await navigator.hid.getDevices() return devices.map(device => device.productName).join('<hr>')
let grantedDeviceList = '' }
grantedDevices.forEach(device => {
grantedDeviceList += `<hr>${device.productName}</hr>`
})
document.getElementById('granted-devices').innerHTML = grantedDeviceList
const grantedDevices2 = await navigator.hid.requestDevice({
filters: []
})
grantedDeviceList = '' async function testIt () {
grantedDevices2.forEach(device => { document.getElementById('granted-devices').innerHTML = formatDevices(await navigator.hid.getDevices())
grantedDeviceList += `<hr>${device.productName}</hr>` document.getElementById('granted-devices2').innerHTML = formatDevices(await navigator.hid.requestDevice({ filters: [] }))
})
document.getElementById('granted-devices2').innerHTML = grantedDeviceList
} }
document.getElementById('clickme').addEventListener('click', testIt) document.getElementById('clickme').addEventListener('click', testIt)

View file

@ -7,9 +7,9 @@ async function testIt () {
const grantedDevices = await navigator.usb.getDevices() const grantedDevices = await navigator.usb.getDevices()
let grantedDeviceList = '' let grantedDeviceList = ''
if (grantedDevices.length > 0) { if (grantedDevices.length > 0) {
grantedDevices.forEach(device => { for (const device of grantedDevices) {
grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>` grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
}) }
} else { } else {
grantedDeviceList = noDevicesFoundMsg grantedDeviceList = noDevicesFoundMsg
} }

View file

@ -68,9 +68,9 @@ const template = [
// on reload, start fresh and close any old // on reload, start fresh and close any old
// open secondary windows // open secondary windows
if (focusedWindow.id === 1) { if (focusedWindow.id === 1) {
BrowserWindow.getAllWindows().forEach(win => { for (const win of BrowserWindow.getAllWindows()) {
if (win.id > 1) win.close() if (win.id > 1) win.close()
}) }
} }
focusedWindow.reload() focusedWindow.reload()
} }
@ -209,15 +209,15 @@ function findReopenMenuItem () {
if (!menu) return if (!menu) return
let reopenMenuItem let reopenMenuItem
menu.items.forEach(item => { for (const item of menu.items) {
if (item.submenu) { if (item.submenu) {
item.submenu.items.forEach(item => { for (const subitem of item.submenu.items) {
if (item.key === 'reopenMenuItem') { if (subitem.key === 'reopenMenuItem') {
reopenMenuItem = item reopenMenuItem = subitem
} }
}) }
} }
}) }
return reopenMenuItem return reopenMenuItem
} }

View file

@ -167,11 +167,11 @@ const supportBinaries = await msiCreator.create()
// 🆕 Step 2a: optionally sign support binaries if you // 🆕 Step 2a: optionally sign support binaries if you
// sign you binaries as part of of your packaging script // sign you binaries as part of of your packaging script
supportBinaries.forEach(async (binary) => { for (const binary of supportBinaries) {
// Binaries are the new stub executable and optionally // Binaries are the new stub executable and optionally
// the Squirrel auto updater. // the Squirrel auto updater.
await signFile(binary) await signFile(binary)
}) }
// Step 3: Compile the template to a .msi file // Step 3: Compile the template to a .msi file
await msiCreator.compile() await msiCreator.compile()

View file

@ -46,7 +46,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => {
} }
// Check each transaction. // Check each transaction.
transactions.forEach((transaction) => { for (const transaction of transactions) {
const payment = transaction.payment const payment = transaction.payment
switch (transaction.transactionState) { switch (transaction.transactionState) {
@ -95,7 +95,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => {
default: default:
break break
} }
}) }
}) })
// Check if the user is allowed to make in-app purchase. // Check if the user is allowed to make in-app purchase.
@ -112,9 +112,9 @@ inAppPurchase.getProducts(PRODUCT_IDS).then(products => {
} }
// Display the name and price of each product. // Display the name and price of each product.
products.forEach(product => { for (const product of products) {
console.log(`The price of ${product.localizedTitle} is ${product.formattedPrice}.`) console.log(`The price of ${product.localizedTitle} is ${product.formattedPrice}.`)
}) }
// Ask the user which product they want to purchase. // Ask the user which product they want to purchase.
const selectedProduct = products[0] const selectedProduct = products[0]

View file

@ -57,12 +57,17 @@ function sortTopologically<T> (originalOrder: T[], edgesById: Map<T, T[]>) {
marked.add(mark); marked.add(mark);
const edges = edgesById.get(mark); const edges = edgesById.get(mark);
if (edges != null) { if (edges != null) {
edges.forEach(visit); for (const edge of edges) {
visit(edge);
}
} }
sorted.push(mark); sorted.push(mark);
}; };
originalOrder.forEach(visit); for (const edge of originalOrder) {
visit(edge);
}
return sorted; return sorted;
} }
@ -98,24 +103,24 @@ function sortItemsInGroup<T> (group: {before?: T[], after?: T[], id?: T}[]) {
const edges = new Map(); const edges = new Map();
const idToIndex = new Map(group.map((item, i) => [item.id, i])); const idToIndex = new Map(group.map((item, i) => [item.id, i]));
group.forEach((item, i) => { for (const [i, item] of group.entries()) {
if (item.before) { if (item.before) {
item.before.forEach(toID => { for (const toID of item.before) {
const to = idToIndex.get(toID); const to = idToIndex.get(toID);
if (to != null) { if (to != null) {
pushOntoMultiMap(edges, to, i); pushOntoMultiMap(edges, to, i);
} }
}); }
} }
if (item.after) { if (item.after) {
item.after.forEach(toID => { for (const toID of item.after) {
const to = idToIndex.get(toID); const to = idToIndex.get(toID);
if (to != null) { if (to != null) {
pushOntoMultiMap(edges, i, to); pushOntoMultiMap(edges, i, to);
} }
}); }
} }
}); }
const sortedNodes = sortTopologically(originalOrder, edges); const sortedNodes = sortTopologically(originalOrder, edges);
return sortedNodes.map(i => group[i]); return sortedNodes.map(i => group[i]);

View file

@ -153,9 +153,9 @@ Menu.prototype.insert = function (pos, item) {
Menu.prototype._callMenuWillShow = function () { Menu.prototype._callMenuWillShow = function () {
if (this.delegate) this.delegate.menuWillShow(this); if (this.delegate) this.delegate.menuWillShow(this);
this.items.forEach(item => { for (const item of this.items) {
if (item.submenu) item.submenu._callMenuWillShow(); if (item.submenu) item.submenu._callMenuWillShow();
}); }
}; };
/* Static Methods */ /* Static Methods */
@ -196,13 +196,13 @@ Menu.buildFromTemplate = function (template) {
const filtered = removeExtraSeparators(sorted); const filtered = removeExtraSeparators(sorted);
const menu = new Menu(); const menu = new Menu();
filtered.forEach(item => { for (const item of filtered) {
if (item instanceof MenuItem) { if (item instanceof MenuItem) {
menu.append(item); menu.append(item);
} else { } else {
menu.append(new MenuItem(item)); menu.append(new MenuItem(item));
} }
}); }
return menu; return menu;
}; };
@ -280,9 +280,9 @@ function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
enumerable: true, enumerable: true,
get: () => checked.get(item), get: () => checked.get(item),
set: () => { set: () => {
this.groupsMap[item.groupId].forEach(other => { for (const other of this.groupsMap[item.groupId]) {
if (other !== item) checked.set(other, false); if (other !== item) checked.set(other, false);
}); }
checked.set(item, true); checked.set(item, true);
} }
}); });

View file

@ -70,9 +70,9 @@ class IncomingMessage extends Readable {
get rawHeaders () { get rawHeaders () {
const rawHeadersArr: string[] = []; const rawHeadersArr: string[] = [];
const { rawHeaders } = this._responseHead; const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => { for (const header of rawHeaders) {
rawHeadersArr.push(header.key, header.value); rawHeadersArr.push(header.key, header.value);
}); }
return rawHeadersArr; return rawHeadersArr;
} }

View file

@ -98,7 +98,9 @@ export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypa
r.on('response', (resp: IncomingMessage) => { r.on('response', (resp: IncomingMessage) => {
if (locallyAborted) return; if (locallyAborted) return;
const headers = new Headers(); const headers = new Headers();
for (const [k, v] of Object.entries(resp.headers)) { headers.set(k, Array.isArray(v) ? v.join(', ') : v); } for (const [k, v] of Object.entries(resp.headers)) {
headers.set(k, Array.isArray(v) ? v.join(', ') : v);
}
const nullBodyStatus = [101, 204, 205, 304]; const nullBodyStatus = [101, 204, 205, 304];
const body = nullBodyStatus.includes(resp.statusCode) || req.method === 'HEAD' ? null : Readable.toWeb(resp as unknown as Readable) as ReadableStream; const body = nullBodyStatus.includes(resp.statusCode) || req.method === 'HEAD' ? null : Readable.toWeb(resp as unknown as Readable) as ReadableStream;
const rResp = new Response(body, { const rResp = new Response(body, {

View file

@ -323,13 +323,15 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
this.items.set(item.id, item); this.items.set(item.id, item);
item.on('change', this.changeListener); item.on('change', this.changeListener);
if (item.child instanceof TouchBar) { if (item.child instanceof TouchBar) {
item.child.orderedItems.forEach(registerItem); for (const child of item.child.orderedItems) {
registerItem(child);
}
} }
}; };
let hasOtherItemsProxy = false; let hasOtherItemsProxy = false;
const idSet = new Set(); const idSet = new Set();
items.forEach((item) => { for (const item of items) {
if (!(item instanceof TouchBarItem)) { if (!(item instanceof TouchBarItem)) {
throw new TypeError('Each item must be an instance of TouchBarItem'); throw new TypeError('Each item must be an instance of TouchBarItem');
} }
@ -347,7 +349,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
} else { } else {
throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar'); throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
} }
}); }
// register in separate loop after all items are validated // register in separate loop after all items are validated
for (const item of (items as TouchBarItem<any>[])) { for (const item of (items as TouchBarItem<any>[])) {

View file

@ -140,9 +140,9 @@ const createGuest = function (embedder: Electron.WebContents, embedderFrameId: n
const makeProps = (eventKey: string, args: any[]) => { const makeProps = (eventKey: string, args: any[]) => {
const props: Record<string, any> = {}; const props: Record<string, any> = {};
webViewEvents[eventKey].forEach((prop, index) => { for (const [index, prop] of webViewEvents[eventKey].entries()) {
props[prop] = args[index]; props[prop] = args[index];
}); }
return props; return props;
}; };

View file

@ -80,11 +80,11 @@ export function parseFeatures (features: string) {
const parsed = parseCommaSeparatedKeyValue(features); const parsed = parseCommaSeparatedKeyValue(features);
const webPreferences: { [K in AllowedWebPreference]?: any } = {}; const webPreferences: { [K in AllowedWebPreference]?: any } = {};
allowedWebPreferences.forEach((key) => { for (const key of allowedWebPreferences) {
if (parsed[key] === undefined) return; if (parsed[key] === undefined) continue;
webPreferences[key] = parsed[key]; webPreferences[key] = parsed[key];
delete parsed[key]; delete parsed[key];
}); }
if (parsed.left !== undefined) parsed.x = parsed.left; if (parsed.left !== undefined) parsed.x = parsed.left;
if (parsed.top !== undefined) parsed.y = parsed.top; if (parsed.top !== undefined) parsed.y = parsed.top;

View file

@ -94,7 +94,9 @@ function useAppVeyorImage (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`); assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyorBuildJobs(targetBranch, options.job, options); callAppVeyorBuildJobs(targetBranch, options.job, options);
} else { } else {
validJobs.forEach((job) => callAppVeyorBuildJobs(targetBranch, job, options)); for (const job of validJobs) {
callAppVeyorBuildJobs(targetBranch, job, options);
}
} }
} }

View file

@ -193,7 +193,9 @@ function buildAppVeyor (targetBranch, options) {
assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`); assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`);
callAppVeyor(targetBranch, options.job, options); callAppVeyor(targetBranch, options.job, options);
} else { } else {
validJobs.forEach((job) => callAppVeyor(targetBranch, job, options)); for (const job of validJobs) {
callAppVeyor(targetBranch, job, options);
}
} }
} }
@ -243,7 +245,9 @@ function buildCircleCI (targetBranch, options) {
} else { } else {
assert(!options.arch, 'Cannot provide a single architecture while building all workflows, please specify a single workflow via --workflow'); assert(!options.arch, 'Cannot provide a single architecture while building all workflows, please specify a single workflow via --workflow');
options.runningPublishWorkflows = true; options.runningPublishWorkflows = true;
circleCIPublishWorkflows.forEach((job) => circleCIcall(targetBranch, job, options)); for (const job of circleCIPublishWorkflows) {
circleCIcall(targetBranch, job, options);
}
} }
} }

View file

@ -461,7 +461,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
toBranch toBranch
}; };
pool.commits.forEach(commit => { for (const commit of pool.commits) {
const str = commit.semanticType; const str = commit.semanticType;
if (commit.isBreakingChange) { if (commit.isBreakingChange) {
notes.breaking.push(commit); notes.breaking.push(commit);
@ -478,7 +478,7 @@ const getNotes = async (fromRef, toRef, newVersion) => {
} else { } else {
notes.unknown.push(commit); notes.unknown.push(commit);
} }
}); }
return notes; return notes;
}; };

View file

@ -58,18 +58,18 @@ new Promise((resolve, reject) => {
.then((dirPath) => { .then((dirPath) => {
tempDir = dirPath; tempDir = dirPath;
// copy files from `/npm` to temp directory // copy files from `/npm` to temp directory
files.forEach((name) => { for (const name of files) {
const noThirdSegment = name === 'README.md' || name === 'LICENSE'; const noThirdSegment = name === 'README.md' || name === 'LICENSE';
fs.writeFileSync( fs.writeFileSync(
path.join(tempDir, name), path.join(tempDir, name),
fs.readFileSync(path.join(ELECTRON_DIR, noThirdSegment ? '' : 'npm', name)) fs.readFileSync(path.join(ELECTRON_DIR, noThirdSegment ? '' : 'npm', name))
); );
}); }
// copy from root package.json to temp/package.json // copy from root package.json to temp/package.json
const packageJson = require(path.join(tempDir, 'package.json')); const packageJson = require(path.join(tempDir, 'package.json'));
jsonFields.forEach((fieldName) => { for (const fieldName of jsonFields) {
packageJson[fieldName] = rootPackageJson[fieldName]; packageJson[fieldName] = rootPackageJson[fieldName];
}); }
packageJson.version = currentElectronVersion; packageJson.version = currentElectronVersion;
fs.writeFileSync( fs.writeFileSync(
path.join(tempDir, 'package.json'), path.join(tempDir, 'package.json'),

View file

@ -65,9 +65,9 @@ async function validateReleaseAssets (release, validatingRelease) {
const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file)); const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file));
failureCount = 0; failureCount = 0;
requiredAssets.forEach(asset => { for (const asset of requiredAssets) {
check(extantAssets.includes(asset), asset); check(extantAssets.includes(asset), asset);
}); }
check((failureCount === 0), 'All required GitHub assets exist for release', true); check((failureCount === 0), 'All required GitHub assets exist for release', true);
if (!validatingRelease || !release.draft) { if (!validatingRelease || !release.draft) {

View file

@ -1229,9 +1229,9 @@ describe('app module', () => {
'http://', 'http://',
'https://' 'https://'
]; ];
protocols.forEach((protocol) => { for (const protocol of protocols) {
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal(''); expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
}); }
}); });
it('returns an empty string for a bogus protocol', () => { it('returns an empty string for a bogus protocol', () => {

View file

@ -276,9 +276,9 @@ describe('BrowserWindow module', () => {
} }
}; };
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show()); for (const win of windows) win.show();
windows.forEach(win => win.focus()); for (const win of windows) win.focus();
windows.forEach(win => win.destroy()); for (const win of windows) win.destroy();
app.removeListener('browser-window-focus', focusListener); app.removeListener('browser-window-focus', focusListener);
}); });
}); });
@ -1342,31 +1342,31 @@ describe('BrowserWindow module', () => {
const fakeSourceIds = [ const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
]; ];
fakeSourceIds.forEach((sourceId) => { for (const sourceId of fakeSourceIds) {
expect(() => { expect(() => {
w.moveAbove(sourceId); w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/); }).to.throw(/Invalid media source id/);
}); }
}); });
it('should throw an exception if wrong type', async () => { it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any]; const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => { for (const sourceId of fakeSourceIds) {
expect(() => { expect(() => {
w.moveAbove(sourceId); w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */); }).to.throw(/Error processing argument at index 0 */);
}); }
}); });
it('should throw an exception if invalid window', async () => { it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist. // It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1', const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9']; 'window:123456:9'];
fakeSourceIds.forEach((sourceId) => { for (const sourceId of fakeSourceIds) {
expect(() => { expect(() => {
w.moveAbove(sourceId); w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/); }).to.throw(/Invalid media source id/);
}); }
}); });
it('should not throw an exception', async () => { it('should not throw an exception', async () => {

View file

@ -1006,10 +1006,10 @@ describe('contextBridge', () => {
} }
}; };
const keys: string[] = []; const keys: string[] = [];
Object.entries(toExpose).forEach(([key, value]) => { for (const [key, value] of Object.entries(toExpose)) {
keys.push(key); keys.push(key);
contextBridge.exposeInMainWorld(key, value); contextBridge.exposeInMainWorld(key, value);
}); }
contextBridge.exposeInMainWorld('keys', keys); contextBridge.exposeInMainWorld('keys', keys);
}); });
const result = await callWithBindings(async (root: any) => { const result = await callWithBindings(async (root: any) => {

View file

@ -136,9 +136,9 @@ describe('MenuItems', () => {
const groups = findRadioGroups(template); const groups = findRadioGroups(template);
groups.forEach(g => { for (const g of groups) {
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.begin]); expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.begin]);
}); }
}); });
it('should assign groupId automatically', () => { it('should assign groupId automatically', () => {
@ -146,7 +146,7 @@ describe('MenuItems', () => {
const usedGroupIds = new Set(); const usedGroupIds = new Set();
const groups = findRadioGroups(template); const groups = findRadioGroups(template);
groups.forEach(g => { for (const g of groups) {
const groupId = (menu.items[g.begin!] as any).groupId; const groupId = (menu.items[g.begin!] as any).groupId;
// groupId should be previously unused // groupId should be previously unused
@ -158,14 +158,14 @@ describe('MenuItems', () => {
for (let i = g.begin!; i < g.end!; ++i) { for (let i = g.begin!; i < g.end!; ++i) {
expect((menu.items[i] as any).groupId).to.equal(groupId); expect((menu.items[i] as any).groupId).to.equal(groupId);
} }
}); }
}); });
it("setting 'checked' should flip other items' 'checked' property", () => { it("setting 'checked' should flip other items' 'checked' property", () => {
const menu = Menu.buildFromTemplate(template); const menu = Menu.buildFromTemplate(template);
const groups = findRadioGroups(template); const groups = findRadioGroups(template);
groups.forEach(g => { for (const g of groups) {
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([]); expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([]);
menu.items[g.begin!].checked = true; menu.items[g.begin!].checked = true;
@ -173,7 +173,7 @@ describe('MenuItems', () => {
menu.items[g.end! - 1].checked = true; menu.items[g.end! - 1].checked = true;
expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.end! - 1]); expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.end! - 1]);
}); }
}); });
}); });
}); });

View file

@ -68,7 +68,9 @@ async function respondNTimes (fn: http.RequestListener, n: number): Promise<stri
server.on('connection', s => sockets.push(s)); server.on('connection', s => sockets.push(s));
defer(() => { defer(() => {
server.close(); server.close();
sockets.forEach(s => s.destroy()); for (const socket of sockets) {
socket.destroy();
}
}); });
return (await listen(server)).url; return (await listen(server)).url;
} }
@ -771,7 +773,7 @@ describe('net module', () => {
}); });
}); });
['Lax', 'Strict'].forEach((mode) => { for (const mode of ['Lax', 'Strict']) {
it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => { it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
const serverUrl = await respondNTimes.toSingleURL((request, response) => { const serverUrl = await respondNTimes.toSingleURL((request, response) => {
response.statusCode = 200; response.statusCode = 200;
@ -812,7 +814,7 @@ describe('net module', () => {
const response2 = await getResponse(urlRequest2); const response2 = await getResponse(urlRequest2);
expect(response2.headers['x-cookie']).to.equal('same=site'); expect(response2.headers['x-cookie']).to.equal('same=site');
}); });
}); }
it('should be able to use the sessions cookie store safely across redirects', async () => { it('should be able to use the sessions cookie store safely across redirects', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
@ -1065,7 +1067,7 @@ describe('net module', () => {
await collectStreamBody(await getResponse(urlRequest)); await collectStreamBody(await getResponse(urlRequest));
}); });
['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => { for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) {
it(`should set sec-fetch-mode to ${mode} if requested`, async () => { it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => { const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal(mode); expect(request.headers['sec-fetch-mode']).to.equal(mode);
@ -1080,7 +1082,7 @@ describe('net module', () => {
urlRequest.setHeader('sec-fetch-mode', mode); urlRequest.setHeader('sec-fetch-mode', mode);
await collectStreamBody(await getResponse(urlRequest)); await collectStreamBody(await getResponse(urlRequest));
}); });
}); }
it('should set sec-fetch-dest to empty by default', async () => { it('should set sec-fetch-dest to empty by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => { const serverUrl = await respondOnce.toSingleURL((request, response) => {
@ -1095,12 +1097,12 @@ describe('net module', () => {
await collectStreamBody(await getResponse(urlRequest)); await collectStreamBody(await getResponse(urlRequest));
}); });
[ for (const dest of [
'empty', 'audio', 'audioworklet', 'document', 'embed', 'font', 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet', 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
'report', 'script', 'serviceworker', 'style', 'track', 'video', 'report', 'script', 'serviceworker', 'style', 'track', 'video',
'worker', 'xslt' 'worker', 'xslt'
].forEach((dest) => { ]) {
it(`should set sec-fetch-dest to ${dest} if requested`, async () => { it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => { const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal(dest); expect(request.headers['sec-fetch-dest']).to.equal(dest);
@ -1115,7 +1117,7 @@ describe('net module', () => {
urlRequest.setHeader('sec-fetch-dest', dest); urlRequest.setHeader('sec-fetch-dest', dest);
await collectStreamBody(await getResponse(urlRequest)); await collectStreamBody(await getResponse(urlRequest));
}); });
}); }
it('should be able to abort an HTTP request before first write', async () => { it('should be able to abort an HTTP request before first write', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => { const serverUrl = await respondOnce.toSingleURL((request, response) => {
@ -1691,11 +1693,11 @@ describe('net module', () => {
await once(urlRequest, 'close'); await once(urlRequest, 'close');
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
['finish', 'abort', 'close', 'error'].forEach(evName => { for (const evName of ['finish', 'abort', 'close', 'error']) {
urlRequest.on(evName as any, () => { urlRequest.on(evName as any, () => {
reject(new Error(`Unexpected ${evName} event`)); reject(new Error(`Unexpected ${evName} event`));
}); });
}); }
setTimeout(50).then(resolve); setTimeout(50).then(resolve);
}); });
}); });
@ -1934,9 +1936,9 @@ describe('net module', () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => { const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200; response.statusCode = 200;
response.statusMessage = 'OK'; response.statusMessage = 'OK';
customHeaders.forEach((headerTuple) => { for (const headerTuple of customHeaders) {
response.setHeader(headerTuple[0], headerTuple[1]); response.setHeader(headerTuple[0], headerTuple[1]);
}); }
response.end(); response.end();
}); });
const urlRequest = net.request(serverUrl); const urlRequest = net.request(serverUrl);
@ -1948,15 +1950,15 @@ describe('net module', () => {
expect(rawHeaders).to.be.an('array'); expect(rawHeaders).to.be.an('array');
let rawHeadersIdx = 0; let rawHeadersIdx = 0;
customHeaders.forEach((headerTuple) => { for (const headerTuple of customHeaders) {
const headerKey = headerTuple[0]; const headerKey = headerTuple[0];
const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]]; const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
headerValues.forEach((headerValue) => { for (const headerValue of headerValues) {
expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey); expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue); expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
rawHeadersIdx += 2; rawHeadersIdx += 2;
}); }
}); }
await collectStreamBody(response); await collectStreamBody(response);
}); });

View file

@ -157,7 +157,7 @@ describe('renderer nodeIntegrationInSubFrames', () => {
}); });
}; };
generateConfigs( const configs = generateConfigs(
{ {
preload: path.resolve(__dirname, 'fixtures/sub-frames/preload.js'), preload: path.resolve(__dirname, 'fixtures/sub-frames/preload.js'),
nodeIntegrationInSubFrames: true nodeIntegrationInSubFrames: true
@ -174,9 +174,11 @@ describe('renderer nodeIntegrationInSubFrames', () => {
name: 'webview', name: 'webview',
webPreferences: { webviewTag: true, preload: false } webPreferences: { webviewTag: true, preload: false }
} }
).forEach(config => { );
for (const config of configs) {
generateTests(config.title, config.webPreferences); generateTests(config.title, config.webPreferences);
}); }
describe('internal <iframe> inside of <webview>', () => { describe('internal <iframe> inside of <webview>', () => {
let w: BrowserWindow; let w: BrowserWindow;

View file

@ -32,7 +32,7 @@ describe('systemPreferences module', () => {
] as const; ] as const;
const defaultsDict: Record<string, any> = {}; const defaultsDict: Record<string, any> = {};
defaultsMap.forEach(row => { defaultsDict[row.key] = row.value; }); for (const row of defaultsMap) { defaultsDict[row.key] = row.value; }
systemPreferences.registerDefaults(defaultsDict); systemPreferences.registerDefaults(defaultsDict);
@ -160,10 +160,10 @@ describe('systemPreferences module', () => {
it('returns a valid system color', () => { it('returns a valid system color', () => {
const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow'] as const; const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow'] as const;
colors.forEach(color => { for (const color of colors) {
const sysColor = systemPreferences.getSystemColor(color); const sysColor = systemPreferences.getSystemColor(color);
expect(sysColor).to.be.a('string'); expect(sysColor).to.be.a('string');
}); }
}); });
}); });
@ -211,10 +211,10 @@ describe('systemPreferences module', () => {
'window-frame-text' 'window-frame-text'
] as const; ] as const;
colors.forEach(color => { for (const color of colors) {
const sysColor = systemPreferences.getColor(color); const sysColor = systemPreferences.getColor(color);
expect(sysColor).to.be.a('string'); expect(sysColor).to.be.a('string');
}); }
await expectDeprecationMessages( await expectDeprecationMessages(
() => { () => {

View file

@ -1312,10 +1312,10 @@ describe('webContents module', () => {
'default_public_and_private_interfaces', 'default_public_and_private_interfaces',
'disable_non_proxied_udp' 'disable_non_proxied_udp'
] as const; ] as const;
policies.forEach((policy) => { for (const policy of policies) {
w.webContents.setWebRTCIPHandlingPolicy(policy); w.webContents.setWebRTCIPHandlingPolicy(policy);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
}); }
}); });
}); });

View file

@ -904,7 +904,7 @@ describe('chromium features', () => {
await closeAllWindows(); await closeAllWindows();
}); });
[true, false].forEach((isSandboxEnabled) => for (const isSandboxEnabled of [true, false]) {
describe(`sandbox=${isSandboxEnabled}`, () => { describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => { it('posts data in the same window', async () => {
const w = new BrowserWindow({ const w = new BrowserWindow({
@ -954,8 +954,8 @@ describe('chromium features', () => {
const res = await newWin.webContents.executeJavaScript('document.body.innerText'); const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello'); expect(res).to.equal('body:greeting=hello');
}); });
}) });
); }
}); });
describe('window.open', () => { describe('window.open', () => {
@ -1913,7 +1913,7 @@ describe('chromium features', () => {
}); });
describe('DOM storage quota increase', () => { describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => { for (const storageName of ['localStorage', 'sessionStorage']) {
it(`allows saving at least 40MiB in ${storageName}`, async () => { it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false }); const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
@ -1959,7 +1959,7 @@ describe('chromium features', () => {
} }
})()).to.eventually.be.rejected(); })()).to.eventually.be.rejected();
}); });
}); }
}); });
describe('persistent storage', () => { describe('persistent storage', () => {

View file

@ -44,9 +44,9 @@ describe('chrome extensions', () => {
}); });
afterEach(closeAllWindows); afterEach(closeAllWindows);
afterEach(() => { afterEach(() => {
session.defaultSession.getAllExtensions().forEach((e: any) => { for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id); session.defaultSession.removeExtension(e.id);
}); }
}); });
it('does not crash when using chrome.management', async () => { it('does not crash when using chrome.management', async () => {
@ -759,9 +759,9 @@ describe('chrome extensions', () => {
describe('extension ui pages', () => { describe('extension ui pages', () => {
afterEach(() => { afterEach(() => {
session.defaultSession.getAllExtensions().forEach(e => { for (const e of session.defaultSession.getAllExtensions()) {
session.defaultSession.removeExtension(e.id); session.defaultSession.removeExtension(e.id);
}); }
}); });
it('loads a ui page of an extension', async () => { it('loads a ui page of an extension', async () => {

View file

@ -14,11 +14,11 @@
const { ipcRenderer } = require('electron'); const { ipcRenderer } = require('electron');
const observer = new MutationObserver((mutationList, observer) => { const observer = new MutationObserver((mutationList, observer) => {
mutationList.forEach(({ type, attributeName }) => { for (const { type, attributeName } of mutationList) {
if (type === 'attributes' && attributeName === 'style') { if (type === 'attributes' && attributeName === 'style') {
ipcRenderer.send('set-transparent'); ipcRenderer.send('set-transparent');
} }
}); }
}); });
observer.observe(document.body, { attributes: true }); observer.observe(document.body, { attributes: true });

View file

@ -27,7 +27,9 @@ describe('webContents.setWindowOpenHandler', () => {
done(e); done(e);
} finally { } finally {
process.removeAllListeners('uncaughtException'); process.removeAllListeners('uncaughtException');
listeners.forEach((listener) => process.on('uncaughtException', listener)); for (const listener of listeners) {
process.on('uncaughtException', listener);
}
} }
}); });

View file

@ -148,9 +148,9 @@ app.whenReady().then(async () => {
const { getFiles } = require('./get-files'); const { getFiles } = require('./get-files');
const testFiles = await getFiles(__dirname, { filter }); const testFiles = await getFiles(__dirname, { filter });
testFiles.sort().forEach((file) => { for (const file of testFiles.sort()) {
mocha.addFile(file); mocha.addFile(file);
}); }
if (validTestPaths && validTestPaths.length > 0 && testFiles.length === 0) { if (validTestPaths && validTestPaths.length > 0 && testFiles.length === 0) {
console.error('Test files were provided, but they did not match any searched files'); console.error('Test files were provided, but they did not match any searched files');

View file

@ -195,9 +195,9 @@ describe('node feature', () => {
emitter.removeAllListeners(eventName); emitter.removeAllListeners(eventName);
emitter.once(eventName, (...args) => { emitter.once(eventName, (...args) => {
emitter.removeAllListeners(eventName); emitter.removeAllListeners(eventName);
listeners.forEach((listener) => { for (const listener of listeners) {
emitter.on(eventName, listener); emitter.on(eventName, listener);
}); }
callback(...args); callback(...args);
}); });

View file

@ -929,7 +929,7 @@ describe('<webview> tag', function () {
}); });
afterEach(async () => { afterEach(async () => {
await w.executeJavaScript(`{ await w.executeJavaScript(`{
document.querySelectorAll('webview').forEach(el => el.remove()) for (const el of document.querySelectorAll('webview')) el.remove();
}`); }`);
}); });
after(closeAllWindows); after(closeAllWindows);
@ -1411,7 +1411,7 @@ describe('<webview> tag', function () {
}); });
afterEach(async () => { afterEach(async () => {
await w.executeJavaScript(`{ await w.executeJavaScript(`{
document.querySelectorAll('webview').forEach(el => el.remove()) for (const el of document.querySelectorAll('webview')) el.remove();
}`); }`);
}); });
after(closeAllWindows); after(closeAllWindows);
@ -1791,7 +1791,7 @@ describe('<webview> tag', function () {
}); });
afterEach(async () => { afterEach(async () => {
await w.executeJavaScript(`{ await w.executeJavaScript(`{
document.querySelectorAll('webview').forEach(el => el.remove()) for (const el of document.querySelectorAll('webview')) el.remove();
}`); }`);
}); });
after(closeAllWindows); after(closeAllWindows);
@ -2088,7 +2088,7 @@ describe('<webview> tag', function () {
}); });
afterEach(async () => { afterEach(async () => {
await w.executeJavaScript(`{ await w.executeJavaScript(`{
document.querySelectorAll('webview').forEach(el => el.remove()) for (const el of document.querySelectorAll('webview')) el.remove();
}`); }`);
}); });
after(closeAllWindows); after(closeAllWindows);