Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
response.end(img);
track('screenshot', now() - start);
} catch (err) {
response.status(400).send('Cannot render requested URL');
console.error('Cannot render requested URL');
console.error(err);
}
});
app.get('/_ah/health', (request, response) => response.send('OK'));
app.stop = async() => {
await config.chrome.kill();
};
const appPromise = chromeLauncher.launch({
chromeFlags: ['--headless', '--disable-gpu', '--remote-debugging-address=0.0.0.0'],
port: 0
}).then((chrome) => {
console.log('Chrome launched with debugging on port', chrome.port);
config.chrome = chrome;
config.port = chrome.port;
// Don't open a port when running from inside a module (eg. tests). Importing
// module can control this.
if (!module.parent) {
app.listen(PORT, function() {
console.log('Listening on port', PORT);
});
}
return app;
}).catch((error) => {
console.error(error);
const chromeFlags = [];
let startingUrl;
let port;
let ignoreDefaultFlags;
if (args.length) {
const providedFlags = args.filter(flag => flag.startsWith('--'));
const portFlag = providedFlags.find(flag => flag.startsWith('--port='));
if (portFlag) port = parseInt(portFlag.replace('--port=', ''), 10);
const enableExtensions = !!providedFlags.find(flag => flag === '--enable-extensions');
// The basic pattern for enabling Chrome extensions
if (enableExtensions) {
ignoreDefaultFlags = true;
chromeFlags.push(...Launcher.defaultFlags().filter(flag => flag !== '--disable-extensions'));
}
chromeFlags.push(...providedFlags);
startingUrl = args.find(flag => !flag.startsWith('--'));
}
launch({
startingUrl,
port,
ignoreDefaultFlags,
chromeFlags,
})
// eslint-disable-next-line no-console
.then(v => console.log(`✨ Chrome debugging port: ${v.port}`));
function runLighthouse({ targetUrl }) {
const chromeFlags = [
'--headless',
'--no-sandbox', // chrome sandboxing requires docker container to have the
// `SYS_ADMIN` capability added which is not supported by GitHub actions
];
return chromeLauncher.launch({ chromeFlags }).then(chrome => {
const opts = {
port: chrome.port,
output: 'html',
};
const config = null;
return lighthouse(targetUrl, opts, config).then(results => {
// use results.lhr for the JS-consumable output
// https://github.com/GoogleChrome/lighthouse/blob/master/types/lhr.d.ts
// use results.report for the HTML/JSON/CSV output as a string
// use results.artifacts for the trace/screenshots/other specific case you need (rarer)
return chrome.kill().then(() => results);
});
});
}
async function launchChromeAndRunLighthouse(url, opts, config) {
// eslint-disable-next-line no-unused-vars
const chrome = await chromeLauncher.launch({
port: 9222,
logLevel: 'silent',
chromeFlags: ['--headless', '--disable-gpu'],
});
const browser = await puppeteer.connect({
browserURL: 'http://localhost:9222',
});
browser.on('targetchanged', async target => {
const page = await target.page();
if (NETWORK[opts.connection]) {
await page
.target()
.createCDPSession()
const chromeFlags = [...DEFAULT_CHROME_FLAGS, ...flags]
if (!chromeInstance) {
if (process.env.AWS_EXECUTION_ENV || forceLambdaLauncher) {
chromeInstance = new LambdaChromeLauncher({
chromePath,
chromeFlags,
port,
})
} else {
// This let's us use chrome-launcher in local development,
// but omit it from the lambda function's zip artefact
try {
// eslint-disable-next-line
const { Launcher: LocalChromeLauncher } = require('chrome-launcher')
chromeInstance = new LocalChromeLauncher({ chromePath, chromeFlags: flags, port })
} catch (error) {
throw new Error('@serverless-chrome/lambda: Unable to find "chrome-launcher". ' +
"Make sure it's installed if you wish to develop locally.")
}
}
}
debug('Spawning headless shell')
const launchStartTime = Date.now()
try {
await chromeInstance.launch()
} catch (error) {
debug('Error trying to spawn chrome:', error)
static async getChromeExecutablePath(stable) {
if (!stable) {
const launcher = importCwd.silent('puppeteer');
if (!launcher) {
throw new Error(
'Cannot find Chromium. Make sure you have puppeteer installed',
);
}
const exePath = launcher.executablePath();
return exePath;
}
const installations = await chromeFinder[getPlatform()]();
if (installations.length === 0) {
throw new Error('Chrome not installed');
}
return installations.pop(); // If you have multiple installed chromes return regular chrome
}
static async getChromeExecutablePath(stable) {
if (!stable) {
const launcher = importCwd.silent('puppeteer');
if (!launcher) {
throw new Error(
'Cannot find Chromium. Make sure you have puppeteer installed',
);
}
const exePath = launcher.executablePath();
return exePath;
}
const installations = await chromeFinder[getPlatform()]();
if (installations.length === 0) {
throw new Error('Chrome not installed');
}
return installations.pop(); // If you have multiple installed chromes return regular chrome
}
export type ChromiumExtensionRunnerParams = {|
...ExtensionRunnerParams,
// Chromium desktop CLI params.
...ChromiumSpecificRunnerParams,
|};
const log = createLogger(__filename);
const asyncMkdirp = promisify(mkdirp);
const EXCLUDED_CHROME_FLAGS = [
'--disable-extensions',
'--mute-audio',
];
export const DEFAULT_CHROME_FLAGS = ChromeLauncher.defaultFlags()
.filter((flag) => !EXCLUDED_CHROME_FLAGS.includes(flag));
/**
* Implements an IExtensionRunner which manages a Chromium instance.
*/
export class ChromiumExtensionRunner {
cleanupCallbacks: Set;
params: ChromiumExtensionRunnerParams;
chromiumInstance: LaunchedChrome;
chromiumLaunch: typeof defaultChromiumLaunch;
reloadManagerExtension: string;
wss: WebSocket.Server;
exiting: boolean;
_promiseSetupDone: ?Promise;
constructor(params: ChromiumExtensionRunnerParams) {
const finder: (() => string[]) | undefined = (() => {
// Use already known path within Marp CLI official Docker image
if (process.env.IS_DOCKER) return () => ['/usr/bin/chromium-browser']
// Use Chrome installed to Windows within WSL
if (isWSL()) return chromeFinder.wsl
return chromeFinder[process.platform]
})()
function launchChromeAndRunLighthouse(url, flags, config) {
return chromeLauncher.launch(CHROME_LAUNCH_OPTS).then(chrome => {
flags.port = chrome.port;
return lighthouse(url, flags, config).
then(results => chrome.kill().then(() => results)).
catch(err => chrome.kill().then(() => { throw err; }, () => { throw err; }));
});
}