Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
///
///
const fs = require('fs'),
jsdom = require('jsdom'),
sinon = require('sinon'),
glob = require('glob'),
path = require('path')
const {JSDOM} = jsdom
const virtualConsole = new jsdom.VirtualConsole()
virtualConsole.sendTo(console, {omitJSDOMErrors: true})
import * as chai from 'chai'
chai.should()
chai.use(require('sinon-chai'))
const mockResponse = (server, url, file) => {
const ok = [200, { 'Content-type': 'application/json' }, fs.readFileSync(file, 'utf8')]
server.respondWith('GET', url, ok)
server.respondWith('POST', url, ok)
server.respondWith('DELETE', url, ok)
server.respondWith('PUT', url, ok)
}
const htmlSource = fs.readFileSync('test/pages/application.html', 'utf8')
function mockify(html = '') {
// Start of message that we want to suppress.
let msg =
'Error: Not implemented: HTMLCanvasElement.prototype.getContext' +
' (without installing the canvas npm package)'
// Override default virtual console of jsdom
const virtualConsole = new jsdom.VirtualConsole()
// Set up a simple 'mock' console output. Only 'error' needs to be overridden
let myConsole = {
error: msg => {
if (msg.indexOf(msg) === 0) {
//console.error('all is well');
} else {
// All other messages pass through
console.error(msg)
}
}
}
// Using the global catch instead of specific event handler, because I couldn't get them to work
virtualConsole.sendTo(myConsole)
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* setup.js */
import {JSDOM, VirtualConsole} from 'jsdom';
import global from 'global';
const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(console);
const dom = new JSDOM('', {
// JSDom 11.12 causes SecurityError: localStorage is not available for opaque origins
// https://github.com/jsdom/jsdom/issues/2304
url: 'http://localhost',
virtualConsole
});
const {window} = dom;
mockCanvas(window);
const nop = () => {};
function mockCanvas(globalWindow) {
globalWindow.HTMLCanvasElement.prototype.getContext = function mockGetContext() {
return {
await this.server.emitAsync(`fetch::end::${getType(mediaType!)}` as 'fetch::end::*', fetchEnd);
/*
* If the target is not an HTML we don't need to
* traverse it.
*/
/* istanbul ignore if */
if (!isHTMLDocument(this.finalHref, this.headers)) {
await this.server.emitAsync('scan::end', { resource: this.finalHref });
resolve();
return;
}
const virtualConsole = new VirtualConsole();
virtualConsole.on('error', (err: Error) => {
debug(`Console: ${err}`);
});
virtualConsole.on('jsdomError', (err) => {
debug(`Console: ${err}`);
});
const initialDocument = createHTMLDocument(fetchEnd.response.body.content, this.finalHref);
this._resourceLoader = new CustomResourceLoader(this, initialDocument);
const jsdom = new JSDOM(this._targetNetworkData.response.body.content, {
beforeParse: beforeParse(this.finalHref),
// includeNodeLocations: true, // TODO: re-enable once locations can be copied from snapshot.
return new Promise((resolve, reject) => {
const dom = new JSDOM('', {
runScripts: "outside-only",
// will not log browser events to console
virtualConsole: new jsdom.VirtualConsole()
})
const window = dom.window
const document = window.document
const Vue = loadVueIntoWindow(window)
// require a new instance of Tweet every time to avoid side-effects
const { Tweet, Moment, Timeline } = require('./dist')
// window and document needs to be global
// (required by vue's Ctor.$mount)
global.window = window
global.document = document
resolve({ Vue, Tweet, Moment, Timeline, window, document })
})
}
options.onScriptLoaded(url)
}
return data;
}
else {
return Buffer.from('')
// Let's just ignore any remote files.
// return super.fetch(url, fetchOptions);
}
}
}
let queue = []
let dom = new jsdom.JSDOM(html, {
virtualConsole: new jsdom.VirtualConsole().sendTo(console),
resources: new ResourceLoader(queue),
runScripts: "dangerously",
beforeParse(window) {
// Polyfill rAF for react
window.requestAnimationFrame = require('raf')
window.cancelAnimationFrame = require('raf').cancel
// jsdom seems to choke on webpack's tag loader,
// so I'm manually calling any onload handlers instead
// to avoid a deadlock.
// TODO: get links actually working.
let appendChild = window.HTMLHeadElement.prototype.appendChild
window.HTMLHeadElement.prototype.appendChild = function(...args) {
let result = appendChild.apply(this, args)
if (args[0] instanceof window.HTMLLinkElement && args[0].onload) {
if (args[0].rel === "stylesheet" && options.onStyleSheetLoaded) {
typesetConfig[jax] = (jax === config.output);
}
}
// generate css for html and svg outputs, if global css option is provided
if (config.cssInline && (typesetConfig['svg'] || typesetConfig['html'])) {
typesetConfig['css'] = true;
}
// Create jsdom options (cf. defaults for config.jsdom)
const jsdomConfig = {
runScripts: config.jsdom.runScript,
};
// translate 'true' option
if (config.jsdom.virtualConsole === true) {
config.jsdom.virtualConsole = new jsdom.VirtualConsole();
config.jsdom.virtualConsole.sendTo(console);
}
// set up DOM basics
const doc = typeof input === 'string' ? new JSDOM(input, config.jsdom) : input;
const window = doc.window;
const document = window.document;
//rewrite custom scripts types from core MathJax
const rewriteScripts = function(oldType, newType) {
const scripts = document.querySelectorAll('script[type="' + oldType + '"]');
for (let script of scripts) script.setAttribute('type', newType);
};
rewriteScripts('math/tex', 'math/inline-TeX');
rewriteScripts('math/tex; mode=display', 'math/TeX');
rewriteScripts('math/asciimath', 'math/asciiMath');
let dom, window, injectParent, injectNextSibling;
// A promise-like that never resolves and does not retain references to callbacks.
function BrokenPromise () {}
BrokenPromise.prototype.then = BrokenPromise.prototype.catch = BrokenPromise.prototype.finally = () => new BrokenPromise();
if (compilation.assets[compilation.options.output.filename]) {
// Get the compiled main bundle
const output = compilation.assets[compilation.options.output.filename].source();
// @TODO: provide a non-DOM option to allow turning off JSDOM entirely.
const tpl = options.templateContent || '';
dom = new jsdom.JSDOM(tpl.replace(PRERENDER_REG, '<div id="PRERENDER_INJECT"></div>'), {
// suppress console-proxied eval() errors, but keep console proxying
virtualConsole: new jsdom.VirtualConsole({ omitJSDOMErrors: false }).sendTo(console),
// `url` sets the value returned by `window.location`, `document.URL`...
// Useful for routers that depend on the current URL (such as react-router or reach-router)
url: options.documentUrl || 'http://localhost',
// don't track source locations for performance reasons
includeNodeLocations: false,
// don't allow inline event handlers & script tag exec
runScripts: 'outside-only'
});
window = dom.window;
// Find the placeholder node for injection & remove it
const injectPlaceholder = window.document.getElementById('PRERENDER_INJECT');
if (injectPlaceholder) {
exports.runEmfjs = function(source, callback, errorCallback) {
const virtualConsole = new jsdom.VirtualConsole();
virtualConsole.sendTo(console);
var dom = new JSDOM(`
/**
* @author EmmanuelOlaojo
* @since 11/18/17
*/
let jsdom = require("jsdom");
const {JSDOM} = jsdom;
const virtualConsole = new jsdom.VirtualConsole();
const OG_PROP = "property";
const TWITTER_PROP = "name";
const CONTENT = "content";
virtualConsole.sendTo(console, {omitJSDOMErrors: true});
/**
* Gets og/twitter title, description, image
* from a url
*
* @param url the url
*
* @returns {Promise.<{og: {}, twitter: {}}>}
*/
exports.grabInfo = async (url) => {