Skip to content

Commit

Permalink
chore: Improved VSCode debug
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Mar 4, 2023
1 parent 1ac06c3 commit 9f4b1d1
Show file tree
Hide file tree
Showing 5 changed files with 238 additions and 27 deletions.
42 changes: 37 additions & 5 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,49 @@
// Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Chrome",
"request": "launch",
"type": "chrome",
"url": "about:blank",
"disableNetworkCache": true,
"webRoot": "${workspaceFolder}",
"userDataDir": "${workspaceFolder}/userDataDir",
"port": 9222,
"runtimeArgs": ["--auto-open-devtools-for-tabs"],
"pathMapping": {
"webpack:///./~/*": "${workspaceFolder}/node_modules/*",
"webpack:////*": "/*",
"webpack://?:*/*": "${workspaceFolder}/*",
"webpack:///([a-z]):/(.+)": "$1:/$2",
"/dist": "${workspaceFolder}/dist",
"/": "${workspaceFolder}/wa-source"
}
},
{
"type": "node",
"request": "launch",
"name": "Launch Browser",
"name": "Debug Chrome",
"presentation": {
"hidden": false,
"group": "Other",
"order": 2
},
"preLaunchTask": "npm: watch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "launch:attach"]
},
{
"type": "node",
"request": "launch",
"name": "Launch Browser",
"presentation": {
"hidden": false,
"group": "Other Old",
"order": 2
},
"preLaunchTask": "npm: watch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"launch:local",
Expand All @@ -23,12 +55,12 @@
]
},
{
"type": "pwa-chrome",
"type": "chrome",
"request": "attach",
"name": "Attach Browser",
"presentation": {
"hidden": false,
"group": "Other",
"group": "Other Old",
"order": 2
},
"address": "127.0.0.1",
Expand All @@ -48,13 +80,13 @@
],
"compounds": [
{
"name": "Launch and debug",
"name": "Launch and Debug",
"presentation": {
"hidden": false,
"group": "Launch",
"order": 1
},
"configurations": ["Launch Browser", "Attach Browser"]
"configurations": ["Launch Chrome", "Debug Chrome"]
}
]
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"docs:build": "npm run docs:clean && npm run docs:theme && typedoc --gitRevision main",
"docs:clean": "shx rm -rf docs",
"docs:theme": "cd ./docs-source && tsc",
"launch:attach": "ts-node ./src/tools/launchAttach.ts",
"launch:local": "ts-node ./src/tools/launchLocal.ts",
"launch:protocol-log": "ts-node ./src/tools/launchProtocolLog.ts",
"lint": "npx eslint --ext .ts src",
Expand Down
48 changes: 26 additions & 22 deletions src/tools/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,7 @@ type LaunchArguments = Parameters<
typeof playwright.chromium.launchPersistentContext
>;

export async function getPage(options?: LaunchArguments[1]) {
let userDataDir = path.resolve(__dirname, '../../userDataDir');
if (Array.isArray(options?.args)) {
const index = options?.args.findIndex((a) =>
a.startsWith('--user-data-dir')
);
if (typeof index === 'number' && index > -1) {
const param = options?.args[index];
options?.args.splice(index, 1);
userDataDir = param?.split('=')[1] || userDataDir;
}
}

const browser = await playwright.chromium.launchPersistentContext(
userDataDir,
options
);

const page = browser.pages().length
? browser.pages()[0]
: await browser.newPage();

export async function preparePage(page: playwright.Page) {
page.route('https://crashlogs.whatsapp.net/**', (route) => {
route.abort();
});
Expand Down Expand Up @@ -145,6 +124,31 @@ export async function getPage(options?: LaunchArguments[1]) {
);
});
});
}

