code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
var decorate = function (job) { var sourceCode = job.sourceCode, basePos = job.basePos; var sourceNode = job.sourceNode; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {DecorationsT} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( sourceNode, basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( sourceNode, basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( sourceNode, basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; };
Lexes job.sourceCode and attaches an output array job.decorations of style classes preceded by the position at which they start in job.sourceCode in order. @type{function (JobT)}
decorate ( job )
javascript
googlearchive/code-prettify
js-modules/prettify.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/prettify.js
Apache-2.0
function injectJS(url, opt_func) { var el = document.createElement('script'); if (typeof opt_func === 'function') { el.onload = el.onerror = el.onreadystatechange = function () { if (el && (!el.readyState || /loaded|complete/.test(el.readyState))) { el.onerror = el.onload = el.onreadystatechange = null; el = null; opt_func(); } }; } el.type = 'text/javascript'; el.src = url; document.getElementsByTagName('head')[0].appendChild(el); }
Dynamically load script @param {string} url JavaScript file @param {Function=} opt_func onload callback
injectJS ( url , opt_func )
javascript
googlearchive/code-prettify
tests/test_base.js
https://github.com/googlearchive/code-prettify/blob/master/tests/test_base.js
Apache-2.0
function injectCSS(url) { var el = document.createElement('link'); el.rel = 'stylesheet'; el.type = 'text/css'; el.href = url; document.getElementsByTagName('head')[0].appendChild(el); }
Dynamically load stylesheet @param {string} url CSS file
injectCSS ( url )
javascript
googlearchive/code-prettify
tests/test_base.js
https://github.com/googlearchive/code-prettify/blob/master/tests/test_base.js
Apache-2.0
function runTests(goldens) { // Regexp literals defined here so that the interpreter doesn't have to // compile them each time the function containing them is called. /** @const {RegExp} */ var ampRe = /&/g; /** @const {RegExp} */ var ltRe = /</g; /** @const {RegExp} */ var gtRe = />/g; /** @const {RegExp} */ var quotRe = /\"/g; /** @const {RegExp} */ var nbspRe = /\xa0/g; /** @const {RegExp} */ var newlineRe = /[\r\n]/g; /** @const {RegExp} */ var voidElemsRe = /^(?:br|hr|link|img)$/; /** @type {?boolean} */ var innerHtmlWorks = null; /** * Get timestamp in milliseconds unit. * * @return {number} */ function now() { return (Date.now ? Date.now() : (new Date()).getTime()); } /** * Escapes HTML special characters to HTML. * * @param {string} str the HTML to escape * @return {string} output escaped HTML */ function textToHtml(str) { return str .replace(ampRe, '&amp;') .replace(ltRe, '&lt;') .replace(gtRe, '&gt;'); } /** * Like {@link textToHtml} but escapes double quotes to be attribute safe. * * @param {string} str the HTML to escape * @return {string} output escaped HTML */ function attribToHtml(str) { return textToHtml(str).replace(quotRe, '&quot;'); } /** * convert a plain text string to HTML by escaping HTML special chars. * * @param {string} plainText * @return {string} */ function htmlEscape(plainText) { return attribToHtml(plainText).replace(nbspRe, '&nbsp;'); } /** * Traverse node and manually build `innerHTML`. * * @param {Node} node DOM node * @param {string} out HTML content * @param {boolean=} opt_sortAttrs if attributes should be sorted */ function normalizedHtml(node, out, opt_sortAttrs) { switch (node.nodeType) { case 1: // ELEMENT_NODE // start-tag var name = node.tagName.toLowerCase(); out.push('<', name); // attributes var attrs = node.attributes; var n = attrs.length; if (n) { if (opt_sortAttrs) { // sort attributes by name var sortedAttrs = []; for (var i = n; --i >= 0;) { sortedAttrs[i] = attrs[i]; } sortedAttrs.sort(function (a, b) { return (a.name < b.name) ? -1 : (a.name === b.name ? 0 : 1); }); attrs = sortedAttrs; } for (var i = 0; i < n; ++i) { var attr = attrs[i]; // specified: <tag atn> vs. <tag atn="atv"> if (!attr.specified) { continue; } out.push(' ', attr.name.toLowerCase(), '="', attribToHtml(attr.value), '"'); } } out.push('>'); // children for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out, opt_sortAttrs); } // end-tag if (node.firstChild || !voidElemsRe.test(name)) { out.push('<\/', name, '>'); } break; case 3: // TEXT_NODE case 4: // CDATA_SECTION_NODE out.push(textToHtml(node.nodeValue)); break; } } /** * get normalized markup. innerHTML varies enough across browsers that we * can't use it. * * @param {Node} node * @return {string} */ function normalizedInnerHtml(node) { // manually build innerHTML with sorted attributes var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out, true); } out = out.join(''); // more normalization to work around problems with non-ascii chars in // regexps in Safari for (var i = 0; (i = out.indexOf('\xa0')) >= 0;) { out = out.substring(0, i) + '&nbsp;' + out.substring(i + 1); } return out.replace(/\r\n?/g, '\n'); } /** * Are newlines and adjacent spaces significant in the given node's * `innerHTML`? * * @param {Node} node DOM node * @param {string} content its HTML content * @return {boolean} is it preformatted */ function isPreformatted(node, content) { // PRE means preformatted, and is a very common case, so don't create // unnecessary computed style objects. if ('PRE' === node.tagName) { return true; } if (!newlineRe.test(content)) { return true; } // Don't care var whitespace = ''; // For disconnected nodes, IE has no currentStyle. if (node.currentStyle) { whitespace = node.currentStyle.whiteSpace; } else if (window.getComputedStyle) { // Firefox makes a best guess if node is disconnected whereas Safari // returns the empty string. whitespace = window.getComputedStyle(node, null).whiteSpace; } return !whitespace || whitespace === 'pre'; } /** * Get `innerHTML` of a node * * @param {Node} node DOM node * @return {string} HTML content */ function getInnerHtml(node) { // innerHTML is hopelessly broken in Safari 2.0.4 when the content is // an HTML description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === innerHtmlWorks) { var testNode = document.createElement('pre'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); innerHtmlWorks = !/</.test(testNode.innerHTML); } if (innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if ('XMP' === node.tagName) { content = textToHtml(content); } else if (!isPreformatted(node, content)) { content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1') .replace(/(?:[\r\n]+[ \t]*)+/g, ' '); } return content; } else { var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } } /** * number of characters in common from the beginning. * * @param {string} a * @param {string} b * @return {number} */ function commonPrefix(a, b) { var n = Math.min(a.length, b.length); var i; for (i = 0; i < n; ++i) { if (a.charAt(i) !== b.charAt(i)) { break; } } return i; } /** * number of characters in common at the end up to max. * * @param {string} a * @param {string} b * @param {number} max * @return {number} */ function commonSuffix(a, b, max) { var n = Math.min(a.length - max, b.length - max); var i; for (i = 0; i < n; ++i) { if (a.charAt(a.length - i - 1) !== b.charAt(b.length - i - 1)) { break; } } return i; } /** * Replace whitespace characters with printable graphical representations. * * @param {string} txt * @return {string} */ function showAllCharacters(txt) { // space = \xb7, \u02f0, \u2219, \u2423, \u2420 // htab = \xbb, \u21e5, \u25b8, \u2409 // newline = \xac, \xb6, \u21b5, \u2424 // vtab = \u240B // ffeed = \u240C return txt .replace(/ /g, '\xb7') .replace(/(\r?\n)/g, '\u21b5$1') .replace(/\t/g, '\u25b8') .replace(/\v/g, '\u240B') .replace(/\f/g, '\u240C'); } /** * Find differences between two texts, and return an HTML report. * * @param {string} golden text * @param {string} actual text * @return {string} HTML representation */ function diffTexts(golden, actual) { if (true) { golden = showAllCharacters(golden); actual = showAllCharacters(actual); } var npre = commonPrefix(golden, actual); var npost = commonSuffix(golden, actual, npre); return ( '<table class="diff"><tr><th>Golden<\/th><td><code>' + htmlEscape(golden.substring(0, npre)) + '&raquo;<span class="mismatch">' + htmlEscape(golden.substring(npre, golden.length - npost)) + '<\/span>&laquo;' + htmlEscape(golden.substring(golden.length - npost)) + '<\/code><\/td><\/tr><tr><th>Actual<\/th><td><code>' + htmlEscape(actual.substring(0, npre)) + '&raquo;<span class="mismatch">' + htmlEscape(actual.substring(npre, actual.length - npost)) + '<\/span>&laquo;' + htmlEscape(actual.substring(actual.length - npost)) + '<\/code><\/td><\/tr><\/table>' ); } /** * Convert golden from abbreviated form back to original text * * @param {string} golden * @return {string} */ function expandGolden(golden) { return golden.replace(/`([A-Z]{3})/g, function (_, lbl) { // convert abbreviations that start with ` return (lbl === 'END' ? '<\/span>' : '<span class="' + lbl.toLowerCase() + '">'); }) // line numbers .replace(/`#(?![0-9])/, '<li class="L0">') .replace(/`#([0-9])/g, '<\/li><li class="L$1">'); } /** * Compare tests results against expected outcomes. * * @param {Object<string,string>} goldens * @return {{html: Array<string>, pass: integer, fail: integer}} HTML report */ function runComparison(goldens) { var out = []; var npass = 0; var nfail = 0; for (var id in goldens) { // compare actual against expexted var golden = expandGolden(goldens[id]); var actual = normalizedInnerHtml(document.getElementById(id)); var diff = golden !== actual; out.push('<div class="test">' + (diff ? 'FAIL' : 'PASS') + ': <a href="#' + id + '">' + id + '<\/a><\/div>'); if (diff) { ++nfail; // write out difference out.push( diffTexts(golden, actual).replace(/&lt;br&gt;/g, '&lt;br&gt;\n')); } else { ++npass; } } out.unshift( '<p class="pass">\u2714 ' + npass + ' passing<\/p>', '<p class="fail">\u2718 ' + nfail + ' failing<\/p>'); out.push('<h3 id="summary">Tests ' + (nfail ? 'failed' : 'passed') + '<\/h3>'); return { html: out, pass: npass, fail: nfail }; } // for more accurate timing, no continuation. // This file must be loaded after prettify.js for this to work. window.PR_SHOULD_USE_CONTINUATION = false; // time syntax highlighting var t = now(); // tic PR.prettyPrint(function () { t = now() - t; // toc // verify results against golden and write HTML report var report = runComparison(goldens); document.title += (' \u2014 ' + (report.fail ? 'FAIL' : 'PASS')); report.html.unshift('<p id="timing">Took ' + t + ' ms<\/p>');
Perform syntax highlighting and execute tests to verify results. @param {Object<string,string>} goldens a mapping from IDs of prettyprinted chunks to an abbreviated form of the expected output. See "var goldens" in prettify_test.html and prettify_test_2.html for examples.
runTests ( goldens )
javascript
googlearchive/code-prettify
tests/test_base.js
https://github.com/googlearchive/code-prettify/blob/master/tests/test_base.js
Apache-2.0
(function () { if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } })();
Shim for ES5 Date.now for older browsers (IE < 9, FF < 3, etc.) @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Polyfill
(anonymous) ( )
javascript
googlearchive/code-prettify
tests/shims.js
https://github.com/googlearchive/code-prettify/blob/master/tests/shims.js
Apache-2.0
(function () { if (!document.getElementsByClassName) { document.getElementsByClassName = function (className) { className = className.replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ' '); var results = []; function walk(node) { if (node.nodeType !== 1) { return; } // This test should be order-insensitive. if ((' ' + node.className + ' ').indexOf(className) >= 0) { results[results.length] = node; } for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } } walk(document.body); return results; }; } })();
Shim for HTML5 getElementsByClassName for older browsers (IE < 9, FF < 3, etc.)
(anonymous) ( )
javascript
googlearchive/code-prettify
tests/shims.js
https://github.com/googlearchive/code-prettify/blob/master/tests/shims.js
Apache-2.0
(function () { 'use strict'; var _slice = Array.prototype.slice; try { // Can't be used with DOM elements in IE < 9 _slice.call(document.documentElement); } catch (e) { // Fails in IE < 9 // This will work for genuine arrays, array-like objects, // NamedNodeMap (attributes, entities, notations), // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), // and will not fail on other DOM objects (as do DOM elements in IE < 9) Array.prototype.slice = function(begin, end) { // IE < 9 gets unhappy with an undefined end argument end = (typeof end !== 'undefined') ? end : this.length; // For native Array objects, we use the native slice function if (Object.prototype.toString.call(this) === '[object Array]') { return _slice.call(this, begin, end); } // For array like object we handle it ourselves. var i, cloned = [], size, len = this.length; // Handle negative value for "begin" var start = begin || 0; start = (start >= 0) ? start : Math.max(0, len + start); // Handle negative value for "end" var upTo = (typeof end === 'number') ? Math.min(end, len) : len; if (end < 0) { upTo = len + end; } // Actual expected size of the slice size = upTo - start; if (size > 0) { cloned = new Array(size); if (this.charAt) { for (i = 0; i < size; i++) { cloned[i] = this.charAt(start + i); } } else { for (i = 0; i < size; i++) { cloned[i] = this[start + i]; } } } return cloned; }; } }());
Shim for "fixing" IE's lack of support (IE < 9) for applying slice on host objects like NamedNodeMap, NodeList, and HTMLCollection (technically, since host objects have been implementation-dependent, at least before ES2015, IE hasn't needed to work this way). Also works on strings, fixes IE < 9 to allow an explicit undefined for the 2nd argument (as in Firefox), and prevents errors when called on other DOM objects. @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Streamlining_cross-browser_behavior
(anonymous) ( )
javascript
googlearchive/code-prettify
tests/shims.js
https://github.com/googlearchive/code-prettify/blob/master/tests/shims.js
Apache-2.0
function syncMod(src, dest, mode) { if (mode !== false) { fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode); } } // Create copies of language handler files under all registered aliases grunt.registerMultiTask('aliases', 'Create language aliases', function () { var opts = this.options({ timestamp: false, mode: false }); var count = 0; this.filesSrc.forEach(function (src) { // run language handler in sandbox grunt.verbose.subhead('Running ' + src.cyan + ' in sandbox...'); var exts = runLanguageHandler(src); grunt.verbose.ok(); // go over collected extensions exts.forEach(function (ext) { // copy file var dest = src.replace(/\blang-\w+\b/, 'lang-' + ext); grunt.verbose.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan); grunt.file.copy(src, dest); // sync timestamp and file mode syncTimestamp(src, dest, opts.timestamp); syncMod(src, dest, opts.mode); count++; }); }); grunt.log.ok('Copied ' + count.toString().cyan + grunt.util.pluralize(count, ' file/ files')); }); };
Copy file mode from source to destination. @param {string} src @param {string} dest @param {boolean|number} mode
syncMod ( src , dest , mode )
javascript
googlearchive/code-prettify
tasks/aliases.js
https://github.com/googlearchive/code-prettify/blob/master/tasks/aliases.js
Apache-2.0
function syncTimestamp(src, dest, timestamp) { if (timestamp) { var stat = fs.lstatSync(src); var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r'); fs.futimesSync(fd, stat.atime, stat.mtime); fs.closeSync(fd); } } /** * Copy file mode from source to destination. * @param {string} src * @param {string} dest * @param {boolean|number} mode */ function syncMod(src, dest, mode) { if (mode !== false) { fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode); } } // Create copies of language handler files under all registered aliases grunt.registerMultiTask('aliases', 'Create language aliases', function () { var opts = this.options({ timestamp: false, mode: false }); var count = 0; this.filesSrc.forEach(function (src) { // run language handler in sandbox grunt.verbose.subhead('Running ' + src.cyan + ' in sandbox...'); var exts = runLanguageHandler(src); grunt.verbose.ok(); // go over collected extensions exts.forEach(function (ext) { // copy file var dest = src.replace(/\blang-\w+\b/, 'lang-' + ext); grunt.verbose.writeln('Copying ' + src.cyan + ' -> ' + dest.cyan); grunt.file.copy(src, dest); // sync timestamp and file mode syncTimestamp(src, dest, opts.timestamp); syncMod(src, dest, opts.mode); count++; }); }); grunt.log.ok('Copied ' + count.toString().cyan + grunt.util.pluralize(count, ' file/ files')); }); };
Copy timestamp from source to destination file. @param {string} src @param {string} dest @param {boolean} timestamp
syncTimestamp ( src , dest , timestamp )
javascript
googlearchive/code-prettify
tasks/aliases.js
https://github.com/googlearchive/code-prettify/blob/master/tasks/aliases.js
Apache-2.0
module.exports = function (grunt) { 'use strict'; /* * HACK: Custom task to override "closure-compiler:langs" since all lang-* * files are compiled in parallel, launching too many Java processes at once * which easily runs out of memory! This task programmatically creates * separate targets (one file per target) so that lang files are compiled * sequentially (sync) instead of in parallel (async). */ grunt.registerMultiTask('gcc', 'Override closure-compiler', function () { // closure-compiler:langs var task = 'closure-compiler'; var target = this.target; if (!grunt.task.exists(task)) { grunt.fail.warn(grunt.util.error('Require task "' + task + '".')); } // create new targets for each file (one file per target) var count = 0; var opts = this.options(); this.files.forEach(function (file, idx) { // simple target config with only: src, dest, and options delete file.orig; file.options = opts; // configure new target grunt.config.set([task, target + idx], file); grunt.verbose.writeln('New target ' + (task + ':' + target + idx).cyan); count++; }); grunt.log.ok('Configured ' + count.toString().cyan + ' lang targets'); // remove original multi-file target grunt.config.set([task, target], {}); // enqueue modified task to run //console.log(grunt.config.get(task)); grunt.task.run(task); }); };
google-code-prettify https://github.com/google/code-prettify @author Amro @license Apache-2.0
module.exports ( grunt )
javascript
googlearchive/code-prettify
tasks/gcc.js
https://github.com/googlearchive/code-prettify/blob/master/tasks/gcc.js
Apache-2.0
function createSandbox() { // collect registered language extensions var sandbox = {}; sandbox.extensions = []; // mock prettify.js API sandbox.window = {}; sandbox.window.PR = sandbox.PR = { registerLangHandler: function (handler, exts) { sandbox.extensions = sandbox.extensions.concat(exts); }, createSimpleLexer: function (sPatterns, fPatterns) { return function (job) {}; }, sourceDecorator: function (options) { return function (job) {}; }, prettyPrintOne: function (src, lang, ln) { return src; }, prettyPrint: function (done, root) {}, PR_ATTRIB_NAME: 'atn', PR_ATTRIB_VALUE: 'atv', PR_COMMENT: 'com', PR_DECLARATION: 'dec', PR_KEYWORD: 'kwd', PR_LITERAL: 'lit', PR_NOCODE: 'nocode', PR_PLAIN: 'pln', PR_PUNCTUATION: 'pun', PR_SOURCE: 'src', PR_STRING: 'str', PR_TAG: 'tag', PR_TYPE: 'typ' }; return sandbox; }
Returns a mock object PR of the prettify API. This is used to collect registered language file extensions. @return {Object} PR object with an additional `extensions` property.
createSandbox ( )
javascript
googlearchive/code-prettify
tasks/lib/lang-aliases.js
https://github.com/googlearchive/code-prettify/blob/master/tasks/lib/lang-aliases.js
Apache-2.0
function runLanguageHandler(src) { // execute source code in an isolated sandbox with a mock PR object var sandbox = createSandbox(); vm.runInNewContext(fs.readFileSync(src), sandbox, { filename: src }); // language name var lang = path.basename(src, path.extname(src)).replace(/^lang-/, ''); // collect and filter extensions var exts = sandbox.extensions.map(function (ext) { // case-insensitive names return ext.toLowerCase(); }).filter(function (ext) { // skip self, and internal names like foo-bar-baz or lang.foo return ext !== lang && !/\W/.test(ext); }); exts = exts.filter(function (ext, pos) { // remove duplicates return exts.indexOf(ext) === pos; }); return exts; }
Runs a language handler file under VM to collect extensions. Given a lang-*.js file, runs the language handler in a fake context where PR.registerLangHandler collects handler names without doing anything else. This is later used to makes copies of the JS extension under all its registered language names lang-<EXT>.js @param {string} src path to lang-xxx.js language handler @return {Array<string>} registered file extensions
runLanguageHandler ( src )
javascript
googlearchive/code-prettify
tasks/lib/lang-aliases.js
https://github.com/googlearchive/code-prettify/blob/master/tasks/lib/lang-aliases.js
Apache-2.0
gulp.task( 'v1-jigyosyo', ['download'], function () { gulp.src( 'api/JIGYOSYO.CSV' ) .pipe( jigyosyo2json() ) .pipe( v1() ) .pipe( chmod( 644 ) ) .pipe( gulp.dest( 'api/v1' ) ); } );
Create an API of the Jigyosyo postal code.
(anonymous) ( )
javascript
madefor/postal-code-api
gulpfile.js
https://github.com/madefor/postal-code-api/blob/master/gulpfile.js
MIT
const writeToFile = function(filePath, data) { fs.writeFile(filePath, data, function(err) { if (err) { return console.error(err); } console.log(`SVG file was created: ${filePath}`); }); };
@description Write data to the specified file path. @param {string} filePath Path of the destination file @param {*} data Data to write to the destination
writeToFile ( filePath , data )
javascript
Bogdan-Lyashenko/js-code-to-svg-flowchart
cli/index.cli.js
https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js
MIT
const createAbstractedSvgFile = function(file, code, abstractionLevel) { const errMsg = 'Please use (case insensitive, without the quotes): "function", "function_dependencies", "class", "import" or "export"'; if (!abstractionLevel) return console.error(`No abstraction level specified`); const flowTreeBuilder = js2flowchart.createFlowTreeBuilder(); //Check if the abstraction level(s) are valid and process them let abstractions = abstractionLevel.map(al => { try { return js2flowchart.ABSTRACTION_LEVELS[al.toUpperCase()]; } catch (err) { throw new Error(`The following abstraction level isn't valid: ${al}\n${errMsg}`); } }); flowTreeBuilder.setAbstractionLevel(abstractions); const flowTree = flowTreeBuilder.build(code); const svg = js2flowchart.convertFlowTreeToSvg(flowTree), filePath = `${file}.svg`; writeToFile(filePath, svg); };
@description Create an SVG file with the provided abstraction level @param {string} file Name of the JS script @param {string} code JS code of the JS script @param {...string} abstractionLevel Abstraction levels (function, function dependencies, class, import, export) @return undefined
createAbstractedSvgFile ( file , code , abstractionLevel )
javascript
Bogdan-Lyashenko/js-code-to-svg-flowchart
cli/index.cli.js
https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js
MIT
const list = val => val.split(',');
@description Convert argument lists to arrays. @param {string} val Argument lists @return {string[]} Array of arguments
list
javascript
Bogdan-Lyashenko/js-code-to-svg-flowchart
cli/index.cli.js
https://github.com/Bogdan-Lyashenko/js-code-to-svg-flowchart/blob/master/cli/index.cli.js
MIT
getPlace (place) { return window.document.getElementsByTagName(place)[0] },
This function return the element by tagName @type {Function} @return {Object}
getPlace ( place )
javascript
ktquez/vue-head
vue-head-es6.js
https://github.com/ktquez/vue-head/blob/master/vue-head-es6.js
MIT
undoTitle (state) { if (!state.before) return window.document.title = state.before },
Undo the window.document title for previous state @type {Function} @param {Object} state
undoTitle ( state )
javascript
ktquez/vue-head
vue-head-es6.js
https://github.com/ktquez/vue-head/blob/master/vue-head-es6.js
MIT
undo () { if (!els.length) return els.forEach(el => el.parentElement.removeChild(el)) els = [] if(!substitutedEls.length) return substitutedEls.forEach((el, idx) => { var parent = el.parentElement parent.replaceChild(originalSubstitutedEls[idx], el) }) substitutedEls = [] originalSubstitutedEls = [] },
Undo elements to its previous state @type {Function}
undo ( )
javascript
ktquez/vue-head
vue-head-es6.js
https://github.com/ktquez/vue-head/blob/master/vue-head-es6.js
MIT
handle (arr, tag, place, update) { if (!arr) return arr.forEach(obj => { let parent = (obj.body) ? this.getPlace('body') : this.getPlace(place) let el = window.document.getElementById(obj.id) if (!el) { el = window.document.createElement(tag) update = false } // Elements that will substitute data if (el.hasAttribute('id')) { originalSubstitutedEls.push(el.cloneNode(true)) this.prepareElement(obj, el) substitutedEls.push(el) return } // Other elements this.prepareElement(obj, el) // Updated elements if (update) { diffEls.push(el) return } // Add elements in Node this.add(obj, el, parent) }) }
Handle of create elements @type {Function} @param {Array} arr @param {String} tag - style, link, meta, script, base @param {String} place - Default 'head' @param {Boolean} update
handle ( arr , tag , place , update )
javascript
ktquez/vue-head
vue-head-es6.js
https://github.com/ktquez/vue-head/blob/master/vue-head-es6.js
MIT
const VueHead = (Vue, options) => { if (installed) return installed = true if (options) { Vue.util.extend(opt, options) } function init (update) { let head = (typeof this.$options.head === 'function') ? this.$options.head.bind(this)() : this.$options.head if (!head) return Object.keys(head).forEach(key => { let prop = head[key] if (!prop) return let obj = (typeof prop === 'function') ? head[key].bind(this)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) this.$emit('okHead') } function destroy () { if (!this.$options.head) return util.undoTitle(diffTitle) util.undo() } // v1 if (Vue.version.match(/[1].(.)+/g)) { Vue.mixin({ ready () { init.call(this) }, destroyed () { destroy.call(this) }, events: { updateHead () { init.call(this, true) util.update() } } }) } // v2 if (Vue.version.match(/[2].(.)+/g)) { Vue.mixin({ created () { this.$on('updateHead', () => { init.call(this, true) util.update() }) }, mounted () { init.call(this) }, beforeDestroy () { destroy.call(this) } }) }
Plugin | vue-head @param {Function} Vue @param {Object} options
VueHead
javascript
ktquez/vue-head
vue-head-es6.js
https://github.com/ktquez/vue-head/blob/master/vue-head-es6.js
MIT
getPlace: function (place) { return window.document.getElementsByTagName(place)[0] },
This function return the element <head> @type {Function} @return {Object}
getPlace ( place )
javascript
ktquez/vue-head
vue-head.js
https://github.com/ktquez/vue-head/blob/master/vue-head.js
MIT
add: function (obj, el, parent) { parent.appendChild(el) // Fixed elements that do not suffer removal if (obj.undo !== undefined && !obj.undo) return // Elements which are removed els.push(el) },
Add Elements @param {Object} obj @param {HTMLElement} el @param {HTMLElement} parent
add ( obj , el , parent )
javascript
ktquez/vue-head
vue-head.js
https://github.com/ktquez/vue-head/blob/master/vue-head.js
MIT
function destroy () { if (!this.$options.head) return util.undoTitle(diffTitle) util.undo() }
Remove the meta tags elements in the head
destroy ( )
javascript
ktquez/vue-head
vue-head.js
https://github.com/ktquez/vue-head/blob/master/vue-head.js
MIT
function init (update) { var self = this var head = (typeof self.$options.head === 'function') ? self.$options.head.bind(self)() : self.$options.head if (!head) return Object.keys(head).forEach(function (key) { var prop = head[key] if (!prop) return var obj = (typeof prop === 'function') ? head[key].bind(self)() : head[key] if (key === 'title') { util[key](obj) return } util.handle(obj, key, 'head', update) }) self.$emit('okHead') } /** * Remove the meta tags elements in the head */ function destroy () { if (!this.$options.head) return util.undoTitle(diffTitle) util.undo() } // v1 if (Vue.version.match(/[1].(.)+/g)) { Vue.mixin({ ready: function () { init.call(this) }, destroyed: function () { destroy.call(this) }, events: { updateHead: function () { init.call(this, true) util.update() } } }) }
Initializes and updates the elements in the head @param {Boolean} update
init ( update )
javascript
ktquez/vue-head
vue-head.js
https://github.com/ktquez/vue-head/blob/master/vue-head.js
MIT
function resolveURL(url, base) { var p1 = parseURL(url); var p2 = parseURL(base); if (p1.scheme) return url; if (p1.path.indexOf('/') == 0) { return p2.scheme + '://' + p2.authority + p1.path + (p1.query ? '?' + p1.query : ''); } else { var b = (p2.path.lastIndexOf('/') != -1) ? p2.path.substring(0, p2.path.lastIndexOf('/')) : p2.path; return p2.scheme + '://' + p2.authority + b + '/' + p1.path + (p1.query ? '?' + p1.query : ''); } } function test() { // Some quick testcases... var testCases = [ ['test', 'https://google.com', 'https://google.com/test'], ['/test', 'https://google.com', 'https://google.com/test'], ['test', 'https://google.com/a', 'https://google.com/test'], ['/test', 'https://google.com/a', 'https://google.com/test'], ['test', 'https://google.com/a/', 'https://google.com/a/test'], ['/test', 'https://google.com/a/', 'https://google.com/test'], ['test', 'https://google.com/a/b', 'https://google.com/a/test'], ['/test', 'https://google.com/a/b', 'https://google.com/test'], ['test', 'https://google.com/a/b/', 'https://google.com/a/b/test'], ['/test', 'https://google.com/a/b/', 'https://google.com/test'], ['https://google.com', 'https://google.com', 'https://google.com'], ['/?abc', 'https://google.com', 'https://google.com/?abc'], ['/test?abc=2', 'https://google.com/ddd?a=23', 'https://google.com/test?abc=2'], ]; testCases.forEach(function (t) { var u1 = t[0]; var u2 = t[1]; var r = t[2]; var res = resolveURL(t[0], t[1]); console.info(t[0], t[1], res, res == t[2]); }); } module.exports = { parseURL: parseURL, resolveURL: resolveURL, test: test, };
Resolve URL url based off URL base (equivalent API to nodejs url.resolve with arguments flipped)
resolveURL ( url , base )
javascript
webosbrew/webos-homebrew-channel
frontend/baseurl.js
https://github.com/webosbrew/webos-homebrew-channel/blob/master/frontend/baseurl.js
MIT
var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; };
Utility function for retreiving the text value of an array of DOM nodes @param {Array|Element} elem
Sizzle.getText ( elem )
javascript
nwutils/nw-sample-apps
file-explorer/js/jquery-1.7.2.js
https://github.com/nwutils/nw-sample-apps/blob/master/file-explorer/js/jquery-1.7.2.js
MIT
CodeMirror.defineExtension("closeTag", function(cm, ch, indent) { if (!cm.getOption('closeTagEnabled')) { throw CodeMirror.Pass; } var mode = cm.getOption('mode'); if (mode == 'text/html') { /* * Relevant structure of token: * * htmlmixed * className * state * htmlState * type * context * tagName * mode * * xml * className * state * tagName * type */ var pos = cm.getCursor(); var tok = cm.getTokenAt(pos); var state = tok.state; if (state.mode && state.mode != 'html') { throw CodeMirror.Pass; // With htmlmixed, we only care about the html sub-mode. } if (ch == '>') { var type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml if (tok.className == 'tag' && type == 'closeTag') { throw CodeMirror.Pass; // Don't process the '>' at the end of an end-tag. } cm.replaceSelection('>'); // Mode state won't update until we finish the tag. pos = {line: pos.line, ch: pos.ch + 1}; cm.setCursor(pos); tok = cm.getTokenAt(cm.getCursor()); state = tok.state; type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml if (tok.className == 'tag' && type != 'selfcloseTag') { var tagName = state.htmlState ? state.htmlState.context.tagName : state.tagName; // htmlmixed : xml if (tagName.length > 0) { insertEndTag(cm, indent, pos, tagName); } return; } // Undo the '>' insert and allow cm to handle the key instead. cm.setSelection({line: pos.line, ch: pos.ch - 1}, pos); cm.replaceSelection(""); } else if (ch == '/') { if (tok.className == 'tag' && tok.string == '<') { var tagName = state.htmlState ? (state.htmlState.context ? state.htmlState.context.tagName : '') : state.context.tagName; // htmlmixed : xml # extra htmlmized check is for '</' edge case if (tagName.length > 0) { completeEndTag(cm, pos, tagName); return; } } } } throw CodeMirror.Pass; // Bubble if not handled });
Call during key processing to close tags. Handles the key event if the tag is closed, otherwise throws CodeMirror.Pass. - cm: The editor instance. - ch: The character being processed. - indent: Optional. Omit or pass true to use the default indentation tag list defined in the 'closeTagIndent' option. Pass false to disable indentation. Pass an array to override the default list of tag names.
(anonymous) ( cm , ch , indent )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/lib/util/closetag.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/lib/util/closetag.js
MIT
ModeTest.test = function() { ModeTest.tests += 1; var mode = CodeMirror.getMode(ModeTest.modeOptions, ModeTest.modeName); if (arguments.length < 1) { throw "must have text for test"; } if (arguments.length % 2 != 1) { throw "must have text for test plus expected (style, token) pairs"; } var text = arguments[0]; var expectedOutput = []; for (var i = 1; i < arguments.length; i += 2) { expectedOutput.push([arguments[i],arguments[i + 1]]); } var observedOutput = ModeTest.highlight(text, mode) var pass, passStyle = ""; if (expectedOutput.length > 0) { pass = ModeTest.highlightOutputsEqual(expectedOutput, observedOutput); passStyle = pass ? 'mt-pass' : 'mt-fail'; ModeTest.passes += pass ? 1 : 0; } var s = ''; s += '<div class="mt-test ' + passStyle + '">'; s += '<pre>' + ModeTest.htmlEscape(text) + '</pre>'; s += '<div class="cm-s-default">'; if (pass || expectedOutput.length == 0) { s += ModeTest.prettyPrintOutputTable(observedOutput); } else { s += 'expected:'; s += ModeTest.prettyPrintOutputTable(expectedOutput); s += 'observed:'; s += ModeTest.prettyPrintOutputTable(observedOutput); } s += '</div>'; s += '</div>'; document.write(s); }
Run a test; prettyprints the results using document.write(). @param string to highlight @param style[i] expected style of the i'th token in string @param token[i] expected value for the i'th token in string
ModeTest.test ( )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/test/mode_test.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/test/mode_test.js
MIT
ModeTest.highlight = function(string, mode) { var state = mode.startState() var lines = string.replace(/\r\n/g,'\n').split('\n'); var output = []; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; var stream = new CodeMirror.StringStream(line); if (line == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state); var substr = line.slice(stream.start, stream.pos); output.push([style, substr]); stream.start = stream.pos; } } return output; }
Emulation of CodeMirror's internal highlight routine for testing. Multi-line input is supported. @param string to highlight @param mode the mode that will do the actual highlighting @return array of [style, token] pairs
ModeTest.highlight ( string , mode )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/test/mode_test.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/test/mode_test.js
MIT
ModeTest.highlightOutputsEqual = function(o1, o2) { var eq = (o1.length == o2.length); if (eq) { for (var j in o1) { eq = eq && o1[j].length == 2 && o1[j][0] == o2[j][0] && o1[j][1] == o2[j][1]; } } return eq; }
Compare two arrays of output from ModeTest.highlight. @param o1 array of [style, token] pairs @param o2 array of [style, token] pairs @return boolean; true iff outputs equal
ModeTest.highlightOutputsEqual ( o1 , o2 )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/test/mode_test.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/test/mode_test.js
MIT
ModeTest.prettyPrintOutputTable = function(output) { var s = '<table class="mt-output">'; s += '<tr>'; for (var i = 0; i < output.length; ++i) { var token = output[i]; s += '<td class="mt-token">' + '<span class="cm-' + token[0] + '">' + ModeTest.htmlEscape(token[1]).replace(/ /g,'&middot;') + '</span>' + '</td>'; } s += '</tr><tr>'; for (var i = 0; i < output.length; ++i) { var token = output[i]; s += '<td class="mt-style"><span>' + token[0] + '</span></td>'; } s += '</table>'; return s; }
Print tokens and corresponding styles in a table. Spaces in the token are replaced with 'interpunct' dots (&middot;). @param output array of [style, token] pairs @return html string
ModeTest.prettyPrintOutputTable ( output )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/test/mode_test.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/test/mode_test.js
MIT
ModeTest.printSummary = function() { document.write(ModeTest.passes + ' passes for ' + ModeTest.tests + ' tests'); }
Print how many tests have run so far and how many of those passed.
ModeTest.printSummary ( )
javascript
nwutils/nw-sample-apps
mini-code-edit/cm/test/mode_test.js
https://github.com/nwutils/nw-sample-apps/blob/master/mini-code-edit/cm/test/mode_test.js
MIT
const extend = function () { let extended = {}; let deep = false; let i = 0; let length = arguments.length; /* Check if a deep merge */ if (Object.prototype.toString.call(arguments[0]) === "[object Boolean]") { deep = arguments[0]; i++; } /* Merge the object into the extended object */ let merge = function (obj) { for (let prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { /* If deep merge and property is an object, merge properties */ if (deep && Object.prototype.toString.call(obj[prop]) === "[object Object]") { extended[prop] = extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; /* Loop through each object and conduct a merge */ for (; i < length; i++) { let obj = arguments[i]; merge(obj); } return extended; };
Merge two or more objects. Returns a new object. @private @param {Boolean} deep If true, do a deep (or recursive) merge [optional] @param {Object} objects The objects to merge together @returns {Object} Merged values of defaults and options
extend ( )
javascript
tuupola/lazyload
lazyload.js
https://github.com/tuupola/lazyload/blob/master/lazyload.js
MIT
var __cookie = function(key, value) { var cookieName = 'jqfs', cookieDays = 365, result, date = new Date(), jar = {}, expires = '', x, pts, pt; result = (result = new RegExp('(?:^|; )'+cookieName+'=([^;]*)').exec(document.cookie)) ? decodeURIComponent(result[1]) : null; if (null !== result) { pts = result.split('||'); for (x in pts) { try { pt = pts[x].split('|',2); jar[pt[0]] = pt[1]; } catch (e) {} } } // Get cookie: if (1 === arguments.length) { return jar[key]; } // Set cookie if (null === value || false === value) { delete jar[key]; } else { jar[key] = value; } pts = []; for (x in jar) { pts.push(x+'|'+jar[x]); } if (cookieDays > 0) { date.setTime(date.getTime()+(cookieDays*24*60*60*1000)); expires = '; expires='+date.toGMTString(); } document.cookie = cookieName + '=' + encodeURIComponent(pts.join('||')) + '; path=/; SameSite=Lax' + expires; };
Utility function for getting/setting cookies. This function stores multiple values in one single cookie: max efficiency! Also: this function gets/sets cookies that PHP can also get/set (static Cookie class). Cookies are valid for 365 days. @param {string} key Name of the value to store. @param {string} value Value to store. Omit to get a cookie, provide to set a cookie. @return {string} The value for a cookie (when value is omitted, of course).
__cookie ( key , value )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
loadFont: function(type, font) { if (fontsLoaded[font]) { return; } fontsLoaded[font] = true; switch(type) { case 'google': var url = 'https://fonts.googleapis.com/css?family=' + font.replace(/ /g,'+') + ':' + this.options.googleFonts[font].variants + '&display=swap'; this.options.debug && console.log('Loading Google font ' + font + ' from ' + url); $('head').append($('<link>', {href:url, rel:'stylesheet', type:'text/css'})); break; case 'local': this.options.debug && console.log('Loading local font ' + font); $('head').append("<style> @font-face { font-family:'" + font + "'; src:local('" + font + "'), url('" + this.options.localFontsUrl + font + ".woff') format('woff'); } </style>"); break; } },
Load font, either from Google or from local url. @param {string} type Font type, either 'google' or 'local'. @param {string} font Font family name. F.e: 'Chakra', 'Zilla Slab'.
loadFont ( type , font )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
getFavorites: function() { var favoriteFonts = __cookie('favs'), recentFonts = __cookie('recents'); favoriteFonts = favoriteFonts ? favoriteFonts.split(',') : []; recentFonts = (!!this.options.nrRecents && recentFonts) ? recentFonts.split(',') : []; // Dedupe: var fonts = recentFonts.slice(0); for (var f = 0; f < favoriteFonts.length; f++) { if (fonts.indexOf(favoriteFonts[f]) == -1) { fonts.push(favoriteFonts[f]); } } var $frag = $(document.createDocumentFragment()), $li = null, $orgLi, tmp; var fontType = ""; var fontFamily = ""; var font = undefined; for (var f = 0; f < fonts.length; f++) { tmp = fonts[f].split(':'), fontType = tmp[0], fontFamily = tmp[1], font = this.allFonts[fontType][fontFamily]; if (!font) { continue; } $orgLi = $("[data-font-family='" + fontFamily + "']", this.$results); if ($orgLi.length > 0) { $li = $orgLi.clone().addClass('fp-fav'); $frag.append($li[0]); } } if (null !== $li) { $frag.prepend($('<li class="fp-fav fp-divider">' + this.dictionary['favFonts'] + '</li>')[0]); this.$results.prepend($frag); } },
Construct list of favorited and recently picked fonts
getFavorites ( )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
function stopPropagation(e) { e.stopPropagation(); }
stopPropagation - makes the code only doing this a little easier to read in line
stopPropagation ( e )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
function bind(func, obj) { var slice = Array.prototype.slice; var args = slice.call(arguments, 2); return function () { return func.apply(obj, args.concat(slice.call(arguments))); }; }
Create a function bound to a given object Thanks to underscore.js
bind ( func , obj )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
function draggable(element, onmove, onstart, onstop) { onmove = onmove || function () { }; onstart = onstart || function () { }; onstop = onstop || function () { }; var doc = document; var dragging = false; var offset = {}; var maxHeight = 0; var maxWidth = 0; var hasTouch = ('ontouchstart' in window); var duringDragEvents = {}; duringDragEvents["selectstart"] = prevent; duringDragEvents["dragstart"] = prevent; duringDragEvents["touchmove mousemove"] = move; duringDragEvents["touchend mouseup"] = stop; function prevent(e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } e.returnValue = false; } function move(e) { if (dragging) { // Mouseup happened outside of window if (IE && doc.documentMode < 9 && !e.button) { return stop(); } var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0]; var pageX = t0 && t0.pageX || e.pageX; var pageY = t0 && t0.pageY || e.pageY; var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); if (hasTouch) { // Stop scrolling in iOS prevent(e); } onmove.apply(element, [dragX, dragY, e]); } } function start(e) { var rightclick = (e.which) ? (e.which == 3) : (e.button == 2); if (!rightclick && !dragging) { if (onstart.apply(element, arguments) !== false) { dragging = true; maxHeight = $(element).height(); maxWidth = $(element).width(); offset = $(element).offset(); $(doc).on(duringDragEvents); $(doc.body).addClass("sp-dragging"); move(e); prevent(e); } } } function stop() { if (dragging) { $(doc).off(duringDragEvents); $(doc.body).removeClass("sp-dragging"); // Wait a tick before notifying observers to allow the click event // to fire in Chrome. setTimeout(function() { onstop.apply(element, arguments); }, 0); } dragging = false; } $(element).on("touchstart mousedown", start); }
Lightweight drag helper. Handles containment within the element, so that when dragging, the x is within [0,element.width] and y is within [0,element.height]
draggable ( element , onmove , onstart , onstop )
javascript
danieladov/jellyfin-plugin-skin-manager
Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
https://github.com/danieladov/jellyfin-plugin-skin-manager/blob/master/Jellyfin.Plugin.SkinManager/Configuration/fontpicker.js
MIT
included(app) { let assetRev = this.project.addons.find(addon => addon.name === 'broccoli-asset-rev'); if (assetRev && !assetRev.supportsFastboot) { throw new SilentError( 'This version of ember-cli-fastboot requires a newer version of broccoli-asset-rev' ); } // set autoRun to false since we will conditionally include creating app when app files // is eval'd in app-boot app.options.autoRun = false; app.import('vendor/experimental-render-mode-rehydrate.js'); // get the app registry object and app name so that we can build the fastboot // tree this._appRegistry = app.registry; this._name = app.name; this.fastbootOptions = this._fastbootOptionsFor(app.env, app.project); migrateInitializers(this.project); },
Called at the start of the build process to let the addon know it will be used. Sets the auto run on app to be false so that we create and route app automatically only in browser. See: https://ember-cli.com/user-guide/#integration
included ( app )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/index.js
MIT
importTransforms() { return { fastbootShim: fastbootTransform, }; },
Registers the fastboot shim that allows apps and addons to wrap non-compatible libraries in Node with a FastBoot check using `app.import`.
importTransforms ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/index.js
MIT
contentFor(type, config, contents) { if (type === 'body') { return '<!-- EMBER_CLI_FASTBOOT_BODY -->'; } if (type === 'head') { return '<!-- EMBER_CLI_FASTBOOT_TITLE --><!-- EMBER_CLI_FASTBOOT_HEAD -->'; } if (type === 'app-boot') { return fastbootAppBoot(config.modulePrefix, JSON.stringify(config.APP || {})); } // if the fastboot addon is installed, we overwrite the config-module so that the config can be read // from meta tag/directly for browser build and from Fastboot config for fastboot target. if (type === 'config-module') { const originalContents = contents.join(''); const appConfigModule = `${config.modulePrefix}`; contents.splice(0, contents.length); contents.push( "if (typeof FastBoot !== 'undefined') {", "return FastBoot.config('" + appConfigModule + "');", '} else {', originalContents, '}' ); return; } },
Inserts placeholders into index.html that are used by the FastBoot server to insert the rendered content into the right spot. Also injects a module for FastBoot application boot.
contentFor ( type , config , contents )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/index.js
MIT
_getFastbootTree() { const appName = this._name; let fastbootTrees = []; this._processAddons(this.project.addons, fastbootTrees); // check the parent containing the fastboot directory const projectFastbootPath = path.join(this.project.root, 'fastboot'); // ignore the project's fastboot folder if we are an addon, as that is already handled above if (!this.project.isEmberCLIAddon() && this.existsSync(projectFastbootPath)) { let fastbootTree = this.treeGenerator(projectFastbootPath); fastbootTrees.push(fastbootTree); } // transpile the fastboot JS tree let mergedFastBootTree = new MergeTrees(fastbootTrees, { overwrite: true, }); let funneledFastbootTrees = new Funnel(mergedFastBootTree, { destDir: appName, }); const processExtraTree = p.preprocessJs(funneledFastbootTrees, '/', this._name, { registry: this._appRegistry, }); // FastBoot app factory module const writeFile = require('broccoli-file-creator'); let appFactoryModuleTree = writeFile('app-factory.js', fastbootAppFactoryModule(appName)); let newProcessExtraTree = new MergeTrees([processExtraTree, appFactoryModuleTree], { overwrite: true, }); function stripLeadingSlash(filePath) { return filePath.replace(/^\//, ''); } let appFilePath = stripLeadingSlash(this.app.options.outputPaths.app.js); let finalFastbootTree = new Concat(newProcessExtraTree, { outputFile: appFilePath.replace(/\.js$/, '-fastboot.js'), });
Function that builds the fastboot tree from all fastboot complaint addons and project and transpiles it into appname-fastboot.js
_getFastbootTree ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/index.js
MIT
build() { this.buildConfig(); this.buildDependencies(); this.buildManifest(); this.buildHostWhitelist(); let outputPath = path.join(this.outputPath, 'package.json'); this.writeFileIfContentChanged(outputPath, this.toJSONString()); }
The main hook called by Broccoli Plugin. Used to build or rebuild the tree. In this case, we generate the configuration and write it to `package.json`.
build ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js
MIT
function _checkInitializerTypeExists(rootPath, type) { const isTypeExists = fastbootInitializerTypes.some((fastbootInitializerType) => { const pathType = path.join(rootPath, 'app', fastbootInitializerType, type); return existsSync(pathType); }); return isTypeExists; }
Helper function to check if there are any `(instance-)?intializers/[browser|fastboot]/` path under the given root path. @param {String} rootPath @param {String} type @returns {Boolean} true if path exists
_checkInitializerTypeExists ( rootPath , type )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
function _checkBrowserInitializers(rootPath) { const isBrowserInitializersPresent = _checkInitializerTypeExists(rootPath, 'browser'); if (isBrowserInitializersPresent) { const errorMsg = `FastBoot build no longer supports ${rootPath}/app/(instance-)?initializers/browser structure. ` + `Please refer to http://ember-fastboot.com/docs/addon-author-guide#browser-only-or-node-only-initializers for a migration path.`; throw new SilentError(errorMsg); } }
Helper function to check if there are any `(instance-)?intializers/browser/` path under the given root path and throw an error @param {String} rootPath
_checkBrowserInitializers ( rootPath )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
function _checkFastBootInitializers(project, rootPath) { // check to see if it is a fastboot complaint addon const isFastbootAddon = _checkInitializerTypeExists(rootPath, 'fastboot'); if (isFastbootAddon) { throw new SilentError(`Having fastboot specific code in app directory of ${rootPath} is deprecated. Please move it to fastboot/app directory.`); } }
Function to move the fastboot initializers to fastboot/app @param {Object} project @param {String} rootPath
_checkFastBootInitializers ( project , rootPath )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
function _migrateAddonInitializers(project) { project.addons.forEach(addon => { const currentAddonPath = addon.root; _checkBrowserInitializers(currentAddonPath); _checkFastBootInitializers(project, currentAddonPath); }); }
Function that migrates the fastboot initializers for all addons. @param {Object} project
_migrateAddonInitializers ( project )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
function _migrateHostAppInitializers(project) { const hostAppPath = path.join(project.root); _checkBrowserInitializers(hostAppPath); _checkFastBootInitializers(project, hostAppPath); }
Function to migrate fastboot initializers for host app. @param {Object} project
_migrateHostAppInitializers ( project )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
module.exports = function migrateInitializers(project) { _migrateAddonInitializers(project); _migrateHostAppInitializers(project); };
Function that migrates all addons and host app fastboot initializers to fastboot/app. It also throws an error if any addon or host app has browser forked initializers. @param {Object} project
migrateInitializers ( project )
javascript
ember-fastboot/ember-cli-fastboot
packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/ember-cli-fastboot/lib/build-utilities/migrate-initializers.js
MIT
function DAG() { this.names = []; this.vertices = Object.create(null);
DAG stands for Directed acyclic graph. It is used to build a graph of dependencies checking that there isn't circular dependencies. p.e Registering initializers with a certain precedence order. @class DAG @constructor
DAG ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot-app-server/test/fixtures/basic-app/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot-app-server/test/fixtures/basic-app/assets/vendor.js
MIT
var DAG = function () { function DAG() { this._vertices = new Vertices();
A topologically ordered map of key/value pairs with a simple API for adding constraints. Edges can forward reference keys that have not been added yet (the forward reference will map the key to undefined).
DAG ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot-app-server/test/fixtures/global-app/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot-app-server/test/fixtures/global-app/assets/vendor.js
MIT
}, { key: 'metadata',
meta information about internalModels
get ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot-app-server/test/fixtures/global-app/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot-app-server/test/fixtures/global-app/assets/vendor.js
MIT
(function() { // Get a handle on the global object var local; if (typeof global !== 'undefined') local = global; else if (typeof window !== 'undefined' && window.document) local = window; else local = self; // It's replaced unconditionally to preserve the expected behavior // in programs even if there's ever a native finally. local.Promise.prototype['finally'] = function finallyPolyfill(callback) { var constructor = this.constructor; return this.then(function(value) { return constructor.resolve(callback()).then(function() { return value; }); }, function(reason) { return constructor.resolve(callback()).then(function() { throw reason; }); }); }; }());
Promise.prototype.finally Pulled from https://github.com/domenic/promises-unwrapping/issues/18#issuecomment-57801572 @author @stefanpenner, @matthew-andrews
(anonymous) ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot-express-middleware/test/fixtures/rejected-promise/app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot-express-middleware/test/fixtures/rejected-promise/app.js
MIT
var Register; (function (Register) { // $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit Register[Register["pc"] = 0] = "pc"; // $1 or $ra (return address): pointer into `program` for the return Register[Register["ra"] = 1] = "ra"; // $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack Register[Register["fp"] = 2] = "fp"; // $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack Register[Register["sp"] = 3] = "sp"; // $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers Register[Register["s0"] = 4] = "s0"; Register[Register["s1"] = 5] = "s1"; // $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers Register[Register["t0"] = 6] = "t0"; Register[Register["t1"] = 7] = "t1";
Registers For the most part, these follows MIPS naming conventions, however the register numbers are different.
(anonymous) ( Register )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/custom-body-attrs/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/custom-body-attrs/assets/vendor.js
MIT
var Heap = function () { function Heap(serializedHeap) { (0, _emberBabel.classCallCheck)(this, Heap); this.placeholders = []; this.offset = 0; this.handle = 0; this.capacity = PAGE_SIZE; if (serializedHeap) { var buffer = serializedHeap.buffer, table = serializedHeap.table, handle = serializedHeap.handle; this.heap = new Uint16Array(buffer); this.table = table; this.offset = this.heap.length; this.handle = handle; this.capacity = 0; } else { this.heap = new Uint16Array(PAGE_SIZE); this.table = []; }
The Heap is responsible for dynamically allocating memory in which we read/write the VM's instructions from/to. When we malloc we pass out a VMHandle, which is used as an indirect way of accessing the memory during execution of the VM. Internally we track the different regions of the memory in an int array known as the table. The table 32-bit aligned and has the following layout: | ... | hp (u32) | info (u32) | | ... | Handle | Size | Scope Size | State | | ... | 32-bits | 16b | 14b | 2b | With this information we effectively have the ability to control when we want to free memory. That being said you can not free during execution as raw address are only valid during the execution. This means you cannot close over them as you will have a bad memory access exception.
Heap ( serializedHeap )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
MIT
DeferredActionQueues.prototype.schedule = function schedule(queueName, target, method, args, onceFlag, stack) { var queues = this.queues; var queue = queues[queueName]; if (queue === undefined) { throw new Error('You attempted to schedule an action in a queue (' + queueName + ') that doesn\'t exist'); } if (method === undefined || method === null) { throw new Error('You attempted to schedule an action in a queue (' + queueName + ') for a method that doesn\'t exist'); } this.queueNameIndex = 0; if (onceFlag) { return queue.pushUnique(target, method, args, stack); } else { return queue.push(target, method, args, stack); }
@method schedule @param {String} queueName @param {Any} target @param {Any} method @param {Any} args @param {Boolean} onceFlag @param {Any} stack @return queue
schedule ( queueName , target , method , args , onceFlag , stack )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
MIT
var CustomComponentState = function () { function CustomComponentState(delegate, component, args) { (0, _emberBabel.classCallCheck)(this, CustomComponentState); this.delegate = delegate; this.component = component; this.args = args;
Stores internal state about a component instance after it's been created.
CustomComponentState ( delegate , component , args )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
MIT
RuntimeResolver.prototype.lookupComponentDefinition = function lookupComponentDefinition(name, meta) { (true && !(name !== 'textarea') && (0, _debug.assert)('You cannot use `textarea` as a component name.', name !== 'textarea')); (true && !(name !== 'input') && (0, _debug.assert)('You cannot use `input` as a component name.', name !== 'input')); var handle = this.lookupComponentHandle(name, meta); if (handle === null) { (true && !(false) && (0, _debug.assert)('Could not find component named "' + name + '" (no component or template with that name was found)')); return null; } return this.resolve(handle);
public componentDefHandleCount = 0; Called while executing Append Op.PushDynamicComponentManager if string
lookupComponentDefinition ( name , meta )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-dependencies/assets/vendor.js
MIT
resolve(handle) { return this.handles[handle]; } // End IRuntimeResolver
Called by RuntimeConstants to lookup unresolved handles.
resolve ( handle )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
lookupHelper(name, meta) { var nextHandle = this.handles.length; var helper$$1 = this._lookupHelper(name, meta); if (helper$$1 !== null) { var handle = this.handle(helper$$1); if (nextHandle === handle) { this.helperDefinitionCount++; } return handle; } return null; }
Called by CompileTimeLookup compiling Unknown or Helper OpCode
lookupHelper ( name , meta )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
lookupModifier(name, meta) { return this.handle(this._lookupModifier(name, meta)); }
Called by CompileTimeLookup compiling the
lookupModifier ( name , meta )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
lookupPartial(name, meta) { var partial = this._lookupPartial(name, meta); return this.handle(partial); } // end CompileTimeLookup
Called by CompileTimeLookup to lookup partial
lookupPartial ( name , meta )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function revalidateObservers(target) { if (ASYNC_OBSERVERS.has(target)) { ASYNC_OBSERVERS.get(target).forEach(observer => { observer.tag = (0, _reference.combine)(getChainTagsForKey(target, observer.path)); observer.lastRevision = (0, _reference.value)(observer.tag); }); } if (SYNC_OBSERVERS.has(target)) { SYNC_OBSERVERS.get(target).forEach(observer => { observer.tag = (0, _reference.combine)(getChainTagsForKey(target, observer.path)); observer.lastRevision = (0, _reference.value)(observer.tag); }); } }
Primarily used for cases where we are redefining a class, e.g. mixins/reopen being applied later. Revalidates all the observers, resetting their tags. @private @param target
revalidateObservers ( target )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
replayable({ args, body }) { // Start a new label frame, to give END and RETURN // a unique meaning. this.startLabels(); this.pushFrame(); // If the body invokes a block, its return will return to // END. Otherwise, the return in RETURN will return to END. this.returnTo('ENDINITIAL'); // Push the arguments onto the stack. The args() function // tells us how many stack elements to retain for re-execution // when updating. var count = args(); // Start a new updating closure, remembering `count` elements // from the stack. Everything after this point, and before END, // will execute both initially and to update the block. // // The enter and exit opcodes also track the area of the DOM // associated with this block. If an assertion inside the block // fails (for example, the test value changes from true to false // in an #if), the DOM is cleared and the program is re-executed, // restoring `count` elements to the stack and executing the // instructions between the enter and exit. this.enter(count); // Evaluate the body of the block. The body of the block may // return, which will jump execution to END during initial // execution, and exit the updating routine. body(); // All execution paths in the body should run the FINALLY once // they are done. It is executed both during initial execution // and during updating execution. this.label('FINALLY'); // Finalize the DOM. this.exit(); // In initial execution, this is a noop: it returns to the // immediately following opcode. In updating execution, this // exits the updating routine. this.return(); // Cleanup code for the block. Runs on initial execution // but not on updating. this.label('ENDINITIAL'); this.popFrame();
A convenience for pushing some arguments on the stack and running some code if the code needs to be re-executed during updating execution if some of the arguments have changed. # Initial Execution The `args` function should push zero or more arguments onto the stack and return the number of arguments pushed. The `body` function provides the instructions to execute both during initial execution and during updating execution. Internally, this function starts by pushing a new frame, so that the body can return and sets the return point ($ra) to the ENDINITIAL label. It then executes the `args` function, which adds instructions responsible for pushing the arguments for the block to the stack. These arguments will be restored to the stack before updating execution. Next, it adds the Enter opcode, which marks the current position in the DOM, and remembers the current $pc (the next instruction) as the first instruction to execute during updating execution. Next, it runs `body`, which adds the opcodes that should execute both during initial execution and during updating execution. If the `body` wishes to finish early, it should Jump to the `FINALLY` label. Next, it adds the FINALLY label, followed by: - the Exit opcode, which finalizes the marked DOM started by the Enter opcode. - the Return opcode, which returns to the current return point ($ra). Finally, it adds the ENDINITIAL label followed by the PopFrame instruction, which restores $fp, $sp and $ra. # Updating Execution Updating execution for this `replayable` occurs if the `body` added an assertion, via one of the `JumpIf`, `JumpUnless` or `AssertSame` opcodes. If, during updating executon, the assertion fails, the initial VM is restored, and the stored arguments are pushed onto the stack. The DOM between the starting and ending markers is cleared, and the VM's cursor is set to the area just cleared. The return point ($ra) is set to -1, the exit instruction. Finally, the $pc is set to to the instruction saved off by the Enter opcode during initial execution, and execution proceeds as usual. The only difference is that when a `Return` instruction is encountered, the program jumps to -1 rather than the END label, and the PopFrame opcode is not needed.
replayable ( { args , body } )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
class Heap { constructor(serializedHeap) { this.placeholders = []; this.offset = 0; this.handle = 0; this.capacity = PAGE_SIZE; if (serializedHeap) { var { buffer, table, handle } = serializedHeap; this.heap = new Uint32Array(buffer); this.table = table; this.offset = this.heap.length; this.handle = handle; this.capacity = 0; } else { this.heap = new Uint32Array(PAGE_SIZE); this.table = [];
The Heap is responsible for dynamically allocating memory in which we read/write the VM's instructions from/to. When we malloc we pass out a VMHandle, which is used as an indirect way of accessing the memory during execution of the VM. Internally we track the different regions of the memory in an int array known as the table. The table 32-bit aligned and has the following layout: | ... | hp (u32) | info (u32) | size (u32) | | ... | Handle | Scope Size | State | Size | | ... | 32bits | 30bits | 2bits | 32bit | With this information we effectively have the ability to control when we want to free memory. That being said you can not free during execution as raw address are only valid during the execution. This means you cannot close over them as you will have a bad memory access exception.
constructor ( serializedHeap )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
_exports.COMPUTE = COMPUTE; function value(_tag) {
`value` receives a tag and returns an opaque Revision based on that tag. This snapshot can then later be passed to `validate` with the same tag to determine if the tag has changed at all since the time that `value` was called. The current implementation returns the global revision count directly for performance reasons. This is an implementation detail, and should not be relied on directly by users of these APIs. Instead, Revisions should be treated as if they are opaque/unknown, and should only be interacted with via the `value`/`validate` API. @param tag
value ( _tag )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function validate(tag, snapshot) {
`validate` receives a tag and a snapshot from a previous call to `value` with the same tag, and determines if the tag is still valid compared to the snapshot. If the tag's state has changed at all since then, `validate` will return false, otherwise it will return true. This is used to determine if a calculation related to the tags should be rerun. @param tag @param snapshot
validate ( tag , snapshot )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function renderComponent(program, env, builder, main, name, args = {}) { var vm = VM.empty(program, env, builder, main); var { resolver } = vm.constants; var definition = resolveComponent(resolver, name, null); var { manager, state } = definition; var capabilities = capabilityFlagsFrom(manager.getCapabilities(state)); var invocation; if (hasStaticLayoutCapability(capabilities, manager)) { invocation = manager.getLayout(state, resolver); } else { throw new Error('Cannot invoke components with dynamic layouts as a root component.'); } // Get a list of tuples of argument names and references, like // [['title', reference], ['name', reference]] var argList = Object.keys(args).map(key => [key, args[key]]); var blockNames = ['main', 'else', 'attrs']; // Prefix argument names with `@` symbol var argNames = argList.map(([name]) => "@" + name); vm.pushFrame(); // Push blocks on to the stack, three stack values per block for (var i = 0; i < 3 * blockNames.length; i++) { vm.stack.push(null); } vm.stack.push(null); // For each argument, push its backing reference on to the stack argList.forEach(([, reference]) => { vm.stack.push(reference); }); // Configure VM based on blocks and args just pushed on to the stack. vm.args.setup(vm.stack, argNames, blockNames, 0, false); // Needed for the Op.Main opcode: arguments, component invocation object, and // component definition. vm.stack.push(vm.args); vm.stack.push(invocation); vm.stack.push(definition);
Returns a TemplateIterator configured to render a root component.
renderComponent ( program , env , builder , main , name , args = { } )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
flush(fromAutorun = false) { var queue; var queueName; var numberOfQueues = this.queueNames.length; while (this.queueNameIndex < numberOfQueues) { queueName = this.queueNames[this.queueNameIndex]; queue = this.queues[queueName]; if (queue.hasWork() === false) { this.queueNameIndex++; if (fromAutorun && this.queueNameIndex < numberOfQueues) { return 1 /* Pause */ ; } } else { if (queue.flush(false /* async */ ) === 1 /* Pause */ ) { return 1 /* Pause */ ; } }
DeferredActionQueues.flush() calls Queue.flush() @method flush @param {Boolean} fromAutorun
flush ( fromAutorun = false )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
_getDebugInfo(debugEnabled) { if (debugEnabled) { var debugInfo = {}; var queue; var queueName; var numberOfQueues = this.queueNames.length; var i = 0; while (i < numberOfQueues) { queueName = this.queueNames[i]; queue = this.queues[queueName]; debugInfo[queueName] = queue._getDebugInfo(debugEnabled); i++; } return debugInfo; }
Returns debug information for the current queues. @method _getDebugInfo @param {Boolean} debugEnabled @returns {IDebugInfo | undefined}
_getDebugInfo ( debugEnabled )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
defer(queueName, target, method, ...args) { deferCount++;
@deprecated please use schedule instead.
defer ( queueName , target , method , ... args )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
deferOnce(queueName, target, method, ...args) { deferOnceCount++;
@deprecated please use scheduleOnce instead.
deferOnce ( queueName , target , method , ... args )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
DAG.prototype.add = function (key, value, before, after) { if (!key) throw new Error('argument `key` is required'); var vertices = this._vertices; var v = vertices.add(key); v.val = value; if (before) { if (typeof before === "string") { vertices.addEdge(v, vertices.add(before)); } else { for (var i = 0; i < before.length; i++) { vertices.addEdge(v, vertices.add(before[i])); } } } if (after) { if (typeof after === "string") { vertices.addEdge(vertices.add(after), v); } else { for (var i = 0; i < after.length; i++) { vertices.addEdge(vertices.add(after[i]), v); } }
Adds a key/value pair with dependencies on other key/value pairs. @public @param key The key of the vertex to be added. @param value The value of that vertex. @param before A key or array of keys of the vertices that must be visited before this vertex. @param after An string or array of strings with the keys of the vertices that must be after this vertex is visited.
DAG.prototype.add ( key , value , before , after )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
DAG.prototype.each = function (callback) {
Visits key/value pairs in topological order. @public @param callback The function to be invoked with each key/value.
DAG.prototype.each ( callback )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function loadInitializers(app, prefix) { var initializerPrefix = prefix + '/initializers/'; var instanceInitializerPrefix = prefix + '/instance-initializers/'; var initializers = []; var instanceInitializers = []; // this is 2 pass because generally the first pass is the problem // and is reduced, and resolveInitializer has potential to deopt var moduleNames = Object.keys(self.requirejs._eak_seen); for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; if (moduleName.lastIndexOf(initializerPrefix, 0) === 0) { if (!_endsWith(moduleName, '-test')) { initializers.push(moduleName); } } else if (moduleName.lastIndexOf(instanceInitializerPrefix, 0) === 0) { if (!_endsWith(moduleName, '-test')) { instanceInitializers.push(moduleName); } } } registerInitializers(app, initializers); registerInstanceInitializers(app, instanceInitializers);
Configure your application as it boots
loadInitializers ( app , prefix )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
register() { if (!this.isRegistered) { (0, _waiterManager.register)(this); this.isRegistered = true;
Will register the waiter, allowing it to be opted in to pausing async operations until they're completed within your tests. You should invoke it after instantiating your `TestWaiter` instance. **Note**, if you forget to register your waiter, it will be registered for you on the first invocation of `beginAsync`. @private @method register
register ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
debugInfo() { return [...this.items.values()]; } }
Returns the `debugInfo` for each item tracking async operations in this waiter. @public @method debugInfo @returns {ITestWaiterDebugInfo}
this.items.values ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function hasPendingWaiters() { let state = getPendingWaiterState(); return state.pending > 0;
Determines if there are any pending waiters. @returns {boolean} `true` if there are pending waiters, otherwise `false`.
hasPendingWaiters ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
function getPendingWaiterState() { let result = { pending: 0, waiters: {} }; WAITERS.forEach(waiter => { if (!waiter.waitUntil()) { result.pending++; let debugInfo = waiter.debugInfo(); result.waiters[waiter.name] = debugInfo || true; } }); return result; } /** * Determines if there are any pending waiters. * * @returns {boolean} `true` if there are pending waiters, otherwise `false`. */ function hasPendingWaiters() { let state = getPendingWaiterState(); return state.pending > 0;
Gets the current state of all waiters. Any waiters whose `waitUntil` method returns false will be considered `pending`. @returns {IPendingWaiterState} An object containing a count of all waiters pending and a `waiters` object containing the name of all pending waiters and their debug info.
getPendingWaiterState ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/app-with-prototype-mutations/assets/vendor.js
MIT
run(cb) { return cb.call(this.context, this.context); }
Runs a given function in the sandbox with providing the context and the sandbox object. Can be used to run functions outside of the sandbox in the sandbox. @todo: use this when we create app factory from addon
run ( cb )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/custom-sandbox/custom-sandbox.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/custom-sandbox/custom-sandbox.js
MIT
buildWrappedConsole() { var wrappedConsole = Object.create(console); wrappedConsole.error = function() { console.error.apply(console, Array.prototype.map.call(arguments, function(a) { return a; })); }; return wrappedConsole; }
Wraps console.error with sending the error over the channel as well so that it is reported by EKG. // TODO: change this function to send error over the channel instead.
buildWrappedConsole ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/test/fixtures/custom-sandbox/custom-sandbox.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/test/fixtures/custom-sandbox/custom-sandbox.js
MIT
html() { let response = this._fastbootInfo.response; let statusCode = response && this._fastbootInfo.response.statusCode; if (statusCode === 204) { this._html = ''; this._head = ''; this._body = ''; } else if (statusCode >= 300 && statusCode <= 399) { let location = response.headers.get('location'); this._html = '<body><!-- EMBER_CLI_FASTBOOT_BODY --></body>'; this._head = ''; this._body = ''; if (location) { this._body = `<h1>Redirecting to <a href="${location}">${location}</a></h1>`; } } return insertIntoIndexHTML( this._html, this._htmlAttributes, this._htmlClass, this._head, this._body, this._bodyAttributes, this._bodyClass ); }
Returns the HTML representation of the rendered route, inserted into the application's `index.html`. @returns {Promise<String>} the application's DOM serialized to HTML
html ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/result.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/result.js
MIT
chunks() { return insertIntoIndexHTML( this._html, this._htmlAttributes, this._htmlClass, this._head, this._body, this._bodyAttributes, this._bodyClass ).then(html => { let docParts = html.match(HTML_HEAD_REGEX); if (!docParts || docParts.length === 1) { return [html]; } let [, head, body] = docParts; if (!head || !body) { throw new Error( 'Could not idenfity head and body of the document! Make sure the document is well formed.' ); } let [plainBody, ...shoeboxes] = body.split(SHOEBOX_TAG_PATTERN); let chunks = [head, plainBody].concat( shoeboxes.map(shoebox => `${SHOEBOX_TAG_PATTERN}${shoebox}`) ); return chunks; }); }
Returns the HTML representation of the rendered route, inserted into the application's `index.html`, split into chunks. The first chunk contains the document's head, the second contains the body until just before the shoebox tags (if there are any) and the last chunk contains the shoebox tags and the closing `body` tag. If there are no shoebox tags, there are only 2 chunks and the second one contains the complete document body, including the closing `body` tag. @returns {Promise<Array<String>>} the application's DOM serialized to HTML, split into chunks
chunks ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/result.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/result.js
MIT
domContents() { return { head: this._head, body: this._body, }; }
Returns the serialized representation of DOM HEAD and DOM BODY @returns {Object} serialized version of DOM
domContents ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/result.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/result.js
MIT
_finalize() { if (this.finalized) { throw new Error('Results cannot be finalized more than once'); } // Grab some metadata from the sandboxed application instance // and copy it to this Result object. let { applicationInstanceInstance } = this; if (applicationInstanceInstance) { this._finalizeMetadata(applicationInstanceInstance); } this._finalizeHTML(); this.finalized = true; return this; }
@private Called once the Result has finished being constructed and the ApplicationInstance instance has finished rendering. Once `finalize()` is called, state is gathered from the completed ApplicationInstance instance and statically copied to this Result instance.
_finalize ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/result.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/result.js
MIT
constructor(options) { this.buildSandboxGlobals = options.buildSandboxGlobals || defaultBuildSandboxGlobals; let distPath = (this.distPath = path.resolve(options.distPath)); let config = loadConfig(distPath); this.hostWhitelist = config.hostWhitelist; this.config = config.config; this.appName = config.appName; this.html = config.html; this.sandboxRequire = config.sandboxRequire; if (process.env.APP_CONFIG) { let appConfig = JSON.parse(process.env.APP_CONFIG); let appConfigKey = this.appName; if (!(appConfigKey in appConfig)) { this.config[appConfigKey] = appConfig; } } if (process.env.ALL_CONFIG) { let allConfig = JSON.parse(process.env.ALL_CONFIG); this.config = allConfig; } if (process.env.FASTBOOT_SOURCEMAPS_DISABLE) { this.scripts = buildScripts([...config.scripts]); } else { this.scripts = buildScripts([ require.resolve('./scripts/install-source-map-support'), ...config.scripts, ]); } // default to 1 if maxSandboxQueueSize is not defined so the sandbox is pre-warmed when process comes up const maxSandboxQueueSize = options.maxSandboxQueueSize || 1; // Ensure that the dist files can be evaluated and the `Ember.Application` // instance created. this.buildSandboxQueue(maxSandboxQueueSize); }
Create a new EmberApp. @param {Object} options @param {string} options.distPath - path to the built Ember application @param {Function} [options.buildSandboxGlobals] - the function used to build the final set of global properties accesible within the sandbox @param {Number} [options.maxSandboxQueueSize] - maximum sandbox queue size when using buildSandboxPerRequest flag.
constructor ( options )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
buildSandboxQueue(maxSandboxQueueSize) { this._sandboxApplicationInstanceQueue = new Queue( () => this.buildNewApplicationInstance(), maxSandboxQueueSize ); for (let i = 0; i < maxSandboxQueueSize; i++) { this._sandboxApplicationInstanceQueue.enqueue(); } }
@private Function to build queue of sandboxes which is later leveraged if application is using `buildSandboxPerRequest` flag. This is an optimization to help with performance. @param {Number} maxSandboxQueueSize - maximum size of queue (this is should be a derivative of your QPS)
buildSandboxQueue ( maxSandboxQueueSize )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
buildSandbox() { const { distPath, buildSandboxGlobals, config, appName, sandboxRequire } = this; function fastbootConfig(key) { if (!key) { // default to app key key = appName; } if (config) { return { default: config[key] }; } else { return { default: undefined }; } } let defaultGlobals = { FastBoot: { require: sandboxRequire, config: fastbootConfig, get distPath() { return distPath; }, }, }; let globals = buildSandboxGlobals(defaultGlobals); return new Sandbox(globals); }
@private Builds and initializes a new sandbox to run the Ember application in.
buildSandbox ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
buildNewApplicationInstance() { return Promise.resolve().then(() => { let app = this.buildApp(); return app; }); }
Builds a new application instance sandbox as a micro-task.
buildNewApplicationInstance ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
buildApp() { let sandbox = this.buildSandbox(); debug('adding files to sandbox'); for (let script of this.scripts) { debug('evaluating file %s', script); sandbox.runScript(script); } debug('files evaluated'); // Retrieve the application factory from within the sandbox let AppFactory = sandbox.run(function(ctx) { return ctx.require('~fastboot/app-factory'); }); // If the application factory couldn't be found, throw an error if (!AppFactory || typeof AppFactory['default'] !== 'function') { throw new Error( 'Failed to load Ember app from app.js, make sure it was built for FastBoot with the `ember fastboot:build` command.' ); } debug('creating application'); // Otherwise, return a new `Ember.Application` instance let app = AppFactory['default'](); return app; }
@private Creates a new `Application` @returns {Ember.Application} instance
buildApp ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
getAppInstanceInfo(appInstance, isAppInstancePreBuilt = true) { return { app: appInstance, isSandboxPreBuilt: isAppInstancePreBuilt }; }
@private @param {Promise<instance>} appInstance - the instance that is pre-warmed or built on demand @param {Boolean} isAppInstancePreBuilt - boolean representing how the instance was built @returns {Object}
getAppInstanceInfo ( appInstance , isAppInstancePreBuilt = true )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
async getNewApplicationInstance() { const queueObject = this._sandboxApplicationInstanceQueue.dequeue(); const app = await queueObject.item; return this.getAppInstanceInfo(app, queueObject.isItemPreBuilt); }
@private Get the new sandbox off if it is being created, otherwise create a new one on demand. The later is needed when the current request hasn't finished or wasn't build with sandbox per request turned on and a new request comes in. @param {Boolean} buildSandboxPerVisit if true, a new sandbox will **always** be created, otherwise one is created for the first request only
getNewApplicationInstance ( )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
async _visit(path, fastbootInfo, bootOptions, result, buildSandboxPerVisit) { let shouldBuildApp = buildSandboxPerVisit || this._applicationInstance === undefined; let { app, isSandboxPreBuilt } = shouldBuildApp ? await this.getNewApplicationInstance() : this.getAppInstanceInfo(this._applicationInstance); if (buildSandboxPerVisit) { // entangle the specific application instance to the result, so it can be // destroyed when result._destroy() is called (after the visit is // completed) result.applicationInstance = app; // we add analytics information about the current request to know // whether it used sandbox from the pre-built queue or built on demand. result.analytics.usedPrebuiltSandbox = isSandboxPreBuilt; } else { // save the created application instance so that we can clean it up when // this instance of `src/ember-app.js` is destroyed (e.g. reload) this._applicationInstance = app; } await app.boot(); let instance = await app.buildInstance(); result.applicationInstanceInstance = instance; registerFastBootInfo(fastbootInfo, instance); await instance.boot(bootOptions); await instance.visit(path, bootOptions); await fastbootInfo.deferredPromise; }
@private Main function that creates the app instance for every `visit` request, boots the app instance and then visits the given route and destroys the app instance when the route is finished its render cycle. Ember apps can manually defer rendering in FastBoot mode if they're waiting on something async the router doesn't know about. This function fetches that promise for deferred rendering from the app. @param {string} path the URL path to render, like `/photos/1` @param {Object} fastbootInfo An object holding per request info @param {Object} bootOptions An object containing the boot options that are used by by ember to decide whether it needs to do rendering or not. @param {Object} result @param {Boolean} buildSandboxPerVisit if true, a new sandbox will **always** be created, otherwise one is created for the first request only @return {Promise<instance>} instance
_visit ( path , fastbootInfo , bootOptions , result , buildSandboxPerVisit )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/ember-app.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/ember-app.js
MIT
function loadConfig(distPath) { let pkgPath = path.join(distPath, 'package.json'); let file; try { file = fs.readFileSync(pkgPath); } catch (e) { throw new Error( `Couldn't find ${pkgPath}. You may need to update your version of ember-cli-fastboot.` ); } let schemaVersion; let pkg; try { pkg = JSON.parse(file); schemaVersion = pkg.fastboot.schemaVersion; } catch (e) { throw new Error( `${pkgPath} was malformed or did not contain a fastboot config. Ensure that you have a compatible version of ember-cli-fastboot.` ); } const currentSchemaVersion = FastBootSchemaVersions.latest; // set schema version to 1 if not defined schemaVersion = schemaVersion || FastBootSchemaVersions.base; debug( 'Current schemaVersion from `ember-cli-fastboot` is %s while latest schema version is %s', schemaVersion, currentSchemaVersion ); if (schemaVersion > currentSchemaVersion) { let errorMsg = chalk.bold.red( 'An incompatible version between `ember-cli-fastboot` and `fastboot` was found. Please update the version of fastboot library that is compatible with ember-cli-fastboot.' ); throw new Error(errorMsg); } let appName, config, html, scripts; if (schemaVersion < FastBootSchemaVersions.htmlEntrypoint) { ({ appName, config, html, scripts } = loadManifest(distPath, pkg.fastboot, schemaVersion)); } else { appName = pkg.name; ({ config, html, scripts } = htmlEntrypoint(appName, distPath, pkg.fastboot.htmlEntrypoint)); } let sandboxRequire = buildWhitelistedRequire( pkg.fastboot.moduleWhitelist, distPath, schemaVersion < FastBootSchemaVersions.strictWhitelist ); return { scripts, html, hostWhitelist: pkg.fastboot.hostWhitelist, config, appName, sandboxRequire, }; }
Given the path to a built Ember app, loads our complete configuration while completely hiding any differences in schema version.
loadConfig ( distPath )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/fastboot-schema.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/fastboot-schema.js
MIT
function transformManifestFiles(manifest) { manifest.appFiles = [manifest.appFile]; manifest.vendorFiles = [manifest.vendorFile]; return manifest; }
Function to transform the manifest app and vendor files to an array.
transformManifestFiles ( manifest )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/fastboot-schema.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/fastboot-schema.js
MIT
function buildWhitelistedRequire(whitelist, distPath, isLegacyWhitelist) { whitelist.forEach(function(whitelistedModule) { debug('module whitelisted; module=%s', whitelistedModule); if (isLegacyWhitelist) { let packageName = getPackageName(whitelistedModule); if (packageName !== whitelistedModule && whitelist.indexOf(packageName) === -1) { console.error("Package '" + packageName + "' is required to be in the whitelist."); } } }); return function(moduleName) { let packageName = getPackageName(moduleName); let isWhitelisted = whitelist.indexOf(packageName) > -1; if (isWhitelisted) { try { let resolvedModulePath = resolve.sync(moduleName, { basedir: distPath }); return require(resolvedModulePath); } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { return require(moduleName); } else { throw error; } } } if (isLegacyWhitelist) { if (whitelist.indexOf(moduleName) > -1) { let nodeModulesPath = path.join(distPath, 'node_modules', moduleName); if (fs.existsSync(nodeModulesPath)) { return require(nodeModulesPath); } else { return require(moduleName); } } else { throw new Error( "Unable to require module '" + moduleName + "' in Fastboot because it was not explicitly allowed in 'fastbootDependencies' in your package.json." ); } } throw new Error( "Unable to require module '" + moduleName + "' in Fastboot because its package '" + packageName + "' was not explicitly allowed in 'fastbootDependencies' in your package.json." ); }; }
The Ember app runs inside a sandbox that doesn't have access to the normal Node.js environment, including the `require` function. Instead, we provide our own `require` method that only allows whitelisted packages to be requested. This method takes an array of whitelisted package names and the path to the built Ember app and constructs this "fake" `require` function that gets made available globally inside the sandbox. @param {string[]} whitelist array of whitelisted package names @param {string} distPath path to the built Ember app @param {boolean} isLegacyWhiteList flag to enable legacy behavior
buildWhitelistedRequire ( whitelist , distPath , isLegacyWhitelist )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/fastboot-schema.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/fastboot-schema.js
MIT
async visit(path, options = {}) { let resilient = 'resilient' in options ? options.resilient : this.resilient; let result = await this._app.visit(path, options); if (!resilient && result.error) { throw result.error; } else { return result; } }
Renders the Ember app at a specific URL, returning a promise that resolves to a {@link Result}, giving you access to the rendered HTML as well as metadata about the request such as the HTTP status code. @param {string} path the URL path to render, like `/photos/1` @param {Object} options @param {Boolean} [options.resilient] whether to reject the returned promise if there is an error during rendering. Overrides the instance's `resilient` setting @param {string} [options.html] the HTML document to insert the rendered app into. Uses the built app's index.html by default. @param {Object} [options.metadata] per request meta data that need to be exposed in the app. @param {Boolean} [options.shouldRender] whether the app should do rendering or not. If set to false, it puts the app in routing-only. @param {Boolean} [options.disableShoebox] whether we should send the API data in the shoebox. If set to false, it will not send the API data used for rendering the app on server side in the index.html. @param {Integer} [options.destroyAppInstanceInMs] whether to destroy the instance in the given number of ms. This is a failure mechanism to not wedge the Node process (See: https://github.com/ember-fastboot/fastboot/issues/90) @param {Boolean} [options.buildSandboxPerVisit=false] whether to create a new sandbox context per-visit (slows down each visit, but guarantees no prototype leakages can occur), or reuse the existing sandbox (faster per-request, but each request shares the same set of prototypes) @returns {Promise<Result>} result
visit ( path , options = { } )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/index.js
MIT
reload({ distPath }) { if (this._app) { this._app.destroy(); } this._buildEmberApp(distPath); }
Destroy the existing Ember application instance, and recreate it from the provided dist path. This is commonly done when `dist` has been updated, and you need to prepare to serve requests with the updated assets. @param {Object} options @param {string} options.distPath the path to the built Ember application
reload ( { distPath } )
javascript
ember-fastboot/ember-cli-fastboot
packages/fastboot/src/index.js
https://github.com/ember-fastboot/ember-cli-fastboot/blob/master/packages/fastboot/src/index.js
MIT