Browse Source

chore: enable object-curly-spacing in ESLint (#9168)

pull/9183/head
Max Schmitt 4 weeks ago
committed by GitHub
parent
commit
cd22072685
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      .eslintrc.js
  2. 4
      packages/create-playwright/tests/integration.spec.ts
  3. 2
      src/cli/cli.ts
  4. 2
      src/client/android.ts
  5. 6
      src/client/browserContext.ts
  6. 2
      src/client/browserType.ts
  7. 2
      src/client/input.ts
  8. 2
      src/client/jsHandle.ts
  9. 2
      src/client/page.ts
  10. 4
      src/dispatchers/browserContextDispatcher.ts
  11. 2
      src/dispatchers/browserTypeDispatcher.ts
  12. 2
      src/server/accessibility.ts
  13. 2
      src/server/browserContext.ts
  14. 2
      src/server/chromium/chromium.ts
  15. 4
      src/server/chromium/crAccessibility.ts
  16. 2
      src/server/chromium/crBrowser.ts
  17. 2
      src/server/chromium/crConnection.ts
  18. 12
      src/server/chromium/crCoverage.ts
  19. 16
      src/server/chromium/crDragDrop.ts
  20. 4
      src/server/chromium/crExecutionContext.ts
  21. 4
      src/server/chromium/crNetworkManager.ts
  22. 6
      src/server/chromium/crPage.ts
  23. 22
      src/server/chromium/crPdf.ts
  24. 6
      src/server/chromium/crProtocolHelper.ts
  25. 4
      src/server/common/componentUtils.ts
  26. 2
      src/server/dom.ts
  27. 2
      src/server/electron/electron.ts
  28. 4
      src/server/fetch.ts
  29. 4
      src/server/firefox/ffBrowser.ts
  30. 10
      src/server/firefox/ffConnection.ts
  31. 2
      src/server/firefox/ffExecutionContext.ts
  32. 2
      src/server/firefox/ffNetworkManager.ts
  33. 12
      src/server/firefox/ffPage.ts
  34. 2
      src/server/frames.ts
  35. 2
      src/server/injected/reactSelectorEngine.ts
  36. 4
      src/server/injected/vueSelectorEngine.ts
  37. 2
      src/server/javascript.ts
  38. 2
      src/server/network.ts
  39. 8
      src/server/page.ts
  40. 2
      src/server/screenshotter.ts
  41. 2
      src/server/webkit/webkit.ts
  42. 4
      src/server/webkit/wkAccessibility.ts
  43. 2
      src/server/webkit/wkConnection.ts
  44. 6
      src/server/webkit/wkPage.ts
  45. 2
      src/server/webkit/wkProvisionalPage.ts
  46. 2
      src/test/dispatcher.ts
  47. 2
      src/test/reporters/base.ts
  48. 2
      src/test/reporters/junit.ts
  49. 2
      src/test/runner.ts
  50. 2
      src/test/transform.ts
  51. 4
      src/utils/browserFetcher.ts
  52. 8
      src/utils/dependencies.ts
  53. 4
      src/utils/registry.ts
  54. 18
      src/utils/utils.ts
  55. 2
      src/web/components/expandable.tsx
  56. 2
      src/web/components/splitView.tsx
  57. 2
      src/web/htmlReport/htmlReport.tsx
  58. 2
      src/web/recorder/callLog.tsx
  59. 6
      src/web/recorder/recorder.tsx
  60. 2
      tests/android/browser.spec.ts
  61. 2
      tests/android/device.spec.ts
  62. 12
      tests/beforeunload.spec.ts
  63. 6
      tests/browser.spec.ts
  64. 58
      tests/browsercontext-add-cookies.spec.ts
  65. 16
      tests/browsercontext-base-url.spec.ts
  66. 30
      tests/browsercontext-basic.spec.ts
  67. 8
      tests/browsercontext-clearcookies.spec.ts
  68. 22
      tests/browsercontext-cookies.spec.ts
  69. 10
      tests/browsercontext-credentials.spec.ts
  70. 24
      tests/browsercontext-csp.spec.ts
  71. 16
      tests/browsercontext-device.spec.ts
  72. 2
      tests/browsercontext-dsf.spec.ts
  73. 10
      tests/browsercontext-expose-function.spec.ts
  74. 118
      tests/browsercontext-fetch.spec.ts
  75. 24
      tests/browsercontext-locale.spec.ts
  76. 12
      tests/browsercontext-network-event.spec.ts
  77. 22
      tests/browsercontext-page-event.spec.ts
  78. 14
      tests/browsercontext-pages.spec.ts
  79. 18
      tests/browsercontext-proxy.spec.ts
  80. 20
      tests/browsercontext-route.spec.ts
  81. 4
      tests/browsercontext-set-extra-http-headers.spec.ts
  82. 8
      tests/browsercontext-timezone-id.spec.ts
  83. 8
      tests/browsercontext-user-agent.spec.ts
  84. 42
      tests/browsercontext-viewport-mobile.spec.ts
  85. 36
      tests/browsercontext-viewport.spec.ts
  86. 4
      tests/browsertype-basic.spec.ts
  87. 66
      tests/browsertype-connect.spec.ts
  88. 22
      tests/browsertype-launch-server.spec.ts
  89. 40
      tests/browsertype-launch.spec.ts
  90. 14
      tests/capabilities.spec.ts
  91. 10
      tests/channels.spec.ts
  92. 18
      tests/chromium/chromium.spec.ts
  93. 28
      tests/chromium/css-coverage.spec.ts
  94. 20
      tests/chromium/js-coverage.spec.ts
  95. 20
      tests/chromium/launcher.spec.ts
  96. 52
      tests/chromium/oopif.spec.ts
  97. 26
      tests/chromium/session.spec.ts
  98. 28
      tests/chromium/tracing.spec.ts
  99. 2
      tests/config/baseTest.ts
  100. 50
      tests/defaultbrowsercontext-1.spec.ts

1
.eslintrc.js

@ -24,6 +24,7 @@ module.exports = {
* Enforced rules
*/
// syntax preferences
"object-curly-spacing": ["error", "always"],
"quotes": [2, "single", {
"avoidEscape": true,
"allowTemplateLiterals": true

4
packages/create-playwright/tests/integration.spec.ts

@ -67,9 +67,9 @@ const test = base.extend<TestFixtures>({
},
});
for (const packageManager of ['npm', 'yarn'] as ('npm'|'yarn')[]) {
for (const packageManager of ['npm', 'yarn'] as ('npm' | 'yarn')[]) {
test.describe(`Package manager: ${packageManager}`, () => {
test.use({packageManager});
test.use({ packageManager });
test('should generate a project in the current directory', async ({ run }) => {
const { exitCode, dir, stdout } = await run([], { installGitHubActions: true, testDir: 'e2e', language: 'TypeScript' });

2
src/cli/cli.ts

@ -167,7 +167,7 @@ const browsers = [
{ alias: 'wk', name: 'WebKit', type: 'webkit' },
];
for (const {alias, name, type} of browsers) {
for (const { alias, name, type } of browsers) {
commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, [])
.action(function(url, command) {
open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit);

2
src/client/android.ts

@ -360,7 +360,7 @@ function toSelectorChannel(selector: api.AndroidSelector): channels.AndroidSelec
focusable,
focused,
hasChild: hasChild ? { selector: toSelectorChannel(hasChild.selector) } : undefined,
hasDescendant: hasDescendant ? { selector: toSelectorChannel(hasDescendant.selector), maxDepth: hasDescendant.maxDepth} : undefined,
hasDescendant: hasDescendant ? { selector: toSelectorChannel(hasDescendant.selector), maxDepth: hasDescendant.maxDepth } : undefined,
longClickable,
scrollable,
selected,

6
src/client/browserContext.ts

@ -71,16 +71,16 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel,
this.tracing = new Tracing(this);
this._request = FetchRequest.from(initializer.fetchRequest);
this._channel.on('bindingCall', ({binding}) => this._onBinding(BindingCall.from(binding)));
this._channel.on('bindingCall', ({ binding }) => this._onBinding(BindingCall.from(binding)));
this._channel.on('close', () => this._onClose());
this._channel.on('page', ({page}) => this._onPage(Page.from(page)));
this._channel.on('page', ({ page }) => this._onPage(Page.from(page)));
this._channel.on('route', ({ route, request }) => this._onRoute(network.Route.from(route), network.Request.from(request)));
this._channel.on('backgroundPage', ({ page }) => {
const backgroundPage = Page.from(page);
this._backgroundPages.add(backgroundPage);
this.emit(Events.BrowserContext.BackgroundPage, backgroundPage);
});
this._channel.on('serviceWorker', ({worker}) => {
this._channel.on('serviceWorker', ({ worker }) => {
const serviceWorker = Worker.from(worker);
serviceWorker._context = this;
this._serviceWorkers.add(serviceWorker);

2
src/client/browserType.ts

@ -210,7 +210,7 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel, chann
throw new Error('Connecting over CDP is only supported in Chromium.');
const logger = params.logger;
return this._wrapApiCall(async (channel: channels.BrowserTypeChannel) => {
const paramsHeaders = Object.assign({'User-Agent': getUserAgent()}, params.headers);
const paramsHeaders = Object.assign({ 'User-Agent': getUserAgent() }, params.headers);
const headers = paramsHeaders ? headersObjectToArray(paramsHeaders) : undefined;
const result = await channel.connectOverCDP({
endpointURL,

2
src/client/input.ts

@ -108,7 +108,7 @@ export class Touchscreen implements api.Touchscreen {
async tap(x: number, y: number) {
await this._page._wrapApiCall(async channel => {
await channel.touchscreenTap({x, y});
await channel.touchscreenTap({ x, y });
});
}
}

2
src/client/jsHandle.ts

@ -30,7 +30,7 @@ export class JSHandle<T = any> extends ChannelOwner<channels.JSHandleChannel, ch
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.JSHandleInitializer) {
super(parent, type, guid, initializer);
this._preview = this._initializer.preview;
this._channel.on('previewUpdated', ({preview}) => this._preview = preview);
this._channel.on('previewUpdated', ({ preview }) => this._preview = preview);
}
async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg): Promise<R> {

2
src/client/page.ts

@ -491,7 +491,7 @@ export class Page extends ChannelOwner<channels.PageChannel, channels.PageInitia
});
}
async close(options: { runBeforeUnload?: boolean } = {runBeforeUnload: undefined}) {
async close(options: { runBeforeUnload?: boolean } = { runBeforeUnload: undefined }) {
try {
await this._wrapApiCall(async (channel: channels.PageChannel) => {
if (this._ownedContext)

4
src/dispatchers/browserContextDispatcher.ts

@ -65,7 +65,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
this._dispatchEvent('backgroundPage', { page: new PageDispatcher(this._scope, page) });
context.on(CRBrowserContext.CREvents.BackgroundPage, page => this._dispatchEvent('backgroundPage', { page: new PageDispatcher(this._scope, page) }));
for (const serviceWorker of (context as CRBrowserContext).serviceWorkers())
this._dispatchEvent('serviceWorker', { worker: new WorkerDispatcher(this._scope, serviceWorker)});
this._dispatchEvent('serviceWorker', { worker: new WorkerDispatcher(this._scope, serviceWorker) });
context.on(CRBrowserContext.CREvents.ServiceWorker, serviceWorker => this._dispatchEvent('serviceWorker', { worker: new WorkerDispatcher(this._scope, serviceWorker) }));
}
context.on(BrowserContext.Events.Request, (request: Request) => {
@ -84,7 +84,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
responseEndTiming: request._responseEndTiming,
page: PageDispatcher.fromNullable(this._scope, request.frame()._page.initializedOrUndefined())
}));
context.on(BrowserContext.Events.RequestFinished, ({ request, response}: { request: Request, response: Response | null }) => this._dispatchEvent('requestFinished', {
context.on(BrowserContext.Events.RequestFinished, ({ request, response }: { request: Request, response: Response | null }) => this._dispatchEvent('requestFinished', {
request: RequestDispatcher.from(scope, request),
response: ResponseDispatcher.fromNullable(scope, response),
responseEndTiming: request._responseEndTiming,

2
src/dispatchers/browserTypeDispatcher.ts

@ -56,7 +56,7 @@ export class BrowserTypeDispatcher extends Dispatcher<BrowserType, channels.Brow
const waitForNextTask = params.slowMo
? (cb: () => any) => setTimeout(cb, params.slowMo)
: makeWaitForNextTask();
const paramsHeaders = Object.assign({'User-Agent': getUserAgent()}, params.headers || {});
const paramsHeaders = Object.assign({ 'User-Agent': getUserAgent() }, params.headers || {});
const ws = new WebSocket(params.wsEndpoint, [], {
perMessageDeflate: false,
maxPayload: 256 * 1024 * 1024, // 256Mb,

2
src/server/accessibility.ts

@ -40,7 +40,7 @@ export class Accessibility {
interestingOnly = true,
root = null,
} = options;
const {tree, needle} = await this._getAXTree(root || undefined);
const { tree, needle } = await this._getAXTree(root || undefined);
if (!interestingOnly) {
if (root)
return needle && serializeTree(needle)[0];

2
src/server/browserContext.ts

@ -76,7 +76,7 @@ export abstract class BrowserContext extends SdkObject {
this._closePromise = new Promise(fulfill => this._closePromiseFulfill = fulfill);
if (this._options.recordHar)
this._harRecorder = new HarRecorder(this, {...this._options.recordHar, path: path.join(this._browser.options.artifactsDir, `${createGuid()}.har`)});
this._harRecorder = new HarRecorder(this, { ...this._options.recordHar, path: path.join(this._browser.options.artifactsDir, `${createGuid()}.har`) });
this.tracing = new Tracing(this);
this.fetchRequest = new BrowserContextFetchRequest(this);

2
src/server/chromium/chromium.ts

@ -54,7 +54,7 @@ export class Chromium extends BrowserType {
controller.setLogName('browser');
return controller.run(async progress => {
return await this._connectOverCDPInternal(progress, endpointURL, options);
}, TimeoutSettings.timeout({timeout}));
}, TimeoutSettings.timeout({ timeout }));
}
async _connectOverCDPInternal(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray }, onClose?: () => Promise<void>) {

4
src/server/chromium/crAccessibility.ts

@ -22,7 +22,7 @@ import * as accessibility from '../accessibility';
import * as types from '../types';
export async function getAccessibilityTree(client: CRSession, needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> {
const {nodes} = await client.send('Accessibility.getFullAXTree');
const { nodes } = await client.send('Accessibility.getFullAXTree');
const tree = CRAXNode.createTree(client, nodes);
return {
tree,
@ -97,7 +97,7 @@ class CRAXNode implements accessibility.AXNode {
async _findElement(element: dom.ElementHandle): Promise<CRAXNode | null> {
const objectId = element._objectId;
const {node: {backendNodeId}} = await this._client.send('DOM.describeNode', { objectId });
const { node: { backendNodeId } } = await this._client.send('DOM.describeNode', { objectId });
const needle = this.find(node => node._payload.backendDOMNodeId === backendNodeId);
return needle || null;
}

2
src/server/chromium/crBrowser.ts

@ -121,7 +121,7 @@ export class CRBrowser extends Browser {
await Promise.all([...this._crPages.values()].map(page => page.pageOrError()));
}
_onAttachedToTarget({targetInfo, sessionId, waitingForDebugger}: Protocol.Target.attachedToTargetPayload) {
_onAttachedToTarget({ targetInfo, sessionId, waitingForDebugger }: Protocol.Target.attachedToTargetPayload) {
if (targetInfo.type === 'browser')
return;
const session = this._connection.session(sessionId)!;

2
src/server/chromium/crConnection.ts

@ -172,7 +172,7 @@ export class CRSession extends EventEmitter {
throw new ProtocolError(true, `Target closed`);
const id = this._connection._rawSend(this._sessionId, method, params);
return new Promise((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, error: new ProtocolError(false), method});
this._callbacks.set(id, { resolve, reject, error: new ProtocolError(false), method });
});
}

12
src/server/chromium/crCoverage.ts

@ -85,7 +85,7 @@ class JSCoverage {
this._client.send('Profiler.enable'),
this._client.send('Profiler.startPreciseCoverage', { callCount: true, detailed: true }),
this._client.send('Debugger.enable'),
this._client.send('Debugger.setSkipAllPauses', {skip: true})
this._client.send('Debugger.setSkipAllPauses', { skip: true })
]);
}
@ -106,7 +106,7 @@ class JSCoverage {
if (!event.url && !this._reportAnonymousScripts)
return;
// This might fail if the page has already navigated away.
const response = await this._client._sendMayFail('Debugger.getScriptSource', {scriptId: event.scriptId});
const response = await this._client._sendMayFail('Debugger.getScriptSource', { scriptId: event.scriptId });
if (response)
this._scriptSources.set(event.scriptId, response.scriptSource);
}
@ -130,7 +130,7 @@ class JSCoverage {
continue;
const source = this._scriptSources.get(entry.scriptId);
if (source)
coverage.push({...entry, source});
coverage.push({ ...entry, source });
else
coverage.push(entry);
}
@ -157,7 +157,7 @@ class CSSCoverage {
async start(options: types.CSSCoverageOptions = {}) {
assert(!this._enabled, 'CSSCoverage is already enabled');
const {resetOnNavigation = true} = options;
const { resetOnNavigation = true } = options;
this._resetOnNavigation = resetOnNavigation;
this._enabled = true;
this._stylesheetURLs.clear();
@ -186,7 +186,7 @@ class CSSCoverage {
if (!header.sourceURL)
return;
// This might fail if the page has already navigated away.
const response = await this._client._sendMayFail('CSS.getStyleSheetText', {styleSheetId: header.styleSheetId});
const response = await this._client._sendMayFail('CSS.getStyleSheetText', { styleSheetId: header.styleSheetId });
if (response) {
this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);
this._stylesheetSources.set(header.styleSheetId, response.text);
@ -266,7 +266,7 @@ function convertToDisjointRanges(nestedRanges: {
if (lastResult && lastResult.end === lastOffset)
lastResult.end = point.offset;
else
results.push({start: lastOffset, end: point.offset});
results.push({ start: lastOffset, end: point.offset });
}
lastOffset = point.offset;
if (point.type === 0)

16
src/server/chromium/crDragDrop.ts

@ -28,7 +28,7 @@ declare global {
export class DragManager {
private _crPage: CRPage;
private _dragState: Protocol.Input.DragData | null = null;
private _lastPosition = {x: 0, y: 0};
private _lastPosition = { x: 0, y: 0 };
constructor(page: CRPage) {
this._crPage = page;
}
@ -50,7 +50,7 @@ export class DragManager {
}
async interceptDragCausedByMove(x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, moveCallback: () => Promise<void>): Promise<void> {
this._lastPosition = {x, y};
this._lastPosition = { x, y };
if (this._dragState) {
await this._crPage._mainFrameSession._client.send('Input.dispatchDragEvent', {
type: 'dragOver',
@ -75,15 +75,15 @@ export class DragManager {
const dragListener = (event: Event) => dragEvent = event;
const mouseListener = () => {
didStartDrag = new Promise<boolean>(callback => {
window.addEventListener('dragstart', dragListener, {once: true, capture: true});
window.addEventListener('dragstart', dragListener, { once: true, capture: true });
setTimeout(() => callback(dragEvent ? !dragEvent.defaultPrevented : false), 0);
});
};
window.addEventListener('mousemove', mouseListener, {once: true, capture: true});
window.addEventListener('mousemove', mouseListener, { once: true, capture: true });
window.__cleanupDrag = async () => {
const val = await didStartDrag;
window.removeEventListener('mousemove', mouseListener, {capture: true});
window.removeEventListener('dragstart', dragListener, {capture: true});
window.removeEventListener('mousemove', mouseListener, { capture: true });
window.removeEventListener('dragstart', dragListener, { capture: true });
return val;
};
}).toString(), true, 'utility').catch(() => {});
@ -91,7 +91,7 @@ export class DragManager {
client.on('Input.dragIntercepted', onDragIntercepted!);
try {
await client.send('Input.setInterceptDrags', {enabled: true});
await client.send('Input.setInterceptDrags', { enabled: true });
} catch {
// If Input.setInterceptDrags is not supported, just do a regular move.
// This can be removed once we stop supporting old Electron.
@ -105,7 +105,7 @@ export class DragManager {
}))).some(x => x);
this._dragState = expectingDrag ? (await dragInterceptedPromise).data : null;
client.off('Input.dragIntercepted', onDragIntercepted!);
await client.send('Input.setInterceptDrags', {enabled: false});
await client.send('Input.setInterceptDrags', { enabled: false });
if (this._dragState) {

4
src/server/chromium/crExecutionContext.ts

@ -106,9 +106,9 @@ export class CRExecutionContext implements js.ExecutionContextDelegate {
function rewriteError(error: Error): Protocol.Runtime.evaluateReturnValue {
if (error.message.includes('Object reference chain is too long'))
return {result: {type: 'undefined'}};
return { result: { type: 'undefined' } };
if (error.message.includes('Object couldn\'t be returned by value'))
return {result: {type: 'undefined'}};
return { result: { type: 'undefined' } };
if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON'))
rewriteErrorMessage(error, error.message + ' Are you passing a nested JSHandle?');

4
src/server/chromium/crNetworkManager.ts

@ -105,7 +105,7 @@ export class CRNetworkManager {
this._client.send('Network.setCacheDisabled', { cacheDisabled: true }),
this._client.send('Fetch.enable', {
handleAuthRequests: true,
patterns: [{urlPattern: '*', requestStage: 'Request'}, {urlPattern: '*', requestStage: 'Response'}],
patterns: [{ urlPattern: '*', requestStage: 'Request' }, { urlPattern: '*', requestStage: 'Response' }],
}),
]);
} else {
@ -146,7 +146,7 @@ export class CRNetworkManager {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.requestId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
const { username, password } = this._credentials || { username: undefined, password: undefined };
this._client._sendMayFail('Fetch.continueWithAuth', {
requestId: event.requestId,
authChallengeResponse: { response, username, password },

6
src/server/chromium/crPage.ts

@ -460,7 +460,7 @@ class FrameSession {
this._addBrowserListeners();
const promises: Promise<any>[] = [
this._client.send('Page.enable'),
this._client.send('Page.getFrameTree').then(({frameTree}) => {
this._client.send('Page.getFrameTree').then(({ frameTree }) => {
if (this._isMainFrame()) {
this._handleFrameTree(frameTree);
this._addRendererListeners();
@ -815,7 +815,7 @@ class FrameSession {
}
_onLogEntryAdded(event: Protocol.Log.entryAddedPayload) {
const {level, text, args, source, url, lineNumber} = event.entry;
const { level, text, args, source, url, lineNumber } = event.entry;
if (args)
args.map(arg => releaseObject(this._client, arg.objectId!));
if (source !== 'worker') {
@ -853,7 +853,7 @@ class FrameSession {
}
_onScreencastFrame(payload: Protocol.Page.screencastFramePayload) {
this._client.send('Page.screencastFrameAck', {sessionId: payload.sessionId}).catch(() => {});
this._client.send('Page.screencastFrameAck', { sessionId: payload.sessionId }).catch(() => {});
const buffer = Buffer.from(payload.data, 'base64');
this._page.emit(Page.Events.ScreencastFrame, {
buffer,

22
src/server/chromium/crPdf.ts

@ -21,17 +21,17 @@ import { CRSession } from './crConnection';
import { readProtocolStream } from './crProtocolHelper';
const PagePaperFormats: { [key: string]: { width: number, height: number }} = {
letter: {width: 8.5, height: 11},
legal: {width: 8.5, height: 14},
tabloid: {width: 11, height: 17},
ledger: {width: 17, height: 11},
a0: {width: 33.1, height: 46.8 },
a1: {width: 23.4, height: 33.1 },
a2: {width: 16.54, height: 23.4 },
a3: {width: 11.7, height: 16.54 },
a4: {width: 8.27, height: 11.7 },
a5: {width: 5.83, height: 8.27 },
a6: {width: 4.13, height: 5.83 },
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 },
};
const unitToPixels: { [key: string]: number } = {

6
src/server/chromium/crProtocolHelper.ts

@ -49,7 +49,7 @@ export async function readProtocolStream(client: CRSession, handle: string, path
}
const bufs = [];
while (!eof) {
const response = await client.send('IO.read', {handle});
const response = await client.send('IO.read', { handle });
eof = response.eof;
const buf = Buffer.from(response.data, response.base64Encoded ? 'base64' : undefined);
bufs.push(buf);
@ -58,7 +58,7 @@ export async function readProtocolStream(client: CRSession, handle: string, path
}
if (fd)
await fd.close();
await client.send('IO.close', {handle});
await client.send('IO.close', { handle });
return Buffer.concat(bufs);
}
@ -82,7 +82,7 @@ export function exceptionToError(exceptionDetails: Protocol.Runtime.ExceptionDet
messageWithName = lines.slice(0, firstStackTraceLine).join('\n');
stack = messageWithStack;
}
const {name, message} = splitErrorMessage(messageWithName);
const { name, message } = splitErrorMessage(messageWithName);
const err = new Error(message);
err.stack = stack;

4
src/server/common/componentUtils.ts

@ -142,7 +142,7 @@ export function parseComponentSelector(selector: string): ParsedComponentSelecto
// check property is truthy: [enabled]
if (next() === ']') {
eat1();
return {jsonPath, op: '<truthy>', value: null, caseSensetive: false};
return { jsonPath, op: '<truthy>', value: null, caseSensetive: false };
}
const operator = readOperator();
@ -181,7 +181,7 @@ export function parseComponentSelector(selector: string): ParsedComponentSelecto
eat1();
if (operator !== '=' && typeof value !== 'string')
throw new Error(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);
return {jsonPath, op: operator, value, caseSensetive};
return { jsonPath, op: operator, value, caseSensetive };
}
const result: ParsedComponentSelector = {

2
src/server/dom.ts

@ -277,7 +277,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
const [quads, metrics] = await Promise.all([
this._page._delegate.getContentQuads(this),
this._page.mainFrame()._utilityContext().then(utility => utility.evaluate(() => ({width: innerWidth, height: innerHeight}))),
this._page.mainFrame()._utilityContext().then(utility => utility.evaluate(() => ({ width: innerWidth, height: innerHeight }))),
] as const);
if (!quads || !quads.length)
return 'error:notvisible';

2
src/server/electron/electron.ts

@ -26,7 +26,7 @@ import { TimeoutSettings } from '../../utils/timeoutSettings';
import { WebSocketTransport } from '../transport';
import { launchProcess, envArrayToObject } from '../../utils/processLauncher';
import { BrowserContext } from '../browserContext';
import type {BrowserWindow} from 'electron';
import type { BrowserWindow } from 'electron';
import { Progress, ProgressController } from '../progress';
import { helper } from '../helper';
import { eventsHelper } from '../../utils/eventsHelper';

4
src/server/fetch.ts

@ -91,7 +91,7 @@ export abstract class FetchRequest extends SdkObject {
headers['accept-encoding'] = 'gzip,deflate,br';
if (defaults.extraHTTPHeaders) {
for (const {name, value} of defaults.extraHTTPHeaders)
for (const { name, value } of defaults.extraHTTPHeaders)
headers[name.toLowerCase()] = value;
}
@ -235,7 +235,7 @@ export abstract class FetchRequest extends SdkObject {
const auth = response.headers['www-authenticate'];
const credentials = this._defaultOptions().httpCredentials;
if (auth?.trim().startsWith('Basic ') && credentials) {
const {username, password} = credentials;
const { username, password } = credentials;
const encoded = Buffer.from(`${username || ''}:${password || ''}`).toString('base64');
options.headers!['authorization'] = `Basic ${encoded}`;
fulfill(this._sendRequest(url, options, postData));

4
src/server/firefox/ffBrowser.ts

@ -106,7 +106,7 @@ export class FFBrowser extends Browser {
}
_onAttachedToTarget(payload: Protocol.Browser.attachedToTargetPayload) {
const {targetId, browserContextId, openerId, type} = payload.targetInfo;
const { targetId, browserContextId, openerId, type } = payload.targetInfo;
assert(type === 'page');
const context = browserContextId ? this._contexts.get(browserContextId)! : this._defaultContext as FFBrowserContext;
assert(context, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`);
@ -290,7 +290,7 @@ export class FFBrowserContext extends BrowserContext {
throw new Error('Unknown permission: ' + permission);
return protocolPermission;
});
await this._browser._connection.send('Browser.grantPermissions', { origin: origin, browserContextId: this._browserContextId, permissions: filtered});
await this._browser._connection.send('Browser.grantPermissions', { origin: origin, browserContextId: this._browserContextId, permissions: filtered });
}
async _doClearPermissions() {

10
src/server/firefox/ffConnection.ts

@ -75,9 +75,9 @@ export class FFConnection extends EventEmitter {
): Promise<Protocol.CommandReturnValues[T]> {
this._checkClosed(method);
const id = this.nextMessageId();
this._rawSend({id, method, params});
this._rawSend({ id, method, params });
return new Promise((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, error: new ProtocolError(false), method});
this._callbacks.set(id, { resolve, reject, error: new ProtocolError(false), method });
});
}
@ -141,7 +141,7 @@ export class FFConnection extends EventEmitter {
}
createSession(sessionId: string): FFSession {
const session = new FFSession(this, sessionId, message => this._rawSend({...message, sessionId}));
const session = new FFSession(this, sessionId, message => this._rawSend({ ...message, sessionId }));
this._sessions.set(sessionId, session);
return session;
}
@ -193,9 +193,9 @@ export class FFSession extends EventEmitter {
if (this._disposed)
throw new ProtocolError(true, 'Target closed');
const id = this._connection.nextMessageId();
this._rawSend({method, params, id});
this._rawSend({ method, params, id });
return new Promise((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, error: new ProtocolError(false), method});
this._callbacks.set(id, { resolve, reject, error: new ProtocolError(false), method });
});
}

2
src/server/firefox/ffExecutionContext.ts

@ -111,7 +111,7 @@ function checkException(exceptionDetails?: Protocol.Runtime.ExceptionDetails) {
function rewriteError(error: Error): (Protocol.Runtime.evaluateReturnValue | Protocol.Runtime.callFunctionReturnValue) {
if (error.message.includes('cyclic object value') || error.message.includes('Object is not serializable'))
return {result: {type: 'undefined', value: undefined}};
return { result: { type: 'undefined', value: undefined } };
if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON'))
rewriteErrorMessage(error, error.message + ' Are you passing a nested JSHandle?');
if (!js.isJavaScriptErrorInEvaluate(error) && !isSessionClosedError(error))

2
src/server/firefox/ffNetworkManager.ts

@ -50,7 +50,7 @@ export class FFNetworkManager {
}
async setRequestInterception(enabled: boolean) {
await this._session.send('Network.setRequestInterception', {enabled});
await this._session.send('Network.setRequestInterception', { enabled });
}
_onRequestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) {

12
src/server/firefox/ffPage.ts

@ -152,7 +152,7 @@ export class FFPage implements PageDelegate {
}
_onExecutionContextCreated(payload: Protocol.Runtime.executionContextCreatedPayload) {
const {executionContextId, auxData} = payload;
const { executionContextId, auxData } = payload;
const frame = this._page._frameManager.frame(auxData.frameId!);
if (!frame)
return;
@ -169,7 +169,7 @@ export class FFPage implements PageDelegate {
}
_onExecutionContextDestroyed(payload: Protocol.Runtime.executionContextDestroyedPayload) {
const {executionContextId} = payload;
const { executionContextId } = payload;
const context = this._contextIdToContext.get(executionContextId);
if (!context)
return;
@ -220,7 +220,7 @@ export class FFPage implements PageDelegate {
}
_onEventFired(payload: Protocol.Page.eventFiredPayload) {
const {frameId, name} = payload;
const { frameId, name } = payload;
if (name === 'load')
this._page._frameManager.frameLifecycleEvent(frameId, 'load');
if (name === 'DOMContentLoaded')
@ -236,7 +236,7 @@ export class FFPage implements PageDelegate {
}
_onConsole(payload: Protocol.Runtime.consolePayload) {
const {type, args, executionContextId, location} = payload;
const { type, args, executionContextId, location } = payload;
const context = this._contextIdToContext.get(executionContextId)!;
this._page._addConsoleMessage(type, args.map(arg => context.createHandle(arg)), location);
}
@ -260,7 +260,7 @@ export class FFPage implements PageDelegate {
}
async _onFileChooserOpened(payload: Protocol.Page.fileChooserOpenedPayload) {
const {executionContextId, element} = payload;
const { executionContextId, element } = payload;
const context = this._contextIdToContext.get(executionContextId)!;
const handle = context.createHandle(element).asElement()!;
await this._page._onFileChooserOpened(handle);
@ -284,7 +284,7 @@ export class FFPage implements PageDelegate {
worker._createExecutionContext(new FFExecutionContext(workerSession, event.executionContextId));
});
workerSession.on('Runtime.console', event => {
const {type, args, location} = event;
const { type, args, location } = event;
const context = worker._existingExecutionContext!;
this._page._addConsoleMessage(type, args.map(arg => context.createHandle(arg)), location);
});

2
src/server/frames.ts

@ -1336,7 +1336,7 @@ export class Frame extends SdkObject {
async extendInjectedScript(source: string, arg?: any): Promise<js.JSHandle> {
const context = await this._context('main');
const injectedScriptHandle = await context.injectedScript();
return injectedScriptHandle.evaluateHandle((injectedScript, {source, arg}) => {
return injectedScriptHandle.evaluateHandle((injectedScript, { source, arg }) => {
return injectedScript.extend(source, arg);
}, { source, arg });
}

2
src/server/injected/reactSelectorEngine.ts

@ -155,7 +155,7 @@ function findReactRoots(): ReactVNode[] {
export const ReactEngine: SelectorEngine = {
queryAll(scope: SelectorRoot, selector: string): Element[] {
const {name, attributes} = parseComponentSelector(selector);
const { name, attributes } = parseComponentSelector(selector);
const reactRoots = findReactRoots();
const trees = reactRoots.map(reactRoot => buildComponentsTree(reactRoot));

4
src/server/injected/vueSelectorEngine.ts

@ -210,7 +210,7 @@ function findVueRoots(): VueRoot[] {
// Vue3 roots are marked with [data-v-app] attribute
for (const node of document.querySelectorAll('[data-v-app]')) {
if ((node as any)._vnode && (node as any)._vnode.component)
roots.push({root: (node as any)._vnode.component, version: 3});
roots.push({ root: (node as any)._vnode.component, version: 3 });
}
// Vue2 roots are referred to from elements.
const walker = document.createTreeWalker(document, NodeFilter.SHOW_ELEMENT);
@ -231,7 +231,7 @@ function findVueRoots(): VueRoot[] {
export const VueEngine: SelectorEngine = {
queryAll(scope: SelectorRoot, selector: string): Element[] {
const {name, attributes} = parseComponentSelector(selector);
const { name, attributes } = parseComponentSelector(selector);
const vueRoots = findVueRoots();
const trees = vueRoots.map(vueRoot => vueRoot.version === 3 ? buildComponentsTreeVue3(vueRoot.root) : buildComponentsTreeVue2(vueRoot.root));
const treeNodes = trees.map(tree => filterComponentsTree(tree, treeNode => {

2
src/server/javascript.ts

@ -132,7 +132,7 @@ export class JSHandle<T = any> extends SdkObject {
async getProperty(propertyName: string): Promise<JSHandle> {
const objectHandle = await this.evaluateHandle((object: any, propertyName) => {
const result: any = {__proto__: null};
const result: any = { __proto__: null };
result[propertyName] = object[propertyName];
return result;
}, propertyName);

2
src/server/network.ts

@ -54,7 +54,7 @@ export function rewriteCookies(cookies: types.SetNetworkCookieParam[]): types.Se
assert(c.url || (c.domain && c.path), 'Cookie should have a url or a domain/path pair');
assert(!(c.url && c.domain), 'Cookie should have either url or domain');
assert(!(c.url && c.path), 'Cookie should have either url or path');
const copy = {...c};
const copy = { ...c };
if (copy.url) {
assert(copy.url !== 'about:blank', `Blank page can not have cookie "${c.name}"`);
assert(!copy.url.startsWith('data:'), `Data URL page can not have cookie "${c.name}"`);

8
src/server/page.ts

@ -556,7 +556,7 @@ export class PageBinding {
}
static async dispatch(page: Page, payload: string, context: dom.FrameExecutionContext) {
const {name, seq, args} = JSON.parse(payload);
const { name, seq, args } = JSON.parse(payload);
try {
assert(context.world);
const binding = page.getBinding(name)!;
@ -620,12 +620,12 @@ function addPageBinding(bindingName: string, needsHandle: boolean) {
handles = new Map();
me['handles'] = handles;
}
const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));
const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));
if (needsHandle) {
handles.set(seq, args[0]);
binding(JSON.stringify({name: bindingName, seq}));
binding(JSON.stringify({ name: bindingName, seq }));
} else {
binding(JSON.stringify({name: bindingName, seq, args}));
binding(JSON.stringify({ name: bindingName, seq, args }));
}
return promise;
};

2
src/server/screenshotter.ts

@ -140,7 +140,7 @@ export class Screenshotter {
progress.throwIfAborted(); // Screenshotting is expensive - avoid extra work.
const shouldSetDefaultBackground = options.omitBackground && format === 'png';
if (shouldSetDefaultBackground) {
await this._page._delegate.setBackgroundColor({ r: 0, g: 0, b: 0, a: 0});
await this._page._delegate.setBackgroundColor({ r: 0, g: 0, b: 0, a: 0 });
progress.cleanupWhenAborted(() => this._page._delegate.setBackgroundColor());
}
progress.throwIfAborted(); // Avoid extra work.

2
src/server/webkit/webkit.ts

@ -42,7 +42,7 @@ export class WebKit extends BrowserType {
}
_attemptToGracefullyCloseBrowser(transport: ConnectionTransport): void {
transport.send({method: 'Playwright.close', params: {}, id: kBrowserCloseMessageId});
transport.send({ method: 'Playwright.close', params: {}, id: kBrowserCloseMessageId });
}
_defaultArgs(options: types.LaunchOptions, isPersistent: boolean, userDataDir: string): string[] {

4
src/server/webkit/wkAccessibility.ts

@ -21,7 +21,7 @@ import * as types from '../types';
export async function getAccessibilityTree(session: WKSession, needle?: dom.ElementHandle) {
const objectId = needle ? needle._objectId : undefined;
const {axNode} = await session.send('Page.accessibilitySnapshot', { objectId });
const { axNode } = await session.send('Page.accessibilitySnapshot', { objectId });
const tree = new WKAXNode(axNode);
return {
tree,
@ -127,7 +127,7 @@ class WKAXNode implements accessibility.AXNode {
}
isInteresting(insideControl: boolean): boolean {
const {role, focusable} = this._payload;
const { role, focusable } = this._payload;
const name = this._name();
if (role === 'ScrollArea')
return false;

2
src/server/webkit/wkConnection.ts

@ -138,7 +138,7 @@ export class WKSession extends EventEmitter {
const messageObj = { id, method, params };
this._rawSend(messageObj);
return new Promise<Protocol.CommandReturnValues[T]>((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, error: new ProtocolError(false), method});
this._callbacks.set(id, { resolve, reject, error: new ProtocolError(false), method });
});
}

6
src/server/webkit/wkPage.ts

@ -308,7 +308,7 @@ export class WKPage implements PageDelegate {
this._setSession(session);
await Promise.all([
this._initializePageProxySession(),
this._initializeSession(session, false, ({frameTree}) => this._handleFrameTree(frameTree)),
this._initializeSession(session, false, ({ frameTree }) => this._handleFrameTree(frameTree)),
]);
pageOrError = this._page;
} catch (e) {
@ -552,7 +552,7 @@ export class WKPage implements PageDelegate {
columnNumber: (columnNumber || 1) - 1,
}
};
this._onConsoleRepeatCountUpdated({ count: 1});
this._onConsoleRepeatCountUpdated({ count: 1 });
}
_onConsoleRepeatCountUpdated(event: Protocol.Console.messageRepeatCountUpdatedPayload) {
@ -983,7 +983,7 @@ export class WKPage implements PageDelegate {
_onRequestIntercepted(session: WKSession, event: Protocol.Network.requestInterceptedPayload) {
const request = this._requestIdToRequest.get(event.requestId);
if (!request) {
session.sendMayFail('Network.interceptRequestWithError', {errorType: 'Cancellation', requestId: event.requestId});
session.sendMayFail('Network.interceptRequestWithError', { errorType: 'Cancellation', requestId: event.requestId });
return;
}
if (!request._route) {

2
src/server/webkit/wkProvisionalPage.ts

@ -50,7 +50,7 @@ export class WKProvisionalPage {
eventsHelper.addEventListener(session, 'Network.loadingFailed', overrideFrameId(e => wkPage._onLoadingFailed(e))),
];
this.initializationPromise = this._wkPage._initializeSession(session, true, ({frameTree}) => this._handleFrameTree(frameTree));
this.initializationPromise = this._wkPage._initializeSession(session, true, ({ frameTree }) => this._handleFrameTree(frameTree));
}
dispose() {

2
src/test/dispatcher.ts

@ -364,7 +364,7 @@ export class Dispatcher {
pair.result.stderr.push(chunk);
this._reporter.onStdErr?.(chunk, pair?.test, pair?.result);
});
worker.on('teardownError', ({error}) => {
worker.on('teardownError', ({ error }) => {
this._hasWorkerErrors = true;
this._reporter.onError?.(error);
});

2
src/test/reporters/base.ts

@ -285,7 +285,7 @@ function positionInFile(stackLines: string[], file: string): { column: number; l
if (!parsed || !parsed.file)
continue;
if (path.resolve(process.cwd(), parsed.file) === file)
return {column: parsed.column || 0, line: parsed.line || 0};
return { column: parsed.column || 0, line: parsed.line || 0 };
}
}

2
src/test/reporters/junit.ts

@ -131,7 +131,7 @@ class JUnitReporter implements Reporter {
entries.push(entry);
if (test.outcome() === 'skipped') {
entry.children.push({ name: 'skipped'});
entry.children.push({ name: 'skipped' });
return;
}

2
src/test/runner.ts

@ -338,7 +338,7 @@ function filterOnly(suite: Suite) {
}
function filterByFocusedLine(suite: Suite, focusedTestFileLines: FilePatternFilter[]) {
const testFileLineMatches = (testFileName: string, testLine: number) => focusedTestFileLines.some(({re, line}) => {
const testFileLineMatches = (testFileName: string, testLine: number) => focusedTestFileLines.some(({ re, line }) => {
re.lastIndex = 0;
return re.test(testFileName) && (line === testLine || line === null);
});

2
src/test/transform.ts

@ -92,7 +92,7 @@ export function installTransform(): () => void {
sourceMaps: 'both',
} as babel.TransformOptions)!;
if (result.code) {
fs.mkdirSync(path.dirname(cachePath), {recursive: true});
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
if (result.map)
fs.writeFileSync(sourceMapPath, JSON.stringify(result.map), 'utf8');
fs.writeFileSync(codePath, result.code, 'utf8');

4
src/utils/browserFetcher.ts

@ -55,7 +55,7 @@ export async function downloadBrowserWithProgressBar(title: string, browserDirec
try {
for (let attempt = 1, N = 3; attempt <= N; ++attempt) {
debugLogger.log('install', `downloading ${progressBarName} - attempt #${attempt}`);
const {error} = await downloadFile(url, zipPath, {progressCallback: progress, log: debugLogger.log.bind(debugLogger, 'install')});
const { error } = await downloadFile(url, zipPath, { progressCallback: progress, log: debugLogger.log.bind(debugLogger, 'install') });
if (!error) {
debugLogger.log('install', `SUCCESS downloading ${progressBarName}`);
break;
@ -74,7 +74,7 @@ export async function downloadBrowserWithProgressBar(title: string, browserDirec
debugLogger.log('install', `extracting archive`);
debugLogger.log('install', `-- zip: ${zipPath}`);
debugLogger.log('install', `-- location: ${browserDirectory}`);
await extract(zipPath, { dir: browserDirectory});
await extract(zipPath, { dir: browserDirectory });
debugLogger.log('install', `fixing permissions at ${executablePath}`);
await fs.promises.chmod(executablePath, 0o755);
} catch (e) {

8
src/utils/dependencies.ts

@ -39,7 +39,7 @@ export type DependencyGroup = 'chromium' | 'firefox' | 'webkit' | 'tools';
export async function installDependenciesWindows(targets: Set<DependencyGroup>) {
if (targets.has('chromium')) {
const {code} = await utils.spawnAsync('powershell.exe', [path.join(BIN_DIRECTORY, 'install_media_pack.ps1')], { cwd: BIN_DIRECTORY, stdio: 'inherit' });
const { code } = await utils.spawnAsync('powershell.exe', [path.join(BIN_DIRECTORY, 'install_media_pack.ps1')], { cwd: BIN_DIRECTORY, stdio: 'inherit' });
if (code !== 0)
throw new Error('Failed to install windows dependencies!');
}
@ -255,7 +255,7 @@ async function executablesOrSharedLibraries(directoryPath: string): Promise<stri
async function missingFileDependenciesWindows(filePath: string): Promise<Array<string>> {
const executable = path.join(__dirname, '..', '..', 'bin', 'PrintDeps.exe');
const dirname = path.dirname(filePath);
const {stdout, code} = await utils.spawnAsync(executable, [filePath], {
const { stdout, code } = await utils.spawnAsync(executable, [filePath], {
cwd: dirname,
env: {
...process.env,
@ -273,7 +273,7 @@ async function missingFileDependencies(filePath: string, extraLDPaths: string[])
let LD_LIBRARY_PATH = extraLDPaths.join(':');
if (process.env.LD_LIBRARY_PATH)
LD_LIBRARY_PATH = `${process.env.LD_LIBRARY_PATH}:${LD_LIBRARY_PATH}`;
const {stdout, code} = await utils.spawnAsync('ldd', [filePath], {
const { stdout, code } = await utils.spawnAsync('ldd', [filePath], {
cwd: dirname,
env: {
...process.env,
@ -292,7 +292,7 @@ async function missingDLOPENLibraries(libraries: string[]): Promise<string[]> {
// NOTE: Using full-qualified path to `ldconfig` since `/sbin` is not part of the
// default PATH in CRON.
// @see https://github.com/microsoft/playwright/issues/3397
const {stdout, code, error} = await utils.spawnAsync('/sbin/ldconfig', ['-p'], {});
const { stdout, code, error } = await utils.spawnAsync('/sbin/ldconfig', ['-p'], {});
if (code !== 0 || error)
return [];
const isLibraryAvailable = (library: string) => stdout.toLowerCase().includes(library.toLowerCase());

4
src/utils/registry.ts

@ -615,8 +615,8 @@ export class Registry {
}[channel];
const product = products.find((product: any) => product.Product === productName);
const searchConfig = ({
darwin: {platform: 'MacOS', arch: 'universal', artifact: 'pkg'},
win32: {platform: 'Windows', arch: os.arch() === 'x64' ? 'x64' : 'x86', artifact: 'msi'},
darwin: { platform: 'MacOS', arch: 'universal', artifact: 'pkg' },
win32: { platform: 'Windows', arch: os.arch() === 'x64' ? 'x64' : 'x86', artifact: 'msi' },
} as any)[process.platform];
const release = searchConfig ? product.Releases.find((release: any) => release.Platform === searchConfig.platform && release.Architecture === searchConfig.arch) : null;
const artifact = release ? release.Artifacts.find((artifact: any) => artifact.ArtifactName === searchConfig.artifact) : null;

18
src/utils/utils.ts

@ -123,7 +123,7 @@ export function downloadFile(url: string, destinationPath: string, options: {pro
log(`running download:`);
log(`-- from url: ${url}`);
log(`-- to location: ${destinationPath}`);
let fulfill: ({error}: {error: any}) => void = ({error}) => {};
let fulfill: ({ error }: {error: any}) => void = ({ error }) => {};
let downloadedBytes = 0;
let totalBytes = 0;
@ -135,18 +135,18 @@ export function downloadFile(url: string, destinationPath: string, options: {pro
const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
// consume response data to free up memory
response.resume();
fulfill({error});
fulfill({ error });
return;
}
const file = fs.createWriteStream(destinationPath);
file.on('finish', () => fulfill({error: null}));
file.on('error', error => fulfill({error}));
file.on('finish', () => fulfill({ error: null }));
file.on('error', error => fulfill({ error }));
response.pipe(file);
totalBytes = parseInt(response.headers['content-length'] || '0', 10);
log(`-- total bytes: ${totalBytes}`);
if (progressCallback)
response.on('data', onData);
}, (error: any) => fulfill({error}));
}, (error: any) => fulfill({ error }));
return promise;
function onData(chunk: string) {
@ -165,8 +165,8 @@ export function spawnAsync(cmd: string, args: string[], options?: SpawnOptions):
process.stdout.on('data', data => stdout += data);
if (process.stderr)
process.stderr.on('data', data => stderr += data);
process.on('close', code => resolve({stdout, stderr, code}));
process.on('error', error => resolve({stdout, stderr, code: 0, error}));
process.on('close', code => resolve({ stdout, stderr, code }));
process.on('error', error => resolve({ stdout, stderr, code: 0, error }));
});
}
@ -265,7 +265,7 @@ export function getAsBooleanFromENV(name: string): boolean {
export async function mkdirIfNeeded(filePath: string) {
// This will harmlessly throw on windows if the dirname is the root directory.
await fs.promises.mkdir(path.dirname(filePath), {recursive: true}).catch(() => {});
await fs.promises.mkdir(path.dirname(filePath), { recursive: true }).catch(() => {});
}
type HeadersArray = { name: string, value: string }[];
@ -326,7 +326,7 @@ export function arrayToObject(array?: NameValue[]): { [key: string]: string } |
if (!array)
return undefined;
const result: { [key: string]: string } = {};
for (const {name, value} of array)
for (const { name, value } of array)
result[name] = value;
return result;
}

2
src/web/components/expandable.tsx

@ -27,7 +27,7 @@ export const Expandable: React.FunctionComponent<{
<div className='expandable-title' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', whiteSpace: 'nowrap' }}>
<div
className={'codicon codicon-' + (expanded ? 'chevron-down' : 'chevron-right')}
style={{ cursor: 'pointer', color: 'var(--color)', marginRight: '4px'}}
style={{ cursor: 'pointer', color: 'var(--color)', marginRight: '4px' }}
onClick={() => setExpanded(