export async function getPage(options?: LaunchArguments[1]) {
let userDataDir = path.resolve(__dirname, '../../userDataDir');
if (Array.isArray(options?.args)) {
const index = options?.args.findIndex((a) =>
a.startsWith('--user-data-dir')
);
if (typeof index === 'number' && index > -1) {
const param = options?.args[index];
options?.args.splice(index, 1);
userDataDir = param?.split('=')[1] || userDataDir;
}
}

const browser = await playwright.chromium.launchPersistentContext(
userDataDir,
options
);

const page = browser.pages().length
? browser.pages()[0]
: await browser.newPage();

await preparePage(page);

setTimeout(async () => {
await page.goto(URL, {
Expand Down
107 changes: 107 additions & 0 deletions src/tools/extractWhatsappSource copy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as waVersion from '@wppconnect/wa-version';
import * as fs from 'fs';
import * as path from 'path';
import * as prettier from 'prettier';

import * as wpp from '../';
import { getPage, WA_DIR } from './browser';

declare global {
interface Window {
WPP: typeof wpp;
}
}

const WA_VERSION = process.env['WA_VERSION'] || waVersion.getLatestVersion();

async function start() {
const args = process.argv.slice(2);

if (!fs.existsSync(WA_DIR)) {
fs.mkdirSync(WA_DIR);
}

const options = await prettier.resolveConfig(process.cwd());

const { browser, page } = await getPage({
args,
});

const downloads: Promise<void>[] = [];

page.on('response', async (response) => {
const contentType = response.headers()['content-type'] || '';

if (!contentType.startsWith('application/javascript')) {
return;
}

const url = response.url();
const fileName = path.basename(url, '.js') + '.js';
const filePath = path.join(WA_DIR, fileName);

if (fs.existsSync(filePath)) {
return;
}

let resolve: any = null;
downloads.push(
new Promise((r) => {
resolve = r;
})
);

console.log('Downloading: ', fileName);

const body = await response.body();

let content = body.toString('utf8');

content = content.replace(/([ ,:;=>(){}[\]|&])!1\b/g, '$1false');
content = content.replace(/([ ,:;=>(){}[\]|&])!0\b/g, '$1true');
content = content.replace(/\b(return|case)\s*!1\b/g, '$1 false');
content = content.replace(/\b(return|case)\s*!0\b/g, '$1 true');
content = content.replace(/\bvoid 0\b/g, 'undefined');
// Remove sourcemap because it not exists in production
content = content.replace(/\/\/# sourceMappingURL.*/g, '');

content = prettier.format(content, {
...options!,
parser: 'espree',
printWidth: 120,
});

content = `/*! WhatsApp Version: ${WA_VERSION} */\n` + content;

fs.writeFileSync(filePath, content, { encoding: 'utf8' });

resolve?.();
});

await page.waitForFunction(() => window.WPP?.isReady, null, {
timeout: 0,
});

await new Promise((resolve) => setTimeout(resolve, 5000));

await Promise.all(downloads);

await browser.close();
}
start();
67 changes: 67 additions & 0 deletions src/tools/launchAttach.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as playwright from 'playwright-chromium';

import { preparePage, URL } from './browser';

async function start() {
console.log('Connecting to Chrome');
const browser = await playwright.chromium.connectOverCDP(
'http://localhost:9222'
);
console.log('Connected');

const context = browser.contexts()[0];

const page = context.pages().length
? context.pages()[0]
: await context.newPage();

console.log('Preparing page');
await preparePage(page);

setTimeout(async () => {
console.log('Opening WhatsApp WEB');
await page.goto(URL, {
waitUntil: 'domcontentloaded',
timeout: 120000,
});

await page
.waitForFunction(
() => (window as any).Debug?.VERSION,
{},
{ timeout: 120000 }
)
.catch(() => null);

const version = await page
.evaluate(() => (window as any).Debug.VERSION)
.catch(() => null);

console.log('WhatsApp Version: ', version);
}, 1000);

page.on('load', (page) => {
const debug = process.env['DEBUG'] || '*';

page.evaluate((debug: string) => {
localStorage.setItem('debug', debug);
}, debug);
});
}
start();

0 comments on commit 9f4b1d1

Please sign in to comment.