code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function drawDetectionResults() { const canvas = multiPersonCanvas(); drawResults(sourceImage, canvas, faceDetection, predictedPoses); if (!predictedPoses || !predictedPoses.length || !illustration) { return; } skeleton.reset(); canvasScope.project.clear(); if (faceDetection && faceDetection.length > 0) { let face = Skeleton.toFaceFrame(faceDetection[0]); illustration.updateSkeleton(predictedPoses[0], face); } else { illustration.updateSkeleton(predictedPoses[0], null); } illustration.draw(canvasScope, sourceImage.width, sourceImage.height); if (guiState.showCurves) { illustration.debugDraw(canvasScope); } if (guiState.showLabels) { illustration.debugDrawLabel(canvasScope); } }
Draw the results from the multi-pose estimation on to a canvas
drawDetectionResults
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
async function testImageAndEstimatePoses() { toggleLoadingUI(true); setStatusText('Loading FaceMesh model...'); document.getElementById('results').style.display = 'none'; // Reload facemesh model to purge states from previous runs. facemesh = await facemesh_module.load(); // Load an example image setStatusText('Loading image...'); sourceImage = await loadImage(sourceImages[guiState.sourceImage]); // Estimates poses setStatusText('Predicting...'); predictedPoses = await posenet.estimatePoses(sourceImage, { flipHorizontal: false, decodingMethod: 'multi-person', maxDetections: defaultMaxDetections, scoreThreshold: defaultMinPartConfidence, nmsRadius: defaultNmsRadius, }); faceDetection = await facemesh.estimateFaces(sourceImage, false, false); // Draw poses. drawDetectionResults(); toggleLoadingUI(false); document.getElementById('results').style.display = 'block'; }
Loads an image, feeds it into posenet the posenet model, and calculates poses based on the model outputs
testImageAndEstimatePoses
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
function setupGui() { const gui = new dat.GUI(); const imageControls = gui.addFolder('Image'); imageControls.open(); gui.add(guiState, 'sourceImage', Object.keys(sourceImages)).onChange(() => testImageAndEstimatePoses()); gui.add(guiState, 'avatarSVG', Object.keys(avatarSvgs)).onChange(() => loadSVG(avatarSvgs[guiState.avatarSVG])); const debugControls = gui.addFolder('Debug controls'); debugControls.open(); gui.add(guiState, 'showKeypoints').onChange(drawDetectionResults); gui.add(guiState, 'showSkeleton').onChange(drawDetectionResults); gui.add(guiState, 'showCurves').onChange(drawDetectionResults); gui.add(guiState, 'showLabels').onChange(drawDetectionResults); }
Loads an image, feeds it into posenet the posenet model, and calculates poses based on the model outputs
setupGui
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
async function bindPage() { toggleLoadingUI(true); canvasScope = paper.default; let canvas = getIllustrationCanvas(); canvas.width = CANVAS_WIDTH; canvas.height = CANVAS_HEIGHT; canvasScope.setup(canvas); await tf.setBackend('webgl'); setStatusText('Loading PoseNet model...'); posenet = await posenet_module.load({ architecture: resnetArchitectureName, outputStride: defaultStride, inputResolution: defaultInputResolution, multiplier: defaultMultiplier, quantBytes: defaultQuantBytes }); setupGui(posenet); setStatusText('Loading SVG file...'); await loadSVG(Object.values(avatarSvgs)[0]); }
Kicks off the demo by loading the posenet model and estimating poses on a default image
bindPage
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
async function loadSVG(target) { let svgScope = await SVGUtils.importSVG(target); skeleton = new Skeleton(svgScope); illustration = new PoseIllustration(canvasScope); illustration.bindSkeleton(skeleton, svgScope); testImageAndEstimatePoses(); }
Kicks off the demo by loading the posenet model and estimating poses on a default image
loadSVG
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
function toggleLoadingUI( showLoadingUI, loadingDivId = 'loading', mainDivId = 'main') { if (showLoadingUI) { document.getElementById(loadingDivId).style.display = 'block'; document.getElementById(mainDivId).style.display = 'none'; } else { document.getElementById(loadingDivId).style.display = 'none'; document.getElementById(mainDivId).style.display = 'block'; } }
Toggles between the loading UI and the main canvas UI.
toggleLoadingUI
javascript
yemount/pose-animator
utils/demoUtils.js
https://github.com/yemount/pose-animator/blob/master/utils/demoUtils.js
Apache-2.0
function toTuple({y, x}) { return [y, x]; }
Toggles between the loading UI and the main canvas UI.
toTuple
javascript
yemount/pose-animator
utils/demoUtils.js
https://github.com/yemount/pose-animator/blob/master/utils/demoUtils.js
Apache-2.0
function drawPoint(ctx, y, x, r, color) { ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.fillStyle = color; ctx.fill(); }
Toggles between the loading UI and the main canvas UI.
drawPoint
javascript
yemount/pose-animator
utils/demoUtils.js
https://github.com/yemount/pose-animator/blob/master/utils/demoUtils.js
Apache-2.0
function drawSkeleton(keypoints, minConfidence, ctx, scale = 1) { const adjacentKeyPoints = posenet.getAdjacentKeyPoints(keypoints, minConfidence); adjacentKeyPoints.forEach((keypoints) => { drawSegment( toTuple(keypoints[0].position), toTuple(keypoints[1].position), color, scale, ctx); }); }
Draws a pose skeleton by looking up all adjacent keypoints/joints
drawSkeleton
javascript
yemount/pose-animator
utils/demoUtils.js
https://github.com/yemount/pose-animator/blob/master/utils/demoUtils.js
Apache-2.0
_subscribe(subscriber) { // const { source } = this; return source && source.subscribe(subscriber); }
@deprecated This is an internal implementation detail, do not use.
_subscribe
javascript
sverweij/dependency-cruiser
test/extract/transpile/__mocks__/dontconfuse_ts_for_tsx/transpiled/Observable.js
https://github.com/sverweij/dependency-cruiser/blob/master/test/extract/transpile/__mocks__/dontconfuse_ts_for_tsx/transpiled/Observable.js
MIT
function getAverage(arr) { var sum = arr.reduce(function (a, b) { return a + b; }); return sum / arr.length; }
Simple results wrapper Will be passed via events and to formatters
getAverage
javascript
macbre/phantomas
core/results.js
https://github.com/macbre/phantomas/blob/master/core/results.js
BSD-2-Clause
nodeRunner = function () { // "Beep, Beep" }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
nodeRunner
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function getStackFromError(e) { var stack = e.stack .trim() .split("\n") .map(function (item) { return item.replace(/^(\s+at\s|@)/, "").trim(); }) .filter(function (item) { return /:\d+\)?$/.test(item); }); //console.log(stack); return stack; }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
getStackFromError
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function getBacktrace() { var stack = []; try { throw new Error("backtrace"); } catch (e) { stack = getStackFromError(e).slice(3); } return stack.join(" / "); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
getBacktrace
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function getCaller(stepBack) { var caller = false; stepBack = stepBack || 0; try { throw new Error("backtrace"); } catch (e) { caller = getStackFromError(e)[3 + stepBack]; } return caller; }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
getCaller
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function sendMsg(type, data) { scope.__phantomas_emit("scopeMessage", type, data); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
sendMsg
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function log() { sendMsg("log", Array.prototype.slice.apply(arguments)); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
log
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function setMetric(name, value, isFinal) { sendMsg("setMetric", [ name, typeof value !== "undefined" ? value : 0, isFinal === true, ]); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
setMetric
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function incrMetric(name, incr /* =1 */) { sendMsg("incrMetric", [name, incr || 1]); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
incrMetric
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function addToAvgMetric(name, value) { sendMsg("addToAvgMetric", { name: name, value: value, }); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
addToAvgMetric
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function setMarkerMetric(name) { sendMsg("setMarkerMetric", { name: name, }); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
setMarkerMetric
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function addOffender(/*metricName, msg, ...*/) { sendMsg("addOffender", Array.prototype.slice.apply(arguments)); }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
addOffender
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function getParam(param, _default) { return scope.__phantomas_options[param] || _default; }
phantomas browser "scope" with helper code Code below is executed in page's "scope" (injected by the scope.injectJs() helper)
getParam
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function spyEnabled(state, reason) { enabled = state === true; phantomas.log( "Spying " + (enabled ? "enabled" : "disabled") + (reason ? " - " + reason : "") ); }
Proxy function to be used to track calls to native DOM functions Callback is provided with arguments original function was called with Example: window.__phantomas.proxy(window.document, 'getElementById', function() { // ... });
spyEnabled
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function spy(obj, fn, callback, reportResults) { var origFn = obj && obj[fn]; if (typeof origFn !== "function") { return false; } phantomas.log( 'spy: attaching to "%s" function%s', fn, reportResults ? " with results reporting" : "" ); obj[fn] = function () { var args = Array.prototype.slice.call(arguments), results = origFn.apply(this, args); if (enabled && typeof callback === "function") { callback.apply( this, reportResults === true ? [results].concat(args) : args ); } return results; }; // copy custom properties of original function to the mocked one Object.keys(origFn).forEach(function (key) { obj[fn][key] = origFn[key]; }); obj[fn].prototype = origFn.prototype; return true; }
Proxy function to be used to track calls to native DOM functions Callback is provided with arguments original function was called with Example: window.__phantomas.proxy(window.document, 'getElementById', function() { // ... });
spy
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function spyGlobalVar(varName, callback) { phantomas.log("spy: attaching to %s global variable", varName); window.__defineSetter__(varName, function (val) { phantomas.log("spy: %s global variable has been defined", varName); spiedGlobals[varName] = val; callback(val); }); window.__defineGetter__(varName, function () { return spiedGlobals[varName] || undefined; }); }
Proxy function to be used to track calls to native DOM functions Callback is provided with arguments original function was called with Example: window.__phantomas.proxy(window.document, 'getElementById', function() { // ... });
spyGlobalVar
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function getDOMPath(node, dontGoUpTheDom /* = false */) { var path = [], entry = ""; if (node === window) { return "window"; } while (node instanceof Node) { // div entry = node.nodeName.toLowerCase(); // shorten the path a bit if (["body", "head", "html"].indexOf(entry) > -1) { path.push(entry); break; } if (node instanceof DocumentFragment) { entry = "DocumentFragment"; } // div#foo if (node.id && node.id !== "") { entry += "#" + node.id; } // div#foo.bar.test else if (typeof node.className === "string" && node.className !== "") { entry += "." + node.className.trim().replace(/\s+/g, "."); } // div[0] <- index of child node else if (node.parentNode instanceof Node) { entry += "[" + Math.max( 0, Array.prototype.indexOf.call( node.parentNode.children || node.parentNode.childNodes, node ) ) + "]"; } path.push(entry); if (dontGoUpTheDom === true) { break; } // go up the DOM node = node && node.parentNode; } return path.length > 0 ? path.reverse().join(" > ") : false; }
Returns "DOM path" to a given node (starting from <body> down to the node) Example: body.logged_out.vis-public.env-production > div > div
getDOMPath
javascript
macbre/phantomas
core/scope.js
https://github.com/macbre/phantomas/blob/master/core/scope.js
BSD-2-Clause
function lowerCaseHeaders(headers) { var res = {}; Object.keys(headers).forEach((headerName) => { res[headerName.toLowerCase()] = headers[headerName]; }); return res; }
Given key-value set of HTTP headers returns the set with lowercased header names @param {object} headers @returns {object}
lowerCaseHeaders
javascript
macbre/phantomas
core/modules/requestsMonitor/requestsMonitor.js
https://github.com/macbre/phantomas/blob/master/core/modules/requestsMonitor/requestsMonitor.js
BSD-2-Clause
function parseEntryUrl(entry) { var parsed; // asset type entry.type = "other"; if (entry.url.indexOf("data:") === 0) { // base64 encoded data entry.domain = false; entry.protocol = false; entry.isBase64 = true; } else if (entry.url.indexOf("blob:") === 0) { // blob image or video entry.domain = false; entry.protocol = false; entry.isBlob = true; } else { parsed = new URL(entry.url); entry.protocol = parsed.protocol.replace(":", ""); // e.g. "http:" entry.domain = parsed.hostname; entry.query = parsed.search.substring(1); if (entry.protocol === "https") { entry.isSSL = true; } } return entry; }
Given key-value set of HTTP headers returns the set with lowercased header names @param {object} headers @returns {object}
parseEntryUrl
javascript
macbre/phantomas
core/modules/requestsMonitor/requestsMonitor.js
https://github.com/macbre/phantomas/blob/master/core/modules/requestsMonitor/requestsMonitor.js
BSD-2-Clause
function addContentType(headerValue, entry) { var value = headerValue.split(";").shift().toLowerCase(); entry.contentType = value; switch (value) { case "text/html": entry.type = "html"; entry.isHTML = true; break; case "text/xml": entry.type = "xml"; entry.isXML = true; break; case "text/css": entry.type = "css"; entry.isCSS = true; break; case "application/x-javascript": case "application/javascript": case "text/javascript": entry.type = "js"; entry.isJS = true; break; case "application/json": entry.type = "json"; entry.isJSON = true; break; case "image/png": case "image/jpeg": case "image/gif": case "image/svg+xml": case "image/webp": case "image/avif": entry.type = "image"; entry.isImage = true; if (value === "image/svg+xml") { entry.isSVG = true; } break; case "video/webm": case "video/mp4": entry.type = "video"; entry.isVideo = true; break; // @see http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts case "application/font-wof": case "application/font-woff": case "application/font-woff2": case "application/vnd.ms-fontobject": case "application/x-font-opentype": case "application/x-font-truetype": case "application/x-font-ttf": case "application/x-font-woff": case "font/opentype": case "font/ttf": case "font/woff": case "font/woff2": entry.type = "webfont"; entry.isWebFont = true; if (/ttf|truetype$/.test(value)) { entry.isTTF = true; } break; case "application/octet-stream": var ext = (entry.url || "").split(".").pop(); switch (ext) { // @see http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts#comment-8077637 case "otf": entry.type = "webfont"; entry.isWebFont = true; break; } break; case "image/x-icon": case "image/vnd.microsoft.icon": entry.type = "favicon"; entry.isFavicon = true; break; default: debug( "Unknown content type found: " + value + " for <" + entry.url + ">" ); } return entry; }
Detect response content type using "Content-Type header value" @param {string} headerValue @param {object} entry
addContentType
javascript
macbre/phantomas
core/modules/requestsMonitor/requestsMonitor.js
https://github.com/macbre/phantomas/blob/master/core/modules/requestsMonitor/requestsMonitor.js
BSD-2-Clause
function screenshot(ts /* force timestamp in file name */) { var now = Date.now(), path; // check when was the last screenshot taken (exclude time it took to render the screenshot) if (now - lastScreenshot < SCREENSHOTS_MIN_INTERVAL) { //phantomas.log('Film strip: skipped'); return; } // time offset excluding time it took to render screenshots ts = ts || now - start - timeTotal; path = util.format( "%s/%s-%s-%d.png", filmStripOutputDir, filmStripPrefix, startFormatted, ts ); phantomas.render(path); lastScreenshot = Date.now(); // verify that the screnshot was really taken if (fs.isReadable(path)) { phantomas.log( "Film strip: rendered to %s in %d ms", path, Date.now() - now ); phantomas.emit("filmStrip", path, ts); screenshots.push({ path: path, ts: ts, }); // stats timeTotal += Date.now() - now; } else { phantomas.log("Film strip: rendering to %s failed!", path); } }
Please note that rendering each screenshot takes several hundreds ms. Consider increasing default timeout. Run phantomas with --film-strip option to use this module --film-strip-dir folder path to output film strip (default is ./filmstrip directory) --film-strip-prefix film strip files name prefix (defaults to 'screenshot') You can pass a comma separated list of milliseconds when to trigger a screenshot. The time will be calculated relative to "responseEnd" event (issue #174)
screenshot
javascript
macbre/phantomas
extensions/filmStrip/filmStrip.js
https://github.com/macbre/phantomas/blob/master/extensions/filmStrip/filmStrip.js
BSD-2-Clause
function createHAR(page, creator) { // @see: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html var address = page.address; var title = page.title; var startTime = page.startTime; var resources = page.resources; var entries = []; resources.forEach(function (resource) { var request = resource.request; var response = resource.response; if (!request || !response) { return; } // Exclude data URIs from the HAR because they aren't // included in the spec. if (request.url.substring(0, 5).toLowerCase() === "data:") { return; } entries.push({ cache: {}, pageref: address, request: { // Accurate bodySize blocked on https://github.com/ariya/phantomjs/pull/11484 bodySize: -1, cookies: [], headers: request.headers, // Accurate headersSize blocked on https://github.com/ariya/phantomjs/pull/11484 headersSize: -1, httpVersion: "HTTP/1.1", method: request.method, queryString: [], url: request.url, }, response: { bodySize: response.bodySize, cookies: [], headers: response.headers, headersSize: response.headersSize, httpVersion: "HTTP/1.1", redirectURL: "", status: response.status, statusText: response.statusText, content: { mimeType: response.contentType || "", size: response.bodySize, // uncompressed text: "", }, }, startedDateTime: resource.startTime && resource.startTime.toISOString(), time: response.timeToLastByte, timings: { blocked: 0, dns: -1, connect: -1, send: 0, wait: 0, // response.timeToFirstByte || 0, receive: 0, // response.receiveTime, ssl: -1, }, }); }); return { log: { creator: creator, entries: entries, pages: [ { startedDateTime: startTime.toISOString(), id: address, title: title, pageTimings: { onLoad: page.onLoad || -1, onContentLoad: page.onContentLoad || -1, }, }, ], version: "1.2", }, }; }
Inspired by phantomHAR @author: Christopher Van (@cvan) @homepage: https://github.com/cvan/phantomHAR @original: https://github.com/cvan/phantomHAR/blob/master/phantomhar.js
createHAR
javascript
macbre/phantomas
extensions/har/har.js
https://github.com/macbre/phantomas/blob/master/extensions/har/har.js
BSD-2-Clause
async function injectStorage(page, storage, storageType) { if (!page || !storage || !storageType) { return; } /* istanbul ignore next */ await page.evaluateOnNewDocument( (storage, storageType, SESSION_STORAGE, LOCAL_STORAGE) => { const keys = Object.keys(storage); const values = Object.values(storage); if (storageType === SESSION_STORAGE) { for (let i = 0; i < keys.length; i++) { sessionStorage.setItem(keys[i], values[i]); } } if (storageType === LOCAL_STORAGE) { for (let i = 0; i < keys.length; i++) { localStorage.setItem(keys[i], values[i]); } } }, storage, storageType, SESSION_STORAGE, LOCAL_STORAGE ); }
Inject the given storage into the specified page storage. Either localStorage or sessionStorage @param {Page} page in which page the storage should be injected @param {Object} storage the JSON object consisting of the storage keys and values @param {string} storageType either localStorage or sessionStorage
injectStorage
javascript
macbre/phantomas
extensions/pageStorage/pageStorage.js
https://github.com/macbre/phantomas/blob/master/extensions/pageStorage/pageStorage.js
BSD-2-Clause
function phantomas(url, opts) { var events = new EventEmitter(), browser, options; debug("OS: %s %s", process.platform, process.arch); debug("Node.js: %s", process.version); debug("phantomas: %s", VERSION); debug( "Puppeteer: preferred revision r%s", puppeteer.default._preferredRevision ); debug("URL: <%s>", url); // options handling options = Object.assign({}, opts || {}); // avoid #563 options.url = options.url || url || false; debug("Options: %s", JSON.stringify(options)); events.setMaxListeners(250); // MaxListenersExceededWarning: Possible EventEmitter memory leak detected. var results = new Results(); results.setUrl(url); results.setGenerator("phantomas v" + VERSION); // set up and run Puppeteer browser = new Browser(); browser.bind(events); var promise = new Promise(async (resolve, reject) => { try { if (typeof options.url !== "string") { return reject(Error("URL must be a string")); } const page = await browser.init(options), debugScope = require("debug")("phantomas:scope:log"); // prepare a small instance object that will be passed to modules and extensions on init const scope = { getParam: (param, _default) => { return options[param] || _default; }, getVersion: () => VERSION, emit: events.emit.bind(events), on: events.on.bind(events), once: events.once.bind(events), log: debugScope.bind(debug), addOffender: results.addOffender.bind(results), incrMetric: results.incrMetric.bind(results), setMetric: results.setMetric, addToAvgMetric: results.addToAvgMetric, getMetric: results.getMetric, // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluatepagefunction-args evaluate: page.evaluate.bind(page), // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1 querySelectorAll: async function querySelectorAll( selector ) /* istanbul ignore next */ { debug('querySelectorAll("%s")', selector); return page.$$(selector); }, // @see https://pptr.dev/api/puppeteer.page.evaluateonnewdocument // Adds a function which would be invoked in when: // - the child frame is attached or navigated // - the page is navigated injectJs: async (script) => { const debug = require("debug")("phantomas:injectJs"); // Make sure we're on an HTML document, not an XML document for example const prefix = "if (document.constructor.name === 'HTMLDocument') {", suffix = "}"; const preloadFile = prefix + (await require("fs/promises").readFile(script, "utf8")) + suffix; await page.evaluateOnNewDocument(preloadFile); debug(script + " JavaScript file has been injected into page scope"); }, }; // pass phantomas options to page scope // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args /* istanbul ignore next */ await page.evaluateOnNewDocument((options) => { window.__phantomas_options = options; }, options); // expose the function that will pass events from page scope code into Node.js layer // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction await page.exposeFunction("__phantomas_emit", scope.emit); // Inject helper code into the browser's scope (but only once!) events.once("init", () => { debug("onInit: injecting the core/scope.js ..."); scope.injectJs(__dirname + "/../core/scope.js"); }); // bind to sendMsg calls from page scope code events.on("scopeMessage", (type, args) => { const debug = require("debug")("phantomas:core:scopeEvents"); // debug(type + ' [' + args + ']'); switch (type) { case "addOffender": case "incrMetric": case "log": case "setMetric": scope[type].apply(scope, args); break; /* istanbul ignore next */ default: debug("Unrecognized event type: " + type); } }); // bind to a first response // and reject a promise if the first response is 4xx / 5xx HTTP error var firstResponseReceived = false; events.once("recv", async (entry) => { if (!firstResponseReceived && entry.status >= 400) { debug( "<%s> response code is HTTP %d %s", entry.url, entry.status, entry.statusText ); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject( new Error( "HTTP response code from <" + entry.url + "> is " + entry.status ) ); } firstResponseReceived = true; }); // load modules and extensions debug("Loading core modules..."); loader.loadCoreModules(scope); debug("Loading extensions..."); loader.loadExtensions(scope); debug("Loading modules..."); loader.loadModules(scope); await events.emit("init", page, browser.getPuppeteerBrowser()); // @desc Browser's scope and modules are set up, the page is about to be loaded // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagegotourl-options const waitUntil = options["wait-for-network-idle"] ? "networkidle0" : undefined, timeout = options.timeout; await browser.visit(url, waitUntil, timeout); // resolve our run // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#browserclose await events.emit("beforeClose", page); // @desc Called before the Chromium (and all of its pages) is closed await browser.close(); // your last chance to add metrics await events.emit("report"); // @desc Called just before the phantomas results are returned to the caller resolve(results); } catch (ex) { debug("Exception caught: " + ex); debug(ex); // close the browser before leaving here, otherwise subsequent instances will have problems await browser.close(); reject(ex); } }); promise.on = events.on.bind(events); promise.once = events.once.bind(events); return promise; }
Main CommonJS module entry point @param {string} url @param {Object} opts @returns {browser}
phantomas
javascript
macbre/phantomas
lib/index.js
https://github.com/macbre/phantomas/blob/master/lib/index.js
BSD-2-Clause
function listModulesInDirectory(modulesDir) { const log = debug("phantomas:modules"); log("Getting the list of all modules in " + modulesDir); // https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options var ls = fs.readdirSync(modulesDir), modules = []; ls.forEach(function (entry) { // First check whether an entry is a directory, than check if it contains a module file // https://nodejs.org/api/fs.html#fs_fs_existssync_path if (fs.existsSync(modulesDir + "/" + entry + "/" + entry + ".js")) { modules.push(entry); } }); return modules.sort(); }
Lists all modules / extensions in a given directory @param {string} modulesDir @returns {Array<string}
listModulesInDirectory
javascript
macbre/phantomas
lib/loader.js
https://github.com/macbre/phantomas/blob/master/lib/loader.js
BSD-2-Clause
function loadCoreModules(scope) { const modules = ["navigationTiming", "requestsMonitor", "timeToFirstByte"]; modules.forEach((name) => { var log = debug("phantomas:modules:" + name), _scope = Object.assign({}, scope); _scope.log = log; var module = require(__dirname + "/../core/modules/" + name + "/" + name); module(_scope); // auto-inject scope.js from module's directory var scopeFile = __dirname + "/../core/modules/" + name + "/scope.js"; if (fs.existsSync(scopeFile)) { scope.on("init", () => scope.injectJs(scopeFile)); } }); }
Lists all modules / extensions in a given directory @param {string} modulesDir @returns {Array<string}
loadCoreModules
javascript
macbre/phantomas
lib/loader.js
https://github.com/macbre/phantomas/blob/master/lib/loader.js
BSD-2-Clause
function loadExtensions(scope) { const extensions = listModulesInDirectory(__dirname + "/../extensions/"); extensions.forEach((name) => { var log = debug("phantomas:extensions:" + name), _scope = Object.assign({}, scope); _scope.log = log; var module = require(__dirname + "/../extensions/" + name + "/" + name); module(_scope); }); }
Lists all modules / extensions in a given directory @param {string} modulesDir @returns {Array<string}
loadExtensions
javascript
macbre/phantomas
lib/loader.js
https://github.com/macbre/phantomas/blob/master/lib/loader.js
BSD-2-Clause
function loadModules(scope) { const extensions = listModulesInDirectory(__dirname + "/../modules/"); extensions.forEach((name) => { var log = debug("phantomas:modules:" + name), _scope = Object.assign({}, scope); _scope.log = log; var module = require(__dirname + "/../modules/" + name + "/" + name); module(_scope); // auto-inject scope.js from module's directory var scopeFile = __dirname + "/../modules/" + name + "/scope.js"; if (fs.existsSync(scopeFile)) { scope.on("init", () => scope.injectJs(scopeFile)); } }); }
Lists all modules / extensions in a given directory @param {string} modulesDir @returns {Array<string}
loadModules
javascript
macbre/phantomas
lib/loader.js
https://github.com/macbre/phantomas/blob/master/lib/loader.js
BSD-2-Clause
function getMetricsCoveredByTests(spec) { const debug = require("debug")("metricsCovered"); var covered = {}; spec.forEach((testCase) => { debug(testCase.label || testCase.url); Object.keys(testCase.metrics || {}).forEach((metric) => { covered[metric] = true; }); Object.keys(testCase.offenders || {}).forEach((metric) => { covered[metric] = true; }); }); return Object.keys(covered); }
Generates metadata.json file that stores metadata about: - events - metrics - modules - extensions
getMetricsCoveredByTests
javascript
macbre/phantomas
lib/metadata/generate.js
https://github.com/macbre/phantomas/blob/master/lib/metadata/generate.js
BSD-2-Clause
function getOptionsCoveredByTests(spec) { var covered = {}; spec.forEach((testCase) => { Object.keys(testCase.options || {}).forEach((option) => { covered[option] = true; }); }); return Object.keys(covered).sort(); }
Generates metadata.json file that stores metadata about: - events - metrics - modules - extensions
getOptionsCoveredByTests
javascript
macbre/phantomas
lib/metadata/generate.js
https://github.com/macbre/phantomas/blob/master/lib/metadata/generate.js
BSD-2-Clause
function getModuleMetadata(moduleFile) { var content = fs.readFileSync(moduleFile).toString(), data = { name: "", description: "", metrics: {}, events: {}, }, matches, moduleName, metricRegEx = /(setMetric|setMetricEvaluate|incrMetric)\(['"]([^'"]+)['"](\)|,)(.*@desc.*$)?/gm, eventsRegEx = /emit\(['"]([^'"]+)['"]([^)]+).*@desc(.*)$/gm; data.name = moduleName = moduleFile.split("/").pop().replace(/\.js$/, ""); const localPath = moduleFile.replace( fs.realpathSync(__dirname + "/../../"), "" ); data.localPath = localPath; // // scan the source code // // look for metrics metadata while ((matches = metricRegEx.exec(content)) !== null) { var entry = {}, metricName = matches[2], metricComment = matches[4], metricUnit = "ms", hasDesc = metricComment && metricComment.indexOf("@desc") > -1; if (typeof data.metrics[metricName] !== "undefined") { if (hasDesc) { debug( "Found duplicated definition of %s metric in %s module", metricName, moduleName ); } continue; } // parse @desc if (hasDesc) { metricComment = metricComment.split("@desc").pop().trim(); entry.desc = ""; ["unreliable", "optional", "offenders", "gecko"].forEach(function ( marker ) { if (metricComment.indexOf("@" + marker) > -1) { entry[marker] = true; metricComment = metricComment.replace("@" + marker, "").trim(); } }); // detect units (defaults to ms) if ((matches = metricComment.match(/\[([^\]]+)\]/)) !== null) { metricUnit = matches[1]; metricComment = metricComment.replace(matches[0], "").trim(); } else if ( /^(number of|total number of|average specificity|total specificity|median of number|maximum number|maximum level)/.test( metricComment ) ) { metricUnit = "number"; } else if ( /^(the size|size|length|total length) of/.test(metricComment) ) { metricUnit = "bytes"; } // check if offenders are reported for this metric let offenderRegex = new RegExp( "phantomas.addOffender\\([\\n\\r\\s]*[\"']" + metricName + "[\"']" ); if (content.search(offenderRegex) > -1) { entry.offenders = true; } entry.desc = metricComment; entry.unit = metricUnit; } else if (moduleName !== "scope") { debug( "Metadata missing for %s metric in %s module", metricName, moduleName ); } entry.module = moduleName; // add a metric data.metrics[metricName] = entry; } // look for events metadata while ((matches = eventsRegEx.exec(content)) !== null) { // console.log([moduleName, matches[1], matches[2], matches[3]]); data.events[matches[1]] = { file: localPath, desc: matches[3].trim(), arguments: matches[2].replace(/^[,\s]+/g, ""), }; } // parse modules and extensions initial commit block matches = /^\/\*\*([^/]+)\*\//m.exec(content); if (matches) { var desc = matches[0] .replace(/^[\s/]?\*+\s?/gm, "") // remove the beginning of block comment .replace(/\/$/gm, "") // remove the ending of block comment .replace(/^\s?setMetric.*$/gm, "") // remove setMetric annotations .trim(); //console.log(localPath, moduleName, matches[0]); data.description = desc; } //console.log(data); throw new Error('foo'); return data; }
Generates metadata.json file that stores metadata about: - events - metrics - modules - extensions
getModuleMetadata
javascript
macbre/phantomas
lib/metadata/generate.js
https://github.com/macbre/phantomas/blob/master/lib/metadata/generate.js
BSD-2-Clause
async function buildDocs() { // now add some real life examples from loading an example URL from our tests events += `## Examples`; const promise = phantomas("http://0.0.0.0:8888/_make_docs.html"); var hasEvent = {}; [ "recv", "send", "request", "response", "milestone", "metrics", "consoleLog", "jserror", ].forEach((eventName) => { promise.on(eventName, (...args) => { if (hasEvent[eventName]) return; hasEvent[eventName] = true; const dumped = JSON.stringify(args, null, " "); debug("events.md: %s event triggered ...", eventName); events += ` ### ${eventName} Arguments passed to the event: \`\`\`json ${dumped} \`\`\` `.trimRight(); }); }); // make results available when generating metrics.md - see the next step const runResults = await promise; debug("Report metrics: %j", runResults.getMetrics()); debug("Report offenders: %j", runResults.getAllOffenders()); debug("Saving events.md ..."); fs.writeFileSync(docs_dir + "/events.md", events.trim() + docs_notice); /** * metrics.md * * https://github.com/macbre/phantomas/issues/729 */ // get offender examples from integration-spec.yaml const offenders = (() => { const yaml = require("js-yaml"), spec = yaml.load( fs .readFileSync(__dirname + "/../../test/integration-spec.yaml") .toString() ); var offenders = {}; spec.forEach((testCase) => { Object.keys(testCase.offenders || {}).forEach((metricName) => { if (!offenders[metricName]) { offenders[metricName] = testCase.offenders[metricName][0]; } }); }); // test coverage is not 100%, fill missing offenders using the "real" phantomas run from above Object.keys(runResults.getMetrics()).forEach((metricName) => { if (!offenders[metricName] && runResults.getOffenders(metricName)) { offenders[metricName] = runResults.getOffenders(metricName)[0]; } }); return offenders; })(); // build Markdown file var metrics = ` Modules and metrics =================== This file describes all [\`phantomas\` modules](https://github.com/macbre/phantomas/tree/devel/modules) (${metadata.modulesCount} of them) and ${metadata.metricsCount} metrics that they emit. When applicable, [offender](https://github.com/macbre/phantomas/issues/140) example is provided. `; Object.keys(metadata.modules) .sort() .forEach((moduleName) => { const entry = metadata.modules[moduleName]; metrics += ` ## [${moduleName}](${github_root}${entry.file}) > ${entry.desc} `; entry.metrics.sort().forEach((metricName) => { const metric = metadata.metrics[metricName], hasOffenders = metric.offenders ? ", with offenders" : ""; metrics += ` ##### \`${metricName}\` ${metric.desc} (${metric.unit}${hasOffenders}) `; // add offender's example if (hasOffenders && offenders[metricName]) { const dumped = JSON.stringify(offenders[metricName], null, " "); metrics += ` \`\`\`json ${dumped} \`\`\` `; } }); }); debug("Saving metrics.md ..."); fs.writeFileSync(docs_dir + "/metrics.md", metrics.trim() + docs_notice); // --- debug("Done"); }
events.md https://github.com/macbre/phantomas/issues/729
buildDocs
javascript
macbre/phantomas
lib/metadata/make_docs.js
https://github.com/macbre/phantomas/blob/master/lib/metadata/make_docs.js
BSD-2-Clause
function ucfirst(str) { // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: Brett Zamir (http://brett-zamir.me) // * example 1: ucfirst('kevin van zonneveld'); // * returns 1: 'Kevin van zonneveld' str += ""; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); }
Adds CSS complexity metrics using analyze-css npm module. Run phantomas with --analyze-css option to use this module setMetric('cssBase64Length') @desc total length of base64-encoded data in CSS source (will warn about base64-encoded data bigger than 4 kB) @optional @offenders setMetric('cssRedundantBodySelectors') @desc number of redundant body selectors (e.g. body .foo, section body h2, but not body > h1) @optional @offenders setMetric('redundantChildNodesSelectors') @desc number of redundant child nodes selectors @optional @offenders setMetric('cssColors') @desc number of unique colors used in CSS @optional @offenders setMetric('cssComments') @desc number of comments in CSS source @optional @offenders setMetric('cssCommentsLength') @desc length of comments content in CSS source @optional setMetric('cssComplexSelectorsByAttribute') @desc [number] number of selectors with complex matching by attribute (e.g. [class$="foo"]) @optional @offenders setMetric('cssDuplicatedSelectors') @desc number of CSS selectors defined more than once in CSS source @optional @offenders setMetric('cssDuplicatedProperties') @desc number of CSS property definitions duplicated within a selector @optional @offenders setMetric('cssEmptyRules') @desc number of rules with no properties (e.g. .foo { }) @optional @offenders setMetric('cssExpressions') @desc number of rules with CSS expressions (e.g. expression( document.body.clientWidth > 600 ? "600px" : "auto" )) @optional @offenders setMetric('cssOldIEFixes') @desc number of fixes for old versions of Internet Explorer (e.g. * html .foo {} and .foo { *zoom: 1 }) @optional @offenders setMetric('cssImports') @desc number of @import rules @optional @offenders setMetric('cssImportants') @desc number of properties with value forced by !important @optional @offenders setMetric('cssMediaQueries') @desc number of media queries (e.g. @media screen and (min-width: 1370px)) @optional @offenders setMetric('cssMultiClassesSelectors') @desc number of selectors with multiple classes (e.g. span.foo.bar) @optional @offenders setMetric('cssOldPropertyPrefixes') @desc number of properties with no longer needed vendor prefix, powered by data provided by autoprefixer (e.g. --moz-border-radius) @optional @offenders setMetric('cssQualifiedSelectors') @desc number of qualified selectors (e.g. header#nav, .foo#bar, h1.title) @optional @offenders setMetric('cssSpecificityIdAvg') @desc average specificity for ID @optional @offenders setMetric('cssSpecificityIdTotal') @desc total specificity for ID @optional setMetric('cssSpecificityClassAvg') @desc average specificity for class, pseudo-class or attribute @optional @offenders setMetric('cssSpecificityClassTotal') @desc total specificity for class, pseudo-class or attribute @optional setMetric('cssSpecificityTagAvg') @desc average specificity for element @optional @offenders setMetric('cssSpecificityTagTotal') @desc total specificity for element @optional setMetric('cssSelectorsByAttribute') @desc [number] number of selectors by attribute (e.g. .foo[value=bar]) @optional setMetric('cssSelectorsByClass') @desc number of selectors by class @optional setMetric('cssSelectorsById') @desc number of selectors by ID @optional setMetric('cssSelectorsByPseudo') @desc number of pseudo-selectors (e,g. :hover) @optional setMetric('cssSelectorsByTag') @desc number of selectors by tag name @optional setMetric('cssLength') @desc length of CSS source (in bytes) @optional @offenders setMetric('cssRules') @desc number of rules (e.g. .foo, .bar { color: red } is counted as one rule) @optional @offenders setMetric('cssSelectors') @desc number of selectors (e.g. .foo, .bar { color: red } is counted as two selectors - .foo and .bar) @optional @offenders setMetric('cssDeclarations') @desc number of declarations (e.g. .foo, .bar { color: red } is counted as one declaration - color: red) @optional @offenders setMetric('cssNotMinified') @desc [number] set to 1 if the provided CSS is not minified @optional @offenders setMetric('cssSelectorLengthAvg') @desc [number] average length of selector (e.g. for ``.foo .bar, #test div > span { color: red }`` will be set as 2.5) @optional @offenders
ucfirst
javascript
macbre/phantomas
modules/analyzeCss/analyzeCss.js
https://github.com/macbre/phantomas/blob/master/modules/analyzeCss/analyzeCss.js
BSD-2-Clause
async function analyzeCss(css, context) { /** // force JSON output format options.push('--json'); // set basic auth if needed if (phantomas.getParam('auth-user') && phantomas.getParam('auth-pass')) { options.push('--auth-user', phantomas.getParam('auth-user')); options.push('--auth-pass', phantomas.getParam('auth-pass')); } // HTTP proxy (#500) var proxy = phantomas.getParam('proxy', false, 'string'); if (proxy !== false) { if (proxy.indexOf('http:') < 0) { proxy = 'http://' + proxy; // http-proxy-agent (used by analyze-css) expects a protocol as well } options.push('--proxy', proxy); } **/ // https://www.npmjs.com/package/analyze-css#commonjs-module var options = {}; let results; try { results = await analyzer(css, options); } catch (err) { phantomas.log("analyzeCss: sub-process failed! - %s", err); // report failed CSS parsing (issue #494( var offender = offenderSrc; if (err.message) { // Error object returned if (err.message.indexOf("Unable to parse JSON string") > 0) { offender += " (analyzeCss output error)"; } } else { // Error string returned (stderror) if ( err.indexOf("CSS parsing failed") > 0 || err.indexOf("is an invalid expression") > 0 ) { offender += " (" + err.trim() + ")"; } else if (err.indexOf("Empty CSS was provided") > 0) { offender += " (Empty CSS was provided)"; } } phantomas.incrMetric("cssParsingErrors"); phantomas.addOffender("cssParsingErrors", offender); return; } var offenderSrc = context || "[inline CSS]"; phantomas.log("Got results for %s from %s", offenderSrc, results.generator); const metrics = results.metrics, offenders = results.offenders; Object.keys(metrics).forEach((metric) => { var metricPrefixed = "css" + ucfirst(metric); if (/Avg$/.test(metricPrefixed)) { // update the average value (see #641) phantomas.addToAvgMetric(metricPrefixed, metrics[metric]); } else { // increase metrics phantomas.incrMetric(metricPrefixed, metrics[metric]); } // and add offenders if (typeof offenders[metric] !== "undefined") { offenders[metric].forEach((offender) => { phantomas.addOffender(metricPrefixed, { url: offenderSrc, value: { message: offender.message, position: { ...offender.position, source: offender.source || "undefined", }, // cast to object }, }); }); } // add more offenders (#578) else { switch (metricPrefixed) { case "cssLength": case "cssRules": case "cssSelectors": case "cssDeclarations": case "cssNotMinified": case "cssSelectorLengthAvg": case "cssSpecificityIdAvg": case "cssSpecificityClassAvg": case "cssSpecificityTagAvg": phantomas.addOffender(metricPrefixed, { url: offenderSrc, value: metrics[metric], }); break; } } }); }
Adds CSS complexity metrics using analyze-css npm module. Run phantomas with --analyze-css option to use this module setMetric('cssBase64Length') @desc total length of base64-encoded data in CSS source (will warn about base64-encoded data bigger than 4 kB) @optional @offenders setMetric('cssRedundantBodySelectors') @desc number of redundant body selectors (e.g. body .foo, section body h2, but not body > h1) @optional @offenders setMetric('redundantChildNodesSelectors') @desc number of redundant child nodes selectors @optional @offenders setMetric('cssColors') @desc number of unique colors used in CSS @optional @offenders setMetric('cssComments') @desc number of comments in CSS source @optional @offenders setMetric('cssCommentsLength') @desc length of comments content in CSS source @optional setMetric('cssComplexSelectorsByAttribute') @desc [number] number of selectors with complex matching by attribute (e.g. [class$="foo"]) @optional @offenders setMetric('cssDuplicatedSelectors') @desc number of CSS selectors defined more than once in CSS source @optional @offenders setMetric('cssDuplicatedProperties') @desc number of CSS property definitions duplicated within a selector @optional @offenders setMetric('cssEmptyRules') @desc number of rules with no properties (e.g. .foo { }) @optional @offenders setMetric('cssExpressions') @desc number of rules with CSS expressions (e.g. expression( document.body.clientWidth > 600 ? "600px" : "auto" )) @optional @offenders setMetric('cssOldIEFixes') @desc number of fixes for old versions of Internet Explorer (e.g. * html .foo {} and .foo { *zoom: 1 }) @optional @offenders setMetric('cssImports') @desc number of @import rules @optional @offenders setMetric('cssImportants') @desc number of properties with value forced by !important @optional @offenders setMetric('cssMediaQueries') @desc number of media queries (e.g. @media screen and (min-width: 1370px)) @optional @offenders setMetric('cssMultiClassesSelectors') @desc number of selectors with multiple classes (e.g. span.foo.bar) @optional @offenders setMetric('cssOldPropertyPrefixes') @desc number of properties with no longer needed vendor prefix, powered by data provided by autoprefixer (e.g. --moz-border-radius) @optional @offenders setMetric('cssQualifiedSelectors') @desc number of qualified selectors (e.g. header#nav, .foo#bar, h1.title) @optional @offenders setMetric('cssSpecificityIdAvg') @desc average specificity for ID @optional @offenders setMetric('cssSpecificityIdTotal') @desc total specificity for ID @optional setMetric('cssSpecificityClassAvg') @desc average specificity for class, pseudo-class or attribute @optional @offenders setMetric('cssSpecificityClassTotal') @desc total specificity for class, pseudo-class or attribute @optional setMetric('cssSpecificityTagAvg') @desc average specificity for element @optional @offenders setMetric('cssSpecificityTagTotal') @desc total specificity for element @optional setMetric('cssSelectorsByAttribute') @desc [number] number of selectors by attribute (e.g. .foo[value=bar]) @optional setMetric('cssSelectorsByClass') @desc number of selectors by class @optional setMetric('cssSelectorsById') @desc number of selectors by ID @optional setMetric('cssSelectorsByPseudo') @desc number of pseudo-selectors (e,g. :hover) @optional setMetric('cssSelectorsByTag') @desc number of selectors by tag name @optional setMetric('cssLength') @desc length of CSS source (in bytes) @optional @offenders setMetric('cssRules') @desc number of rules (e.g. .foo, .bar { color: red } is counted as one rule) @optional @offenders setMetric('cssSelectors') @desc number of selectors (e.g. .foo, .bar { color: red } is counted as two selectors - .foo and .bar) @optional @offenders setMetric('cssDeclarations') @desc number of declarations (e.g. .foo, .bar { color: red } is counted as one declaration - color: red) @optional @offenders setMetric('cssNotMinified') @desc [number] set to 1 if the provided CSS is not minified @optional @offenders setMetric('cssSelectorLengthAvg') @desc [number] average length of selector (e.g. for ``.foo .bar, #test div > span { color: red }`` will be set as 2.5) @optional @offenders
analyzeCss
javascript
macbre/phantomas
modules/analyzeCss/analyzeCss.js
https://github.com/macbre/phantomas/blob/master/modules/analyzeCss/analyzeCss.js
BSD-2-Clause
async function analyzeImage(body, context) { phantomas.log("Starting analyze-image on %j", context); const results = await analyzer(body, context, {}); phantomas.log("Response from analyze-image: %j", results); for (const offenderName in results.offenders) { phantomas.log( "Offender %s found: %j", offenderName, results.offenders[offenderName] ); const newOffenderName = offenderName.replace("image", "images"); phantomas.incrMetric(newOffenderName); phantomas.addOffender(newOffenderName, { url: context.url || shortenDataUri(context.inline), ...results.offenders[offenderName], }); } }
Adds Responsive Images metrics using analyze-images npm module. Run phantomas with --analyze-images option to use this module
analyzeImage
javascript
macbre/phantomas
modules/analyzeImages/analyzeImages.js
https://github.com/macbre/phantomas/blob/master/modules/analyzeImages/analyzeImages.js
BSD-2-Clause
function extractImageFromDataUri(str) { const result = str.match(/^data:image\/[a-z+]*(?:;[a-z0-9]*)?,(.*)$/); if (result) { // Inline SVGs might be urlencoded if (str.startsWith("data:image/svg+xml") && str.includes("%3Csvg")) { return decodeURIComponent(result[1]); } return result[1]; } return null; }
Adds Responsive Images metrics using analyze-images npm module. Run phantomas with --analyze-images option to use this module
extractImageFromDataUri
javascript
macbre/phantomas
modules/analyzeImages/analyzeImages.js
https://github.com/macbre/phantomas/blob/master/modules/analyzeImages/analyzeImages.js
BSD-2-Clause
function shortenDataUri(str) { if (str.length > 100) { return str.substring(0, 50) + " [...] " + str.substring(str.length - 50); } return str; }
Adds Responsive Images metrics using analyze-images npm module. Run phantomas with --analyze-images option to use this module
shortenDataUri
javascript
macbre/phantomas
modules/analyzeImages/analyzeImages.js
https://github.com/macbre/phantomas/blob/master/modules/analyzeImages/analyzeImages.js
BSD-2-Clause
function ms(value) { return Math.round(value * 1000); }
Retrieves stats about layouts, style recalcs and JS execution Metrics from https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagemetrics
ms
javascript
macbre/phantomas
modules/cpuTasks/cpuTasks.js
https://github.com/macbre/phantomas/blob/master/modules/cpuTasks/cpuTasks.js
BSD-2-Clause
function processHeaders(headers) { var res = { count: 0, size: 0, }; if (headers) { Object.keys(headers).forEach(function (key) { res.count++; res.size += (key + ": " + headers[key] + "\r\n").length; }); } return res; }
Analyzes HTTP headers in both requests and responses
processHeaders
javascript
macbre/phantomas
modules/headers/headers.js
https://github.com/macbre/phantomas/blob/master/modules/headers/headers.js
BSD-2-Clause
function pushToStack(type, entry, check) { // no entry of given type if (typeof stack[type] === "undefined") { stack[type] = entry; } // apply check function else if (check(stack[type], entry) === true) { stack[type] = entry; } }
Analyzes HTTP requests and generates stats metrics setMetric('smallestResponse') @desc the size of the smallest response @offenders setMetric('biggestResponse') @desc the size of the biggest response @offenders setMetric('fastestResponse') @desc the time to the last byte of the fastest response @offenders setMetric('slowestResponse') @desc the time to the last byte of the slowest response @offenders setMetric('smallestLatency') @desc the time to the first byte of the fastest response @offenders setMetric('biggestLatency') @desc the time to the first byte of the slowest response @offenders setMetric('medianResponse') @desc median value of time to the last byte for all responses @offenders setMetric('medianLatency') @desc median value of time to the first byte for all responses @offenders
pushToStack
javascript
macbre/phantomas
modules/requestsStats/requestsStats.js
https://github.com/macbre/phantomas/blob/master/modules/requestsStats/requestsStats.js
BSD-2-Clause
function getFromStack(type) { return stack[type]; }
Analyzes HTTP requests and generates stats metrics setMetric('smallestResponse') @desc the size of the smallest response @offenders setMetric('biggestResponse') @desc the size of the biggest response @offenders setMetric('fastestResponse') @desc the time to the last byte of the fastest response @offenders setMetric('slowestResponse') @desc the time to the last byte of the slowest response @offenders setMetric('smallestLatency') @desc the time to the first byte of the fastest response @offenders setMetric('biggestLatency') @desc the time to the first byte of the slowest response @offenders setMetric('medianResponse') @desc median value of time to the last byte for all responses @offenders setMetric('medianLatency') @desc median value of time to the first byte for all responses @offenders
getFromStack
javascript
macbre/phantomas
modules/requestsStats/requestsStats.js
https://github.com/macbre/phantomas/blob/master/modules/requestsStats/requestsStats.js
BSD-2-Clause
function setDomainMetric(metricName) { phantomas.setMetric(metricName, domains.getLength()); domains.sort().forEach(function (domain, cnt) { phantomas.addOffender(metricName, { domain, requests: cnt }); }); }
Number of requests it took to make the page enter DomContentLoaded and DomComplete states accordingly
setDomainMetric
javascript
macbre/phantomas
modules/requestsTo/requestsTo.js
https://github.com/macbre/phantomas/blob/master/modules/requestsTo/requestsTo.js
BSD-2-Clause
function capitalize(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }
Provides metrics for time to first image, CSS and JS file setMetric('timeToFirstCss') @desc time it took to receive the last byte of the first CSS @offenders setMetric('timeToFirstJs') @desc time it took to receive the last byte of the first JS @offenders setMetric('timeToFirstImage') @desc time it took to receive the last byte of the first image @offenders
capitalize
javascript
macbre/phantomas
modules/timeToFirst/timeToFirst.js
https://github.com/macbre/phantomas/blob/master/modules/timeToFirst/timeToFirst.js
BSD-2-Clause
function formatSingleRunResults(results) { var res = { generator: results.getGenerator(), url: results.getUrl(), metrics: results.getMetrics(), offenders: results.getAllOffenders(), asserts: false, }; // add asserts var asserts = results.getAsserts(), failedAsserts; if (Object.keys(asserts).length > 0) { failedAsserts = results.getFailedAsserts(); res.asserts = { rules: asserts, failedCount: failedAsserts.length, failedAsserts: failedAsserts, }; } return res; }
Results formatter for -R json Options: pretty - pretty print the JSON
formatSingleRunResults
javascript
macbre/phantomas
reporters/json.js
https://github.com/macbre/phantomas/blob/master/reporters/json.js
BSD-2-Clause
function useAnimatedValue({ direction, max, min, value }) { const [data, setData] = useState({ direction, value, }); const animate = useCallback(() => { // perform all the logic inside setData so useEffect's dependency array // can be empty so it will only trigger one on initial render and not // add and remove from ticker constantly. setData(current => { const data = { ...current }; // flip direction once min or max has been reached. if ( (current.value >= current.max && current.direction === 1) || (current.value <= current.min && current.direction === -1) ) { data.direction *= -1; } // increment or decrement ` data.value += data.direction; return data; }); }, []); usePixiTicker(animate); return data.value; }
Implements `react-pixi-fiber`'s `usePixiTicker` hook, and the `useState` hook. Handles animation of the circle and square background.
useAnimatedValue
javascript
michalochman/react-pixi-fiber
examples/src/HooksExample/index.js
https://github.com/michalochman/react-pixi-fiber/blob/master/examples/src/HooksExample/index.js
MIT
function setValueForProperty(type, instance, propName, value, internalHandle) { const propertyInfo = getPropertyInfo(propName); let strictRoot = null; if (__DEV__) { strictRoot = findStrictRoot(internalHandle); } if (shouldIgnoreAttribute(type, propName, propertyInfo)) { return; } let shouldIgnoreValue = false; if (shouldRemoveAttribute(type, propName, value, propertyInfo)) { // Try to reset to property to default value (if it is defined) otherwise ignore provided value. // This is the original behaviour of [email protected] (on which this is based) and [email protected], // left here for backwards compatibility. // TODO This is not the best solution as it makes it impossible to remove props that were once set. // Setting value to null or undefined makes behaviour of props used by PIXI unstable/undefined. // Deleting properties i another idea, however with many getters/setters defined by PIXI it is not trivial. const defaultValue = getDefaultValue(type, propName); if (typeof defaultValue !== "undefined") { value = defaultValue; if (strictRoot != null) { warning( false, "Received undefined for prop `%s` on `<%s />`. Setting default value to `%s`.%s", propName, type, value, getStackAddendum() ); } } else { shouldIgnoreValue = true; if (strictRoot != null) { warning( false, "Received undefined for prop `%s` on `<%s />`. Cannot determine default value. Ignoring.%s", propName, type, getStackAddendum() ); } } } if (!shouldIgnoreValue) { setPixiValue(instance, propName, value); } }
Sets the value for a property on a PIXI.DisplayObject instance. @param {string} type @param {PIXI.DisplayObject} instance @param {string} propName @param {*} value @param {*} internalHandle
setValueForProperty
javascript
michalochman/react-pixi-fiber
src/PixiPropertyOperations.js
https://github.com/michalochman/react-pixi-fiber/blob/master/src/PixiPropertyOperations.js
MIT
function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) }
The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified.
Buffer
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) }
The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified.
from
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } }
Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str[, encoding]) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset[, length]])
assertSize
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) }
Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str[, encoding]) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset[, length]])
alloc
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; i++) { that[i] = 0 } } return that }
Creates a new filled Buffer instance. alloc(size[, fill[, encoding]])
allocUnsafe
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) that.write(string, encoding) return that }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
fromString
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
fromArrayLike
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
fromArrayBuffer
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
fromObject
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
checked
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
SlowBuffer
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'binary': // Deprecated case 'raw': case 'raws': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
byteLength
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
slowToString
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
swap
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function arrayIndexOf (arr, val, byteOffset, encoding) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var foundIndex = -1 for (var i = 0; byteOffset + i < arrLength; i++) { if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } return -1 }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
arrayIndexOf
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
read
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
hexWrite
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
utf8Write
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
asciiWrite
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
binaryWrite
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
base64Write
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
ucs2Write
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
base64Slice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
utf8Slice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
decodeCodePointsArray
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
asciiSlice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
binarySlice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
hexSlice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
utf16leSlice
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
checkOffset
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
checkInt
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
objectWriteUInt16
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
objectWriteUInt32
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
checkIEEE754
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
writeFloat
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
writeDouble
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
base64clean
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
stringtrim
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
toHex
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
utf8ToBytes
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
asciiToBytes
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
utf16leToBytes
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
base64ToBytes
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT
function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i }
Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
blitBuffer
javascript
sparksuite/simplemde-markdown-editor
debug/simplemde.debug.js
https://github.com/sparksuite/simplemde-markdown-editor/blob/master/debug/simplemde.debug.js
MIT