id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
17,400
APIDevTools/swagger-parser
karma.conf.js
configureCodeCoverage
function configureCodeCoverage (config) { if (process.argv.indexOf("--coverage") === -1) { console.warn("Code-coverage is not enabled"); return; } config.reporters.push("coverage"); config.coverageReporter = { reporters: [ { type: "text-summary" }, { type: "lcov" } ] }; config.files = config.files.map(function (file) { if (typeof file === "string") { file = file.replace(/^dist\/(.*)\.min\.js$/, "dist/$1.coverage.js"); } return file; }); }
javascript
function configureCodeCoverage (config) { if (process.argv.indexOf("--coverage") === -1) { console.warn("Code-coverage is not enabled"); return; } config.reporters.push("coverage"); config.coverageReporter = { reporters: [ { type: "text-summary" }, { type: "lcov" } ] }; config.files = config.files.map(function (file) { if (typeof file === "string") { file = file.replace(/^dist\/(.*)\.min\.js$/, "dist/$1.coverage.js"); } return file; }); }
[ "function", "configureCodeCoverage", "(", "config", ")", "{", "if", "(", "process", ".", "argv", ".", "indexOf", "(", "\"--coverage\"", ")", "===", "-", "1", ")", "{", "console", ".", "warn", "(", "\"Code-coverage is not enabled\"", ")", ";", "return", ";", "}", "config", ".", "reporters", ".", "push", "(", "\"coverage\"", ")", ";", "config", ".", "coverageReporter", "=", "{", "reporters", ":", "[", "{", "type", ":", "\"text-summary\"", "}", ",", "{", "type", ":", "\"lcov\"", "}", "]", "}", ";", "config", ".", "files", "=", "config", ".", "files", ".", "map", "(", "function", "(", "file", ")", "{", "if", "(", "typeof", "file", "===", "\"string\"", ")", "{", "file", "=", "file", ".", "replace", "(", "/", "^dist\\/(.*)\\.min\\.js$", "/", ",", "\"dist/$1.coverage.js\"", ")", ";", "}", "return", "file", ";", "}", ")", ";", "}" ]
Configures the code-coverage reporter
[ "Configures", "the", "code", "-", "coverage", "reporter" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/karma.conf.js#L48-L68
17,401
APIDevTools/swagger-parser
online/src/js/form.js
form
function form () { form.form = $("#swagger-parser-form"); form.allow = { label: form.form.find("#allow-label"), menu: form.form.find("#allow-menu"), json: form.form.find("input[name=allow-json]"), yaml: form.form.find("input[name=allow-yaml]"), text: form.form.find("input[name=allow-text]"), empty: form.form.find("input[name=allow-empty]"), unknown: form.form.find("input[name=allow-unknown]") }; form.refs = { label: form.form.find("#refs-label"), menu: form.form.find("#refs-menu"), external: form.form.find("input[name=refs-external]"), circular: form.form.find("input[name=refs-circular]") }; form.validate = { label: form.form.find("#validate-label"), menu: form.form.find("#validate-menu"), schema: form.form.find("input[name=validate-schema]"), spec: form.form.find("input[name=validate-spec]") }; form.tabs = { url: form.form.find("#url-tab"), text: form.form.find("#text-tab") }; form.method = { button: form.form.find("button[name=method]"), menu: form.form.find("#method-menu") }; form.samples = { url: { container: form.form.find("#url-sample"), link: form.form.find("#url-sample-link"), }, text: { container: form.form.find("#text-sample"), link: form.form.find("#text-sample-link"), } }; form.url = form.form.find("input[name=url]"); form.textBox = null; // This is set in editors.js form.bookmark = form.form.find("#bookmark"); }
javascript
function form () { form.form = $("#swagger-parser-form"); form.allow = { label: form.form.find("#allow-label"), menu: form.form.find("#allow-menu"), json: form.form.find("input[name=allow-json]"), yaml: form.form.find("input[name=allow-yaml]"), text: form.form.find("input[name=allow-text]"), empty: form.form.find("input[name=allow-empty]"), unknown: form.form.find("input[name=allow-unknown]") }; form.refs = { label: form.form.find("#refs-label"), menu: form.form.find("#refs-menu"), external: form.form.find("input[name=refs-external]"), circular: form.form.find("input[name=refs-circular]") }; form.validate = { label: form.form.find("#validate-label"), menu: form.form.find("#validate-menu"), schema: form.form.find("input[name=validate-schema]"), spec: form.form.find("input[name=validate-spec]") }; form.tabs = { url: form.form.find("#url-tab"), text: form.form.find("#text-tab") }; form.method = { button: form.form.find("button[name=method]"), menu: form.form.find("#method-menu") }; form.samples = { url: { container: form.form.find("#url-sample"), link: form.form.find("#url-sample-link"), }, text: { container: form.form.find("#text-sample"), link: form.form.find("#text-sample-link"), } }; form.url = form.form.find("input[name=url]"); form.textBox = null; // This is set in editors.js form.bookmark = form.form.find("#bookmark"); }
[ "function", "form", "(", ")", "{", "form", ".", "form", "=", "$", "(", "\"#swagger-parser-form\"", ")", ";", "form", ".", "allow", "=", "{", "label", ":", "form", ".", "form", ".", "find", "(", "\"#allow-label\"", ")", ",", "menu", ":", "form", ".", "form", ".", "find", "(", "\"#allow-menu\"", ")", ",", "json", ":", "form", ".", "form", ".", "find", "(", "\"input[name=allow-json]\"", ")", ",", "yaml", ":", "form", ".", "form", ".", "find", "(", "\"input[name=allow-yaml]\"", ")", ",", "text", ":", "form", ".", "form", ".", "find", "(", "\"input[name=allow-text]\"", ")", ",", "empty", ":", "form", ".", "form", ".", "find", "(", "\"input[name=allow-empty]\"", ")", ",", "unknown", ":", "form", ".", "form", ".", "find", "(", "\"input[name=allow-unknown]\"", ")", "}", ";", "form", ".", "refs", "=", "{", "label", ":", "form", ".", "form", ".", "find", "(", "\"#refs-label\"", ")", ",", "menu", ":", "form", ".", "form", ".", "find", "(", "\"#refs-menu\"", ")", ",", "external", ":", "form", ".", "form", ".", "find", "(", "\"input[name=refs-external]\"", ")", ",", "circular", ":", "form", ".", "form", ".", "find", "(", "\"input[name=refs-circular]\"", ")", "}", ";", "form", ".", "validate", "=", "{", "label", ":", "form", ".", "form", ".", "find", "(", "\"#validate-label\"", ")", ",", "menu", ":", "form", ".", "form", ".", "find", "(", "\"#validate-menu\"", ")", ",", "schema", ":", "form", ".", "form", ".", "find", "(", "\"input[name=validate-schema]\"", ")", ",", "spec", ":", "form", ".", "form", ".", "find", "(", "\"input[name=validate-spec]\"", ")", "}", ";", "form", ".", "tabs", "=", "{", "url", ":", "form", ".", "form", ".", "find", "(", "\"#url-tab\"", ")", ",", "text", ":", "form", ".", "form", ".", "find", "(", "\"#text-tab\"", ")", "}", ";", "form", ".", "method", "=", "{", "button", ":", "form", ".", "form", ".", "find", "(", "\"button[name=method]\"", ")", ",", "menu", ":", "form", ".", "form", ".", "find", "(", "\"#method-menu\"", ")", "}", ";", "form", ".", "samples", "=", "{", "url", ":", "{", "container", ":", "form", ".", "form", ".", "find", "(", "\"#url-sample\"", ")", ",", "link", ":", "form", ".", "form", ".", "find", "(", "\"#url-sample-link\"", ")", ",", "}", ",", "text", ":", "{", "container", ":", "form", ".", "form", ".", "find", "(", "\"#text-sample\"", ")", ",", "link", ":", "form", ".", "form", ".", "find", "(", "\"#text-sample-link\"", ")", ",", "}", "}", ";", "form", ".", "url", "=", "form", ".", "form", ".", "find", "(", "\"input[name=url]\"", ")", ";", "form", ".", "textBox", "=", "null", ";", "// This is set in editors.js", "form", ".", "bookmark", "=", "form", ".", "form", ".", "find", "(", "\"#bookmark\"", ")", ";", "}" ]
Finds all form fields and exposes them as properties.
[ "Finds", "all", "form", "fields", "and", "exposes", "them", "as", "properties", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/form.js#L8-L59
17,402
APIDevTools/swagger-parser
online/src/js/samples.js
samples
function samples () { form.samples.url.link.on("click", function (event) { event.preventDefault(); form.url.val(samples.url); }); form.samples.text.link.on("click", function (event) { event.preventDefault(); form.textBox.setValue(samples.text, -1); form.samples.text.container.hide(); form.textBox.focus(); }); form.textBox.on("input", function () { if (form.textBox.session.getValue().length === 0) { form.samples.text.container.show(); } else { form.samples.text.container.hide(); } }); }
javascript
function samples () { form.samples.url.link.on("click", function (event) { event.preventDefault(); form.url.val(samples.url); }); form.samples.text.link.on("click", function (event) { event.preventDefault(); form.textBox.setValue(samples.text, -1); form.samples.text.container.hide(); form.textBox.focus(); }); form.textBox.on("input", function () { if (form.textBox.session.getValue().length === 0) { form.samples.text.container.show(); } else { form.samples.text.container.hide(); } }); }
[ "function", "samples", "(", ")", "{", "form", ".", "samples", ".", "url", ".", "link", ".", "on", "(", "\"click\"", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "form", ".", "url", ".", "val", "(", "samples", ".", "url", ")", ";", "}", ")", ";", "form", ".", "samples", ".", "text", ".", "link", ".", "on", "(", "\"click\"", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "form", ".", "textBox", ".", "setValue", "(", "samples", ".", "text", ",", "-", "1", ")", ";", "form", ".", "samples", ".", "text", ".", "container", ".", "hide", "(", ")", ";", "form", ".", "textBox", ".", "focus", "(", ")", ";", "}", ")", ";", "form", ".", "textBox", ".", "on", "(", "\"input\"", ",", "function", "(", ")", "{", "if", "(", "form", ".", "textBox", ".", "session", ".", "getValue", "(", ")", ".", "length", "===", "0", ")", "{", "form", ".", "samples", ".", "text", ".", "container", ".", "show", "(", ")", ";", "}", "else", "{", "form", ".", "samples", ".", "text", ".", "container", ".", "hide", "(", ")", ";", "}", "}", ")", ";", "}" ]
Allows the user to use a sample URL or sample API text
[ "Allows", "the", "user", "to", "use", "a", "sample", "URL", "or", "sample", "API", "text" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/samples.js#L10-L31
17,403
APIDevTools/swagger-parser
online/src/js/dropdowns.js
dropdowns
function dropdowns () { // Set the initial method name (in case it was set by the querystring module) setSelectedMethod(form.method.button.val()); // Update each dropdown's label when its value(s) change onChange(form.allow.menu, setAllowLabel); onChange(form.refs.menu, setRefsLabel); onChange(form.validate.menu, setValidateLabel); // Track option changes trackCheckbox(form.allow.json); trackCheckbox(form.allow.yaml); trackCheckbox(form.allow.text); trackCheckbox(form.allow.empty); trackCheckbox(form.allow.unknown); trackCheckbox(form.refs.external); trackCheckbox(form.refs.circular); trackCheckbox(form.validate.schema); trackCheckbox(form.validate.spec); // Change the button text whenever a new method is selected form.method.menu.find("a").on("click", function (event) { form.method.menu.dropdown("toggle"); event.stopPropagation(); var methodName = $(this).data("value"); setSelectedMethod(methodName); trackButtonLabel(methodName); }); }
javascript
function dropdowns () { // Set the initial method name (in case it was set by the querystring module) setSelectedMethod(form.method.button.val()); // Update each dropdown's label when its value(s) change onChange(form.allow.menu, setAllowLabel); onChange(form.refs.menu, setRefsLabel); onChange(form.validate.menu, setValidateLabel); // Track option changes trackCheckbox(form.allow.json); trackCheckbox(form.allow.yaml); trackCheckbox(form.allow.text); trackCheckbox(form.allow.empty); trackCheckbox(form.allow.unknown); trackCheckbox(form.refs.external); trackCheckbox(form.refs.circular); trackCheckbox(form.validate.schema); trackCheckbox(form.validate.spec); // Change the button text whenever a new method is selected form.method.menu.find("a").on("click", function (event) { form.method.menu.dropdown("toggle"); event.stopPropagation(); var methodName = $(this).data("value"); setSelectedMethod(methodName); trackButtonLabel(methodName); }); }
[ "function", "dropdowns", "(", ")", "{", "// Set the initial method name (in case it was set by the querystring module)", "setSelectedMethod", "(", "form", ".", "method", ".", "button", ".", "val", "(", ")", ")", ";", "// Update each dropdown's label when its value(s) change", "onChange", "(", "form", ".", "allow", ".", "menu", ",", "setAllowLabel", ")", ";", "onChange", "(", "form", ".", "refs", ".", "menu", ",", "setRefsLabel", ")", ";", "onChange", "(", "form", ".", "validate", ".", "menu", ",", "setValidateLabel", ")", ";", "// Track option changes", "trackCheckbox", "(", "form", ".", "allow", ".", "json", ")", ";", "trackCheckbox", "(", "form", ".", "allow", ".", "yaml", ")", ";", "trackCheckbox", "(", "form", ".", "allow", ".", "text", ")", ";", "trackCheckbox", "(", "form", ".", "allow", ".", "empty", ")", ";", "trackCheckbox", "(", "form", ".", "allow", ".", "unknown", ")", ";", "trackCheckbox", "(", "form", ".", "refs", ".", "external", ")", ";", "trackCheckbox", "(", "form", ".", "refs", ".", "circular", ")", ";", "trackCheckbox", "(", "form", ".", "validate", ".", "schema", ")", ";", "trackCheckbox", "(", "form", ".", "validate", ".", "spec", ")", ";", "// Change the button text whenever a new method is selected", "form", ".", "method", ".", "menu", ".", "find", "(", "\"a\"", ")", ".", "on", "(", "\"click\"", ",", "function", "(", "event", ")", "{", "form", ".", "method", ".", "menu", ".", "dropdown", "(", "\"toggle\"", ")", ";", "event", ".", "stopPropagation", "(", ")", ";", "var", "methodName", "=", "$", "(", "this", ")", ".", "data", "(", "\"value\"", ")", ";", "setSelectedMethod", "(", "methodName", ")", ";", "trackButtonLabel", "(", "methodName", ")", ";", "}", ")", ";", "}" ]
Adds all the drop-down menu functionality
[ "Adds", "all", "the", "drop", "-", "down", "menu", "functionality" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L11-L39
17,404
APIDevTools/swagger-parser
online/src/js/dropdowns.js
setAllowLabel
function setAllowLabel () { var values = getCheckedAndUnchecked( form.allow.json, form.allow.yaml, form.allow.text, form.allow.empty, form.allow.unknown); switch (values.checked.length) { case 0: form.allow.label.text("No file types allowed"); break; case 1: form.allow.label.text("Only allow " + values.checked[0] + " files"); break; case 2: form.allow.label.text("Only allow " + values.checked[0] + " and " + values.checked[1]); break; case 3: form.allow.label.text("Don't allow " + values.unchecked[0] + " or " + values.unchecked[1]); break; case 4: form.allow.label.text("Don't allow " + values.unchecked[0] + " files"); break; case 5: form.allow.label.text("Allow all file types"); } }
javascript
function setAllowLabel () { var values = getCheckedAndUnchecked( form.allow.json, form.allow.yaml, form.allow.text, form.allow.empty, form.allow.unknown); switch (values.checked.length) { case 0: form.allow.label.text("No file types allowed"); break; case 1: form.allow.label.text("Only allow " + values.checked[0] + " files"); break; case 2: form.allow.label.text("Only allow " + values.checked[0] + " and " + values.checked[1]); break; case 3: form.allow.label.text("Don't allow " + values.unchecked[0] + " or " + values.unchecked[1]); break; case 4: form.allow.label.text("Don't allow " + values.unchecked[0] + " files"); break; case 5: form.allow.label.text("Allow all file types"); } }
[ "function", "setAllowLabel", "(", ")", "{", "var", "values", "=", "getCheckedAndUnchecked", "(", "form", ".", "allow", ".", "json", ",", "form", ".", "allow", ".", "yaml", ",", "form", ".", "allow", ".", "text", ",", "form", ".", "allow", ".", "empty", ",", "form", ".", "allow", ".", "unknown", ")", ";", "switch", "(", "values", ".", "checked", ".", "length", ")", "{", "case", "0", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"No file types allowed\"", ")", ";", "break", ";", "case", "1", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"Only allow \"", "+", "values", ".", "checked", "[", "0", "]", "+", "\" files\"", ")", ";", "break", ";", "case", "2", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"Only allow \"", "+", "values", ".", "checked", "[", "0", "]", "+", "\" and \"", "+", "values", ".", "checked", "[", "1", "]", ")", ";", "break", ";", "case", "3", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"Don't allow \"", "+", "values", ".", "unchecked", "[", "0", "]", "+", "\" or \"", "+", "values", ".", "unchecked", "[", "1", "]", ")", ";", "break", ";", "case", "4", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"Don't allow \"", "+", "values", ".", "unchecked", "[", "0", "]", "+", "\" files\"", ")", ";", "break", ";", "case", "5", ":", "form", ".", "allow", ".", "label", ".", "text", "(", "\"Allow all file types\"", ")", ";", "}", "}" ]
Sets the "allow" label, based on which options are selected
[ "Sets", "the", "allow", "label", "based", "on", "which", "options", "are", "selected" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L69-L92
17,405
APIDevTools/swagger-parser
online/src/js/dropdowns.js
setRefsLabel
function setRefsLabel () { var values = getCheckedAndUnchecked(form.refs.external, form.refs.circular); switch (values.checked.length) { case 0: form.refs.label.text("Only follow internal $refs"); break; case 1: form.refs.label.text("Don't follow " + values.unchecked[0] + " $refs"); break; case 2: form.refs.label.text("Follow all $refs"); } }
javascript
function setRefsLabel () { var values = getCheckedAndUnchecked(form.refs.external, form.refs.circular); switch (values.checked.length) { case 0: form.refs.label.text("Only follow internal $refs"); break; case 1: form.refs.label.text("Don't follow " + values.unchecked[0] + " $refs"); break; case 2: form.refs.label.text("Follow all $refs"); } }
[ "function", "setRefsLabel", "(", ")", "{", "var", "values", "=", "getCheckedAndUnchecked", "(", "form", ".", "refs", ".", "external", ",", "form", ".", "refs", ".", "circular", ")", ";", "switch", "(", "values", ".", "checked", ".", "length", ")", "{", "case", "0", ":", "form", ".", "refs", ".", "label", ".", "text", "(", "\"Only follow internal $refs\"", ")", ";", "break", ";", "case", "1", ":", "form", ".", "refs", ".", "label", ".", "text", "(", "\"Don't follow \"", "+", "values", ".", "unchecked", "[", "0", "]", "+", "\" $refs\"", ")", ";", "break", ";", "case", "2", ":", "form", ".", "refs", ".", "label", ".", "text", "(", "\"Follow all $refs\"", ")", ";", "}", "}" ]
Sets the "refs" label, based on which options are selected
[ "Sets", "the", "refs", "label", "based", "on", "which", "options", "are", "selected" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L97-L110
17,406
APIDevTools/swagger-parser
online/src/js/dropdowns.js
setValidateLabel
function setValidateLabel () { var values = getCheckedAndUnchecked(form.validate.schema, form.validate.spec); switch (values.checked.length) { case 0: form.validate.label.text("Don't validate anything"); break; case 1: form.validate.label.text("Don't validate Swagger " + values.unchecked[0]); break; case 2: form.validate.label.text("Validate everything"); } }
javascript
function setValidateLabel () { var values = getCheckedAndUnchecked(form.validate.schema, form.validate.spec); switch (values.checked.length) { case 0: form.validate.label.text("Don't validate anything"); break; case 1: form.validate.label.text("Don't validate Swagger " + values.unchecked[0]); break; case 2: form.validate.label.text("Validate everything"); } }
[ "function", "setValidateLabel", "(", ")", "{", "var", "values", "=", "getCheckedAndUnchecked", "(", "form", ".", "validate", ".", "schema", ",", "form", ".", "validate", ".", "spec", ")", ";", "switch", "(", "values", ".", "checked", ".", "length", ")", "{", "case", "0", ":", "form", ".", "validate", ".", "label", ".", "text", "(", "\"Don't validate anything\"", ")", ";", "break", ";", "case", "1", ":", "form", ".", "validate", ".", "label", ".", "text", "(", "\"Don't validate Swagger \"", "+", "values", ".", "unchecked", "[", "0", "]", ")", ";", "break", ";", "case", "2", ":", "form", ".", "validate", ".", "label", ".", "text", "(", "\"Validate everything\"", ")", ";", "}", "}" ]
Sets the "validate" label, based on which options are selected
[ "Sets", "the", "validate", "label", "based", "on", "which", "options", "are", "selected" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L115-L128
17,407
APIDevTools/swagger-parser
online/src/js/dropdowns.js
setSelectedMethod
function setSelectedMethod (methodName) { form.method.button.val(methodName.toLowerCase()); methodName = methodName[0].toUpperCase() + methodName.substr(1); form.method.button.text(methodName + " it!"); form.tabs.url.text(methodName + " a URL"); form.tabs.text.text(methodName + " Text"); }
javascript
function setSelectedMethod (methodName) { form.method.button.val(methodName.toLowerCase()); methodName = methodName[0].toUpperCase() + methodName.substr(1); form.method.button.text(methodName + " it!"); form.tabs.url.text(methodName + " a URL"); form.tabs.text.text(methodName + " Text"); }
[ "function", "setSelectedMethod", "(", "methodName", ")", "{", "form", ".", "method", ".", "button", ".", "val", "(", "methodName", ".", "toLowerCase", "(", ")", ")", ";", "methodName", "=", "methodName", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "methodName", ".", "substr", "(", "1", ")", ";", "form", ".", "method", ".", "button", ".", "text", "(", "methodName", "+", "\" it!\"", ")", ";", "form", ".", "tabs", ".", "url", ".", "text", "(", "methodName", "+", "\" a URL\"", ")", ";", "form", ".", "tabs", ".", "text", ".", "text", "(", "methodName", "+", "\" Text\"", ")", ";", "}" ]
Updates the UI to match the specified method name @param {string} methodName - The method name (e.g. "validate", "dereference", etc.)
[ "Updates", "the", "UI", "to", "match", "the", "specified", "method", "name" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L135-L142
17,408
APIDevTools/swagger-parser
online/src/js/dropdowns.js
trackCheckbox
function trackCheckbox (checkbox) { checkbox.on("change", function () { var value = checkbox.is(":checked") ? 1 : 0; analytics.trackEvent("options", "changed", checkbox.attr("name"), value); }); }
javascript
function trackCheckbox (checkbox) { checkbox.on("change", function () { var value = checkbox.is(":checked") ? 1 : 0; analytics.trackEvent("options", "changed", checkbox.attr("name"), value); }); }
[ "function", "trackCheckbox", "(", "checkbox", ")", "{", "checkbox", ".", "on", "(", "\"change\"", ",", "function", "(", ")", "{", "var", "value", "=", "checkbox", ".", "is", "(", "\":checked\"", ")", "?", "1", ":", "0", ";", "analytics", ".", "trackEvent", "(", "\"options\"", ",", "\"changed\"", ",", "checkbox", ".", "attr", "(", "\"name\"", ")", ",", "value", ")", ";", "}", ")", ";", "}" ]
Tracks changes to a checkbox option @param {jQuery} checkbox
[ "Tracks", "changes", "to", "a", "checkbox", "option" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L149-L154
17,409
APIDevTools/swagger-parser
online/src/js/dropdowns.js
getCheckedAndUnchecked
function getCheckedAndUnchecked (checkboxes) { var checked = [], unchecked = []; for (var i = 0; i < arguments.length; i++) { var checkbox = arguments[i]; if (checkbox.is(":checked")) { checked.push(checkbox.data("value")); } else { unchecked.push(checkbox.data("value")); } } return { checked: checked, unchecked: unchecked }; }
javascript
function getCheckedAndUnchecked (checkboxes) { var checked = [], unchecked = []; for (var i = 0; i < arguments.length; i++) { var checkbox = arguments[i]; if (checkbox.is(":checked")) { checked.push(checkbox.data("value")); } else { unchecked.push(checkbox.data("value")); } } return { checked: checked, unchecked: unchecked }; }
[ "function", "getCheckedAndUnchecked", "(", "checkboxes", ")", "{", "var", "checked", "=", "[", "]", ",", "unchecked", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "checkbox", "=", "arguments", "[", "i", "]", ";", "if", "(", "checkbox", ".", "is", "(", "\":checked\"", ")", ")", "{", "checked", ".", "push", "(", "checkbox", ".", "data", "(", "\"value\"", ")", ")", ";", "}", "else", "{", "unchecked", ".", "push", "(", "checkbox", ".", "data", "(", "\"value\"", ")", ")", ";", "}", "}", "return", "{", "checked", ":", "checked", ",", "unchecked", ":", "unchecked", "}", ";", "}" ]
Examines the given checkboxes, and returns arrays of checked and unchecked values. @param {...jQuery} checkboxes @returns {{checked: string[], unchecked: string[]}}
[ "Examines", "the", "given", "checkboxes", "and", "returns", "arrays", "of", "checked", "and", "unchecked", "values", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/dropdowns.js#L172-L184
17,410
APIDevTools/swagger-parser
online/src/js/querystring.js
setFormFields
function setFormFields () { var query = qs.parse(window.location.search.substr(1)); setCheckbox(form.allow.json, query["allow-json"]); setCheckbox(form.allow.yaml, query["allow-yaml"]); setCheckbox(form.allow.text, query["allow-text"]); setCheckbox(form.allow.empty, query["allow-empty"]); setCheckbox(form.allow.unknown, query["allow-unknown"]); setCheckbox(form.refs.external, query["refs-external"]); setCheckbox(form.refs.circular, query["refs-circular"]); setCheckbox(form.validate.schema, query["validate-schema"]); setCheckbox(form.validate.spec, query["validate-spec"]); // If a custom URL is specified, then show the "Your API" tab if (query.url) { form.url.val(query.url); } // If a method is specified, then change the "Validate!" button if (query.method) { query.method = query.method.toLowerCase(); if (["parse", "resolve", "bundle", "dereference", "validate"].indexOf(query.method) !== -1) { form.method.button.val(query.method); } } }
javascript
function setFormFields () { var query = qs.parse(window.location.search.substr(1)); setCheckbox(form.allow.json, query["allow-json"]); setCheckbox(form.allow.yaml, query["allow-yaml"]); setCheckbox(form.allow.text, query["allow-text"]); setCheckbox(form.allow.empty, query["allow-empty"]); setCheckbox(form.allow.unknown, query["allow-unknown"]); setCheckbox(form.refs.external, query["refs-external"]); setCheckbox(form.refs.circular, query["refs-circular"]); setCheckbox(form.validate.schema, query["validate-schema"]); setCheckbox(form.validate.spec, query["validate-spec"]); // If a custom URL is specified, then show the "Your API" tab if (query.url) { form.url.val(query.url); } // If a method is specified, then change the "Validate!" button if (query.method) { query.method = query.method.toLowerCase(); if (["parse", "resolve", "bundle", "dereference", "validate"].indexOf(query.method) !== -1) { form.method.button.val(query.method); } } }
[ "function", "setFormFields", "(", ")", "{", "var", "query", "=", "qs", ".", "parse", "(", "window", ".", "location", ".", "search", ".", "substr", "(", "1", ")", ")", ";", "setCheckbox", "(", "form", ".", "allow", ".", "json", ",", "query", "[", "\"allow-json\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "allow", ".", "yaml", ",", "query", "[", "\"allow-yaml\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "allow", ".", "text", ",", "query", "[", "\"allow-text\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "allow", ".", "empty", ",", "query", "[", "\"allow-empty\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "allow", ".", "unknown", ",", "query", "[", "\"allow-unknown\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "refs", ".", "external", ",", "query", "[", "\"refs-external\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "refs", ".", "circular", ",", "query", "[", "\"refs-circular\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "validate", ".", "schema", ",", "query", "[", "\"validate-schema\"", "]", ")", ";", "setCheckbox", "(", "form", ".", "validate", ".", "spec", ",", "query", "[", "\"validate-spec\"", "]", ")", ";", "// If a custom URL is specified, then show the \"Your API\" tab", "if", "(", "query", ".", "url", ")", "{", "form", ".", "url", ".", "val", "(", "query", ".", "url", ")", ";", "}", "// If a method is specified, then change the \"Validate!\" button", "if", "(", "query", ".", "method", ")", "{", "query", ".", "method", "=", "query", ".", "method", ".", "toLowerCase", "(", ")", ";", "if", "(", "[", "\"parse\"", ",", "\"resolve\"", ",", "\"bundle\"", ",", "\"dereference\"", ",", "\"validate\"", "]", ".", "indexOf", "(", "query", ".", "method", ")", "!==", "-", "1", ")", "{", "form", ".", "method", ".", "button", ".", "val", "(", "query", ".", "method", ")", ";", "}", "}", "}" ]
Populates all form fields based on the query-string in the URL
[ "Populates", "all", "form", "fields", "based", "on", "the", "query", "-", "string", "in", "the", "URL" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/querystring.js#L20-L45
17,411
APIDevTools/swagger-parser
online/src/js/querystring.js
setCheckbox
function setCheckbox (input, value) { if (!value || value === "true" || value === "on") { value = "yes"; } input.val([value]); }
javascript
function setCheckbox (input, value) { if (!value || value === "true" || value === "on") { value = "yes"; } input.val([value]); }
[ "function", "setCheckbox", "(", "input", ",", "value", ")", "{", "if", "(", "!", "value", "||", "value", "===", "\"true\"", "||", "value", "===", "\"on\"", ")", "{", "value", "=", "\"yes\"", ";", "}", "input", ".", "val", "(", "[", "value", "]", ")", ";", "}" ]
Checks or unchecks the given checkbox, based on the given value. @param {jQuery} input @param {*} value
[ "Checks", "or", "unchecks", "the", "given", "checkbox", "based", "on", "the", "given", "value", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/querystring.js#L53-L58
17,412
APIDevTools/swagger-parser
online/src/js/querystring.js
setBookmarkURL
function setBookmarkURL () { var query = {}; var options = form.getOptions(); options.parse.json || (query["allow-json"] = "no"); options.parse.yaml || (query["allow-yaml"] = "no"); options.parse.text || (query["allow-text"] = "no"); options.parse.json.allowEmpty || (query["allow-empty"] = "no"); options.parse.binary || (query["allow-unknown"] = "no"); options.resolve.external || (query["refs-external"] = "no"); options.dereference.circular || (query["refs-circular"] = "no"); options.validate.schema || (query["validate-schema"] = "no"); options.validate.spec || (query["validate-spec"] = "no"); var method = form.method.button.val(); method === "validate" || (query.method = method); var url = form.url.val(); url === "" || (query.url = url); var bookmark = "?" + qs.stringify(query); form.bookmark.attr("href", bookmark); }
javascript
function setBookmarkURL () { var query = {}; var options = form.getOptions(); options.parse.json || (query["allow-json"] = "no"); options.parse.yaml || (query["allow-yaml"] = "no"); options.parse.text || (query["allow-text"] = "no"); options.parse.json.allowEmpty || (query["allow-empty"] = "no"); options.parse.binary || (query["allow-unknown"] = "no"); options.resolve.external || (query["refs-external"] = "no"); options.dereference.circular || (query["refs-circular"] = "no"); options.validate.schema || (query["validate-schema"] = "no"); options.validate.spec || (query["validate-spec"] = "no"); var method = form.method.button.val(); method === "validate" || (query.method = method); var url = form.url.val(); url === "" || (query.url = url); var bookmark = "?" + qs.stringify(query); form.bookmark.attr("href", bookmark); }
[ "function", "setBookmarkURL", "(", ")", "{", "var", "query", "=", "{", "}", ";", "var", "options", "=", "form", ".", "getOptions", "(", ")", ";", "options", ".", "parse", ".", "json", "||", "(", "query", "[", "\"allow-json\"", "]", "=", "\"no\"", ")", ";", "options", ".", "parse", ".", "yaml", "||", "(", "query", "[", "\"allow-yaml\"", "]", "=", "\"no\"", ")", ";", "options", ".", "parse", ".", "text", "||", "(", "query", "[", "\"allow-text\"", "]", "=", "\"no\"", ")", ";", "options", ".", "parse", ".", "json", ".", "allowEmpty", "||", "(", "query", "[", "\"allow-empty\"", "]", "=", "\"no\"", ")", ";", "options", ".", "parse", ".", "binary", "||", "(", "query", "[", "\"allow-unknown\"", "]", "=", "\"no\"", ")", ";", "options", ".", "resolve", ".", "external", "||", "(", "query", "[", "\"refs-external\"", "]", "=", "\"no\"", ")", ";", "options", ".", "dereference", ".", "circular", "||", "(", "query", "[", "\"refs-circular\"", "]", "=", "\"no\"", ")", ";", "options", ".", "validate", ".", "schema", "||", "(", "query", "[", "\"validate-schema\"", "]", "=", "\"no\"", ")", ";", "options", ".", "validate", ".", "spec", "||", "(", "query", "[", "\"validate-spec\"", "]", "=", "\"no\"", ")", ";", "var", "method", "=", "form", ".", "method", ".", "button", ".", "val", "(", ")", ";", "method", "===", "\"validate\"", "||", "(", "query", ".", "method", "=", "method", ")", ";", "var", "url", "=", "form", ".", "url", ".", "val", "(", ")", ";", "url", "===", "\"\"", "||", "(", "query", ".", "url", "=", "url", ")", ";", "var", "bookmark", "=", "\"?\"", "+", "qs", ".", "stringify", "(", "query", ")", ";", "form", ".", "bookmark", ".", "attr", "(", "\"href\"", ",", "bookmark", ")", ";", "}" ]
Sets the href of the bookmark link, based on the values of each form field
[ "Sets", "the", "href", "of", "the", "bookmark", "link", "based", "on", "the", "values", "of", "each", "form", "field" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/querystring.js#L63-L84
17,413
APIDevTools/swagger-parser
online/src/js/editors.js
editors
function editors () { editors.textBox = form.textBox = ace.edit("text-box"); form.textBox.setTheme(ACE_THEME); var session = form.textBox.getSession(); session.setMode("ace/mode/yaml"); session.setTabSize(2); editors.results = $("#results"); editors.tabs = editors.results.find(".nav-tabs"); editors.panes = editors.results.find(".tab-content"); }
javascript
function editors () { editors.textBox = form.textBox = ace.edit("text-box"); form.textBox.setTheme(ACE_THEME); var session = form.textBox.getSession(); session.setMode("ace/mode/yaml"); session.setTabSize(2); editors.results = $("#results"); editors.tabs = editors.results.find(".nav-tabs"); editors.panes = editors.results.find(".tab-content"); }
[ "function", "editors", "(", ")", "{", "editors", ".", "textBox", "=", "form", ".", "textBox", "=", "ace", ".", "edit", "(", "\"text-box\"", ")", ";", "form", ".", "textBox", ".", "setTheme", "(", "ACE_THEME", ")", ";", "var", "session", "=", "form", ".", "textBox", ".", "getSession", "(", ")", ";", "session", ".", "setMode", "(", "\"ace/mode/yaml\"", ")", ";", "session", ".", "setTabSize", "(", "2", ")", ";", "editors", ".", "results", "=", "$", "(", "\"#results\"", ")", ";", "editors", ".", "tabs", "=", "editors", ".", "results", ".", "find", "(", "\".nav-tabs\"", ")", ";", "editors", ".", "panes", "=", "editors", ".", "results", ".", "find", "(", "\".tab-content\"", ")", ";", "}" ]
Initializes the ACE text editors
[ "Initializes", "the", "ACE", "text", "editors" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/editors.js#L12-L22
17,414
APIDevTools/swagger-parser
online/src/js/editors.js
getShortTitle
function getShortTitle (title) { // Get just the file name var lastSlash = title.lastIndexOf("/"); if (lastSlash !== -1) { title = title.substr(lastSlash + 1); } if (title.length > 15) { // It's still too long, so, just return the first 10 characters title = title.substr(0, 10) + "..."; } return title; }
javascript
function getShortTitle (title) { // Get just the file name var lastSlash = title.lastIndexOf("/"); if (lastSlash !== -1) { title = title.substr(lastSlash + 1); } if (title.length > 15) { // It's still too long, so, just return the first 10 characters title = title.substr(0, 10) + "..."; } return title; }
[ "function", "getShortTitle", "(", "title", ")", "{", "// Get just the file name", "var", "lastSlash", "=", "title", ".", "lastIndexOf", "(", "\"/\"", ")", ";", "if", "(", "lastSlash", "!==", "-", "1", ")", "{", "title", "=", "title", ".", "substr", "(", "lastSlash", "+", "1", ")", ";", "}", "if", "(", "title", ".", "length", ">", "15", ")", "{", "// It's still too long, so, just return the first 10 characters", "title", "=", "title", ".", "substr", "(", "0", ",", "10", ")", "+", "\"...\"", ";", "}", "return", "title", ";", "}" ]
Returns a short version of the given title text, to better fit in a tab @param {string} title @returns {string}
[ "Returns", "a", "short", "version", "of", "the", "given", "title", "text", "to", "better", "fit", "in", "a", "tab" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/editors.js#L102-L115
17,415
APIDevTools/swagger-parser
online/src/js/editors.js
showResults
function showResults () { var results = editors.results; setTimeout(function () { results[0].scrollIntoView(); results.addClass("animated") .one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () { // Remove the "animated" class when the animation ends, // so we can replay the animation again next time results.removeClass("animated"); }); }); }
javascript
function showResults () { var results = editors.results; setTimeout(function () { results[0].scrollIntoView(); results.addClass("animated") .one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () { // Remove the "animated" class when the animation ends, // so we can replay the animation again next time results.removeClass("animated"); }); }); }
[ "function", "showResults", "(", ")", "{", "var", "results", "=", "editors", ".", "results", ";", "setTimeout", "(", "function", "(", ")", "{", "results", "[", "0", "]", ".", "scrollIntoView", "(", ")", ";", "results", ".", "addClass", "(", "\"animated\"", ")", ".", "one", "(", "\"webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend\"", ",", "function", "(", ")", "{", "// Remove the \"animated\" class when the animation ends,", "// so we can replay the animation again next time", "results", ".", "removeClass", "(", "\"animated\"", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Ensures that the results are visible, and plays an animation to get the user's attention.
[ "Ensures", "that", "the", "results", "are", "visible", "and", "plays", "an", "animation", "to", "get", "the", "user", "s", "attention", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/editors.js#L120-L132
17,416
APIDevTools/swagger-parser
online/src/js/editors.js
toText
function toText (obj) { if (obj instanceof Error) { return { isJSON: false, text: obj.message + "\n\n" + obj.stack }; } else { try { return { isJSON: true, text: JSON.stringify(obj, null, 2) }; } catch (e) { return { isJSON: false, text: "This API is valid, but it cannot be shown because it contains circular references\n\n" + e.stack }; } } }
javascript
function toText (obj) { if (obj instanceof Error) { return { isJSON: false, text: obj.message + "\n\n" + obj.stack }; } else { try { return { isJSON: true, text: JSON.stringify(obj, null, 2) }; } catch (e) { return { isJSON: false, text: "This API is valid, but it cannot be shown because it contains circular references\n\n" + e.stack }; } } }
[ "function", "toText", "(", "obj", ")", "{", "if", "(", "obj", "instanceof", "Error", ")", "{", "return", "{", "isJSON", ":", "false", ",", "text", ":", "obj", ".", "message", "+", "\"\\n\\n\"", "+", "obj", ".", "stack", "}", ";", "}", "else", "{", "try", "{", "return", "{", "isJSON", ":", "true", ",", "text", ":", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", "}", ";", "}", "catch", "(", "e", ")", "{", "return", "{", "isJSON", ":", "false", ",", "text", ":", "\"This API is valid, but it cannot be shown because it contains circular references\\n\\n\"", "+", "e", ".", "stack", "}", ";", "}", "}", "}" ]
Converts the given object to text. If possible, it is converted to JSON; otherwise, plain text. @param {object} obj @returns {object}
[ "Converts", "the", "given", "object", "to", "text", ".", "If", "possible", "it", "is", "converted", "to", "JSON", ";", "otherwise", "plain", "text", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/editors.js#L141-L162
17,417
APIDevTools/swagger-parser
online/src/js/parser.js
parser
function parser () { // When the form is submitted, parse the Swagger API form.form.on("submit", function (event) { event.preventDefault(); parseSwagger(); }); // When the "x" button is clicked, discard the results $("#clear").on("click", function () { swaggerParser = null; editors.clearResults(); analytics.trackEvent("results", "clear"); }); }
javascript
function parser () { // When the form is submitted, parse the Swagger API form.form.on("submit", function (event) { event.preventDefault(); parseSwagger(); }); // When the "x" button is clicked, discard the results $("#clear").on("click", function () { swaggerParser = null; editors.clearResults(); analytics.trackEvent("results", "clear"); }); }
[ "function", "parser", "(", ")", "{", "// When the form is submitted, parse the Swagger API", "form", ".", "form", ".", "on", "(", "\"submit\"", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "parseSwagger", "(", ")", ";", "}", ")", ";", "// When the \"x\" button is clicked, discard the results", "$", "(", "\"#clear\"", ")", ".", "on", "(", "\"click\"", ",", "function", "(", ")", "{", "swaggerParser", "=", "null", ";", "editors", ".", "clearResults", "(", ")", ";", "analytics", ".", "trackEvent", "(", "\"results\"", ",", "\"clear\"", ")", ";", "}", ")", ";", "}" ]
Adds event handlers to trigger Swagger Parser methods
[ "Adds", "event", "handlers", "to", "trigger", "Swagger", "Parser", "methods" ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/parser.js#L15-L28
17,418
APIDevTools/swagger-parser
online/src/js/parser.js
parseSwagger
function parseSwagger () { try { // Clear any previous results editors.clearResults(); // Get all the parameters swaggerParser = swaggerParser || new SwaggerParser(); var options = form.getOptions(); var method = form.method.button.val(); var api = form.getAPI(); // Call Swagger Parser swaggerParser[method](api, options) .then(function () { // Show the results var results = swaggerParser.$refs.values(); Object.keys(results).forEach(function (key) { editors.showResult(key, results[key]); }); }) .catch(function (err) { editors.showError(ono(err)); analytics.trackError(err); }); // Track the operation counters[method]++; analytics.trackEvent("button", "click", method, counters[method]); } catch (err) { editors.showError(ono(err)); analytics.trackError(err); } }
javascript
function parseSwagger () { try { // Clear any previous results editors.clearResults(); // Get all the parameters swaggerParser = swaggerParser || new SwaggerParser(); var options = form.getOptions(); var method = form.method.button.val(); var api = form.getAPI(); // Call Swagger Parser swaggerParser[method](api, options) .then(function () { // Show the results var results = swaggerParser.$refs.values(); Object.keys(results).forEach(function (key) { editors.showResult(key, results[key]); }); }) .catch(function (err) { editors.showError(ono(err)); analytics.trackError(err); }); // Track the operation counters[method]++; analytics.trackEvent("button", "click", method, counters[method]); } catch (err) { editors.showError(ono(err)); analytics.trackError(err); } }
[ "function", "parseSwagger", "(", ")", "{", "try", "{", "// Clear any previous results", "editors", ".", "clearResults", "(", ")", ";", "// Get all the parameters", "swaggerParser", "=", "swaggerParser", "||", "new", "SwaggerParser", "(", ")", ";", "var", "options", "=", "form", ".", "getOptions", "(", ")", ";", "var", "method", "=", "form", ".", "method", ".", "button", ".", "val", "(", ")", ";", "var", "api", "=", "form", ".", "getAPI", "(", ")", ";", "// Call Swagger Parser", "swaggerParser", "[", "method", "]", "(", "api", ",", "options", ")", ".", "then", "(", "function", "(", ")", "{", "// Show the results", "var", "results", "=", "swaggerParser", ".", "$refs", ".", "values", "(", ")", ";", "Object", ".", "keys", "(", "results", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "editors", ".", "showResult", "(", "key", ",", "results", "[", "key", "]", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "editors", ".", "showError", "(", "ono", "(", "err", ")", ")", ";", "analytics", ".", "trackError", "(", "err", ")", ";", "}", ")", ";", "// Track the operation", "counters", "[", "method", "]", "++", ";", "analytics", ".", "trackEvent", "(", "\"button\"", ",", "\"click\"", ",", "method", ",", "counters", "[", "method", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "editors", ".", "showError", "(", "ono", "(", "err", ")", ")", ";", "analytics", ".", "trackError", "(", "err", ")", ";", "}", "}" ]
This function is called when the "Validate it!" button is clicked. It calls Swagger Parser, passing it all the options selected on the form.
[ "This", "function", "is", "called", "when", "the", "Validate", "it!", "button", "is", "clicked", ".", "It", "calls", "Swagger", "Parser", "passing", "it", "all", "the", "options", "selected", "on", "the", "form", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/online/src/js/parser.js#L34-L67
17,419
APIDevTools/swagger-parser
lib/validators/spec.js
validateSpec
function validateSpec (api) { if (api.openapi) { // We don't (yet) support validating against the OpenAPI spec return; } var paths = Object.keys(api.paths || {}); var operationIds = []; paths.forEach(function (pathName) { var path = api.paths[pathName]; var pathId = "/paths" + pathName; if (path && pathName.indexOf("/") === 0) { validatePath(api, path, pathId, operationIds); } }); var definitions = Object.keys(api.definitions || {}); definitions.forEach(function (definitionName) { var definition = api.definitions[definitionName]; var definitionId = "/definitions/" + definitionName; validateRequiredPropertiesExist(definition, definitionId); }); }
javascript
function validateSpec (api) { if (api.openapi) { // We don't (yet) support validating against the OpenAPI spec return; } var paths = Object.keys(api.paths || {}); var operationIds = []; paths.forEach(function (pathName) { var path = api.paths[pathName]; var pathId = "/paths" + pathName; if (path && pathName.indexOf("/") === 0) { validatePath(api, path, pathId, operationIds); } }); var definitions = Object.keys(api.definitions || {}); definitions.forEach(function (definitionName) { var definition = api.definitions[definitionName]; var definitionId = "/definitions/" + definitionName; validateRequiredPropertiesExist(definition, definitionId); }); }
[ "function", "validateSpec", "(", "api", ")", "{", "if", "(", "api", ".", "openapi", ")", "{", "// We don't (yet) support validating against the OpenAPI spec", "return", ";", "}", "var", "paths", "=", "Object", ".", "keys", "(", "api", ".", "paths", "||", "{", "}", ")", ";", "var", "operationIds", "=", "[", "]", ";", "paths", ".", "forEach", "(", "function", "(", "pathName", ")", "{", "var", "path", "=", "api", ".", "paths", "[", "pathName", "]", ";", "var", "pathId", "=", "\"/paths\"", "+", "pathName", ";", "if", "(", "path", "&&", "pathName", ".", "indexOf", "(", "\"/\"", ")", "===", "0", ")", "{", "validatePath", "(", "api", ",", "path", ",", "pathId", ",", "operationIds", ")", ";", "}", "}", ")", ";", "var", "definitions", "=", "Object", ".", "keys", "(", "api", ".", "definitions", "||", "{", "}", ")", ";", "definitions", ".", "forEach", "(", "function", "(", "definitionName", ")", "{", "var", "definition", "=", "api", ".", "definitions", "[", "definitionName", "]", ";", "var", "definitionId", "=", "\"/definitions/\"", "+", "definitionName", ";", "validateRequiredPropertiesExist", "(", "definition", ",", "definitionId", ")", ";", "}", ")", ";", "}" ]
Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema. @param {SwaggerObject} api
[ "Validates", "parts", "of", "the", "Swagger", "2", ".", "0", "spec", "that", "aren", "t", "covered", "by", "the", "Swagger", "2", ".", "0", "JSON", "Schema", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L16-L38
17,420
APIDevTools/swagger-parser
lib/validators/spec.js
validatePath
function validatePath (api, path, pathId, operationIds) { swaggerMethods.forEach(function (operationName) { var operation = path[operationName]; var operationId = pathId + "/" + operationName; if (operation) { var declaredOperationId = operation.operationId; if (declaredOperationId) { if (operationIds.indexOf(declaredOperationId) === -1) { operationIds.push(declaredOperationId); } else { throw ono.syntax("Validation failed. Duplicate operation id '%s'", declaredOperationId); } } validateParameters(api, path, pathId, operation, operationId); var responses = Object.keys(operation.responses || {}); responses.forEach(function (responseName) { var response = operation.responses[responseName]; var responseId = operationId + "/responses/" + responseName; validateResponse(responseName, (response || {}), responseId); }); } }); }
javascript
function validatePath (api, path, pathId, operationIds) { swaggerMethods.forEach(function (operationName) { var operation = path[operationName]; var operationId = pathId + "/" + operationName; if (operation) { var declaredOperationId = operation.operationId; if (declaredOperationId) { if (operationIds.indexOf(declaredOperationId) === -1) { operationIds.push(declaredOperationId); } else { throw ono.syntax("Validation failed. Duplicate operation id '%s'", declaredOperationId); } } validateParameters(api, path, pathId, operation, operationId); var responses = Object.keys(operation.responses || {}); responses.forEach(function (responseName) { var response = operation.responses[responseName]; var responseId = operationId + "/responses/" + responseName; validateResponse(responseName, (response || {}), responseId); }); } }); }
[ "function", "validatePath", "(", "api", ",", "path", ",", "pathId", ",", "operationIds", ")", "{", "swaggerMethods", ".", "forEach", "(", "function", "(", "operationName", ")", "{", "var", "operation", "=", "path", "[", "operationName", "]", ";", "var", "operationId", "=", "pathId", "+", "\"/\"", "+", "operationName", ";", "if", "(", "operation", ")", "{", "var", "declaredOperationId", "=", "operation", ".", "operationId", ";", "if", "(", "declaredOperationId", ")", "{", "if", "(", "operationIds", ".", "indexOf", "(", "declaredOperationId", ")", "===", "-", "1", ")", "{", "operationIds", ".", "push", "(", "declaredOperationId", ")", ";", "}", "else", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. Duplicate operation id '%s'\"", ",", "declaredOperationId", ")", ";", "}", "}", "validateParameters", "(", "api", ",", "path", ",", "pathId", ",", "operation", ",", "operationId", ")", ";", "var", "responses", "=", "Object", ".", "keys", "(", "operation", ".", "responses", "||", "{", "}", ")", ";", "responses", ".", "forEach", "(", "function", "(", "responseName", ")", "{", "var", "response", "=", "operation", ".", "responses", "[", "responseName", "]", ";", "var", "responseId", "=", "operationId", "+", "\"/responses/\"", "+", "responseName", ";", "validateResponse", "(", "responseName", ",", "(", "response", "||", "{", "}", ")", ",", "responseId", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Validates the given path. @param {SwaggerObject} api - The entire Swagger API object @param {object} path - A Path object, from the Swagger API @param {string} pathId - A value that uniquely identifies the path @param {string} operationIds - An array of collected operationIds found in other paths
[ "Validates", "the", "given", "path", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L48-L73
17,421
APIDevTools/swagger-parser
lib/validators/spec.js
validateParameters
function validateParameters (api, path, pathId, operation, operationId) { var pathParams = path.parameters || []; var operationParams = operation.parameters || []; // Check for duplicate path parameters try { checkForDuplicates(pathParams); } catch (e) { throw ono.syntax(e, "Validation failed. %s has duplicate parameters", pathId); } // Check for duplicate operation parameters try { checkForDuplicates(operationParams); } catch (e) { throw ono.syntax(e, "Validation failed. %s has duplicate parameters", operationId); } // Combine the path and operation parameters, // with the operation params taking precedence over the path params var params = pathParams.reduce(function (combinedParams, value) { var duplicate = combinedParams.some(function (param) { return param.in === value.in && param.name === value.name; }); if (!duplicate) { combinedParams.push(value); } return combinedParams; }, operationParams.slice()); validateBodyParameters(params, operationId); validatePathParameters(params, pathId, operationId); validateParameterTypes(params, api, operation, operationId); }
javascript
function validateParameters (api, path, pathId, operation, operationId) { var pathParams = path.parameters || []; var operationParams = operation.parameters || []; // Check for duplicate path parameters try { checkForDuplicates(pathParams); } catch (e) { throw ono.syntax(e, "Validation failed. %s has duplicate parameters", pathId); } // Check for duplicate operation parameters try { checkForDuplicates(operationParams); } catch (e) { throw ono.syntax(e, "Validation failed. %s has duplicate parameters", operationId); } // Combine the path and operation parameters, // with the operation params taking precedence over the path params var params = pathParams.reduce(function (combinedParams, value) { var duplicate = combinedParams.some(function (param) { return param.in === value.in && param.name === value.name; }); if (!duplicate) { combinedParams.push(value); } return combinedParams; }, operationParams.slice()); validateBodyParameters(params, operationId); validatePathParameters(params, pathId, operationId); validateParameterTypes(params, api, operation, operationId); }
[ "function", "validateParameters", "(", "api", ",", "path", ",", "pathId", ",", "operation", ",", "operationId", ")", "{", "var", "pathParams", "=", "path", ".", "parameters", "||", "[", "]", ";", "var", "operationParams", "=", "operation", ".", "parameters", "||", "[", "]", ";", "// Check for duplicate path parameters", "try", "{", "checkForDuplicates", "(", "pathParams", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "ono", ".", "syntax", "(", "e", ",", "\"Validation failed. %s has duplicate parameters\"", ",", "pathId", ")", ";", "}", "// Check for duplicate operation parameters", "try", "{", "checkForDuplicates", "(", "operationParams", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "ono", ".", "syntax", "(", "e", ",", "\"Validation failed. %s has duplicate parameters\"", ",", "operationId", ")", ";", "}", "// Combine the path and operation parameters,", "// with the operation params taking precedence over the path params", "var", "params", "=", "pathParams", ".", "reduce", "(", "function", "(", "combinedParams", ",", "value", ")", "{", "var", "duplicate", "=", "combinedParams", ".", "some", "(", "function", "(", "param", ")", "{", "return", "param", ".", "in", "===", "value", ".", "in", "&&", "param", ".", "name", "===", "value", ".", "name", ";", "}", ")", ";", "if", "(", "!", "duplicate", ")", "{", "combinedParams", ".", "push", "(", "value", ")", ";", "}", "return", "combinedParams", ";", "}", ",", "operationParams", ".", "slice", "(", ")", ")", ";", "validateBodyParameters", "(", "params", ",", "operationId", ")", ";", "validatePathParameters", "(", "params", ",", "pathId", ",", "operationId", ")", ";", "validateParameterTypes", "(", "params", ",", "api", ",", "operation", ",", "operationId", ")", ";", "}" ]
Validates the parameters for the given operation. @param {SwaggerObject} api - The entire Swagger API object @param {object} path - A Path object, from the Swagger API @param {string} pathId - A value that uniquely identifies the path @param {object} operation - An Operation object, from the Swagger API @param {string} operationId - A value that uniquely identifies the operation
[ "Validates", "the", "parameters", "for", "the", "given", "operation", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L84-L119
17,422
APIDevTools/swagger-parser
lib/validators/spec.js
validateBodyParameters
function validateBodyParameters (params, operationId) { var bodyParams = params.filter(function (param) { return param.in === "body"; }); var formParams = params.filter(function (param) { return param.in === "formData"; }); // There can only be one "body" parameter if (bodyParams.length > 1) { throw ono.syntax( "Validation failed. %s has %d body parameters. Only one is allowed.", operationId, bodyParams.length ); } else if (bodyParams.length > 0 && formParams.length > 0) { // "body" params and "formData" params are mutually exclusive throw ono.syntax( "Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.", operationId ); } }
javascript
function validateBodyParameters (params, operationId) { var bodyParams = params.filter(function (param) { return param.in === "body"; }); var formParams = params.filter(function (param) { return param.in === "formData"; }); // There can only be one "body" parameter if (bodyParams.length > 1) { throw ono.syntax( "Validation failed. %s has %d body parameters. Only one is allowed.", operationId, bodyParams.length ); } else if (bodyParams.length > 0 && formParams.length > 0) { // "body" params and "formData" params are mutually exclusive throw ono.syntax( "Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.", operationId ); } }
[ "function", "validateBodyParameters", "(", "params", ",", "operationId", ")", "{", "var", "bodyParams", "=", "params", ".", "filter", "(", "function", "(", "param", ")", "{", "return", "param", ".", "in", "===", "\"body\"", ";", "}", ")", ";", "var", "formParams", "=", "params", ".", "filter", "(", "function", "(", "param", ")", "{", "return", "param", ".", "in", "===", "\"formData\"", ";", "}", ")", ";", "// There can only be one \"body\" parameter", "if", "(", "bodyParams", ".", "length", ">", "1", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has %d body parameters. Only one is allowed.\"", ",", "operationId", ",", "bodyParams", ".", "length", ")", ";", "}", "else", "if", "(", "bodyParams", ".", "length", ">", "0", "&&", "formParams", ".", "length", ">", "0", ")", "{", "// \"body\" params and \"formData\" params are mutually exclusive", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.\"", ",", "operationId", ")", ";", "}", "}" ]
Validates body and formData parameters for the given operation. @param {object[]} params - An array of Parameter objects @param {string} operationId - A value that uniquely identifies the operation
[ "Validates", "body", "and", "formData", "parameters", "for", "the", "given", "operation", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L127-L145
17,423
APIDevTools/swagger-parser
lib/validators/spec.js
validatePathParameters
function validatePathParameters (params, pathId, operationId) { // Find all {placeholders} in the path string var placeholders = pathId.match(util.swaggerParamRegExp) || []; // Check for duplicates for (var i = 0; i < placeholders.length; i++) { for (var j = i + 1; j < placeholders.length; j++) { if (placeholders[i] === placeholders[j]) { throw ono.syntax( "Validation failed. %s has multiple path placeholders named %s", operationId, placeholders[i]); } } } params .filter(function (param) { return param.in === "path"; }) .forEach(function (param) { if (param.required !== true) { throw ono.syntax( 'Validation failed. Path parameters cannot be optional. Set required=true for the "%s" parameter at %s', param.name, operationId ); } var match = placeholders.indexOf("{" + param.name + "}"); if (match === -1) { throw ono.syntax( 'Validation failed. %s has a path parameter named "%s", ' + "but there is no corresponding {%s} in the path string", operationId, param.name, param.name ); } placeholders.splice(match, 1); }); if (placeholders.length > 0) { throw ono.syntax("Validation failed. %s is missing path parameter(s) for %s", operationId, placeholders); } }
javascript
function validatePathParameters (params, pathId, operationId) { // Find all {placeholders} in the path string var placeholders = pathId.match(util.swaggerParamRegExp) || []; // Check for duplicates for (var i = 0; i < placeholders.length; i++) { for (var j = i + 1; j < placeholders.length; j++) { if (placeholders[i] === placeholders[j]) { throw ono.syntax( "Validation failed. %s has multiple path placeholders named %s", operationId, placeholders[i]); } } } params .filter(function (param) { return param.in === "path"; }) .forEach(function (param) { if (param.required !== true) { throw ono.syntax( 'Validation failed. Path parameters cannot be optional. Set required=true for the "%s" parameter at %s', param.name, operationId ); } var match = placeholders.indexOf("{" + param.name + "}"); if (match === -1) { throw ono.syntax( 'Validation failed. %s has a path parameter named "%s", ' + "but there is no corresponding {%s} in the path string", operationId, param.name, param.name ); } placeholders.splice(match, 1); }); if (placeholders.length > 0) { throw ono.syntax("Validation failed. %s is missing path parameter(s) for %s", operationId, placeholders); } }
[ "function", "validatePathParameters", "(", "params", ",", "pathId", ",", "operationId", ")", "{", "// Find all {placeholders} in the path string", "var", "placeholders", "=", "pathId", ".", "match", "(", "util", ".", "swaggerParamRegExp", ")", "||", "[", "]", ";", "// Check for duplicates", "for", "(", "var", "i", "=", "0", ";", "i", "<", "placeholders", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "placeholders", ".", "length", ";", "j", "++", ")", "{", "if", "(", "placeholders", "[", "i", "]", "===", "placeholders", "[", "j", "]", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has multiple path placeholders named %s\"", ",", "operationId", ",", "placeholders", "[", "i", "]", ")", ";", "}", "}", "}", "params", ".", "filter", "(", "function", "(", "param", ")", "{", "return", "param", ".", "in", "===", "\"path\"", ";", "}", ")", ".", "forEach", "(", "function", "(", "param", ")", "{", "if", "(", "param", ".", "required", "!==", "true", ")", "{", "throw", "ono", ".", "syntax", "(", "'Validation failed. Path parameters cannot be optional. Set required=true for the \"%s\" parameter at %s'", ",", "param", ".", "name", ",", "operationId", ")", ";", "}", "var", "match", "=", "placeholders", ".", "indexOf", "(", "\"{\"", "+", "param", ".", "name", "+", "\"}\"", ")", ";", "if", "(", "match", "===", "-", "1", ")", "{", "throw", "ono", ".", "syntax", "(", "'Validation failed. %s has a path parameter named \"%s\", '", "+", "\"but there is no corresponding {%s} in the path string\"", ",", "operationId", ",", "param", ".", "name", ",", "param", ".", "name", ")", ";", "}", "placeholders", ".", "splice", "(", "match", ",", "1", ")", ";", "}", ")", ";", "if", "(", "placeholders", ".", "length", ">", "0", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s is missing path parameter(s) for %s\"", ",", "operationId", ",", "placeholders", ")", ";", "}", "}" ]
Validates path parameters for the given path. @param {object[]} params - An array of Parameter objects @param {string} pathId - A value that uniquely identifies the path @param {string} operationId - A value that uniquely identifies the operation
[ "Validates", "path", "parameters", "for", "the", "given", "path", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L154-L194
17,424
APIDevTools/swagger-parser
lib/validators/spec.js
validateParameterTypes
function validateParameterTypes (params, api, operation, operationId) { params.forEach(function (param) { var parameterId = operationId + "/parameters/" + param.name; var schema, validTypes; switch (param.in) { case "body": schema = param.schema; validTypes = schemaTypes; break; case "formData": schema = param; validTypes = primitiveTypes.concat("file"); break; default: schema = param; validTypes = primitiveTypes; } validateSchema(schema, parameterId, validTypes); validateRequiredPropertiesExist(schema, parameterId); if (schema.type === "file") { // "file" params must consume at least one of these MIME types var formData = /multipart\/(.*\+)?form-data/; var urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/; var consumes = operation.consumes || api.consumes || []; var hasValidMimeType = consumes.some(function (consume) { return formData.test(consume) || urlEncoded.test(consume); }); if (!hasValidMimeType) { throw ono.syntax( "Validation failed. %s has a file parameter, so it must consume multipart/form-data " + "or application/x-www-form-urlencoded", operationId ); } } }); }
javascript
function validateParameterTypes (params, api, operation, operationId) { params.forEach(function (param) { var parameterId = operationId + "/parameters/" + param.name; var schema, validTypes; switch (param.in) { case "body": schema = param.schema; validTypes = schemaTypes; break; case "formData": schema = param; validTypes = primitiveTypes.concat("file"); break; default: schema = param; validTypes = primitiveTypes; } validateSchema(schema, parameterId, validTypes); validateRequiredPropertiesExist(schema, parameterId); if (schema.type === "file") { // "file" params must consume at least one of these MIME types var formData = /multipart\/(.*\+)?form-data/; var urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/; var consumes = operation.consumes || api.consumes || []; var hasValidMimeType = consumes.some(function (consume) { return formData.test(consume) || urlEncoded.test(consume); }); if (!hasValidMimeType) { throw ono.syntax( "Validation failed. %s has a file parameter, so it must consume multipart/form-data " + "or application/x-www-form-urlencoded", operationId ); } } }); }
[ "function", "validateParameterTypes", "(", "params", ",", "api", ",", "operation", ",", "operationId", ")", "{", "params", ".", "forEach", "(", "function", "(", "param", ")", "{", "var", "parameterId", "=", "operationId", "+", "\"/parameters/\"", "+", "param", ".", "name", ";", "var", "schema", ",", "validTypes", ";", "switch", "(", "param", ".", "in", ")", "{", "case", "\"body\"", ":", "schema", "=", "param", ".", "schema", ";", "validTypes", "=", "schemaTypes", ";", "break", ";", "case", "\"formData\"", ":", "schema", "=", "param", ";", "validTypes", "=", "primitiveTypes", ".", "concat", "(", "\"file\"", ")", ";", "break", ";", "default", ":", "schema", "=", "param", ";", "validTypes", "=", "primitiveTypes", ";", "}", "validateSchema", "(", "schema", ",", "parameterId", ",", "validTypes", ")", ";", "validateRequiredPropertiesExist", "(", "schema", ",", "parameterId", ")", ";", "if", "(", "schema", ".", "type", "===", "\"file\"", ")", "{", "// \"file\" params must consume at least one of these MIME types", "var", "formData", "=", "/", "multipart\\/(.*\\+)?form-data", "/", ";", "var", "urlEncoded", "=", "/", "application\\/(.*\\+)?x-www-form-urlencoded", "/", ";", "var", "consumes", "=", "operation", ".", "consumes", "||", "api", ".", "consumes", "||", "[", "]", ";", "var", "hasValidMimeType", "=", "consumes", ".", "some", "(", "function", "(", "consume", ")", "{", "return", "formData", ".", "test", "(", "consume", ")", "||", "urlEncoded", ".", "test", "(", "consume", ")", ";", "}", ")", ";", "if", "(", "!", "hasValidMimeType", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has a file parameter, so it must consume multipart/form-data \"", "+", "\"or application/x-www-form-urlencoded\"", ",", "operationId", ")", ";", "}", "}", "}", ")", ";", "}" ]
Validates data types of parameters for the given operation. @param {object[]} params - An array of Parameter objects @param {object} api - The entire Swagger API object @param {object} operation - An Operation object, from the Swagger API @param {string} operationId - A value that uniquely identifies the operation
[ "Validates", "data", "types", "of", "parameters", "for", "the", "given", "operation", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L204-L246
17,425
APIDevTools/swagger-parser
lib/validators/spec.js
checkForDuplicates
function checkForDuplicates (params) { for (var i = 0; i < params.length - 1; i++) { var outer = params[i]; for (var j = i + 1; j < params.length; j++) { var inner = params[j]; if (outer.name === inner.name && outer.in === inner.in) { throw ono.syntax('Validation failed. Found multiple %s parameters named "%s"', outer.in, outer.name); } } } }
javascript
function checkForDuplicates (params) { for (var i = 0; i < params.length - 1; i++) { var outer = params[i]; for (var j = i + 1; j < params.length; j++) { var inner = params[j]; if (outer.name === inner.name && outer.in === inner.in) { throw ono.syntax('Validation failed. Found multiple %s parameters named "%s"', outer.in, outer.name); } } } }
[ "function", "checkForDuplicates", "(", "params", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "params", ".", "length", "-", "1", ";", "i", "++", ")", "{", "var", "outer", "=", "params", "[", "i", "]", ";", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "params", ".", "length", ";", "j", "++", ")", "{", "var", "inner", "=", "params", "[", "j", "]", ";", "if", "(", "outer", ".", "name", "===", "inner", ".", "name", "&&", "outer", ".", "in", "===", "inner", ".", "in", ")", "{", "throw", "ono", ".", "syntax", "(", "'Validation failed. Found multiple %s parameters named \"%s\"'", ",", "outer", ".", "in", ",", "outer", ".", "name", ")", ";", "}", "}", "}", "}" ]
Checks the given parameter list for duplicates, and throws an error if found. @param {object[]} params - An array of Parameter objects
[ "Checks", "the", "given", "parameter", "list", "for", "duplicates", "and", "throws", "an", "error", "if", "found", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L253-L263
17,426
APIDevTools/swagger-parser
lib/validators/spec.js
validateResponse
function validateResponse (code, response, responseId) { if (code !== "default" && (code < 100 || code > 599)) { throw ono.syntax("Validation failed. %s has an invalid response code (%s)", responseId, code); } var headers = Object.keys(response.headers || {}); headers.forEach(function (headerName) { var header = response.headers[headerName]; var headerId = responseId + "/headers/" + headerName; validateSchema(header, headerId, primitiveTypes); }); if (response.schema) { var validTypes = schemaTypes.concat("file"); if (validTypes.indexOf(response.schema.type) === -1) { throw ono.syntax( "Validation failed. %s has an invalid response schema type (%s)", responseId, response.schema.type); } else { validateSchema(response.schema, responseId + "/schema", validTypes); } } }
javascript
function validateResponse (code, response, responseId) { if (code !== "default" && (code < 100 || code > 599)) { throw ono.syntax("Validation failed. %s has an invalid response code (%s)", responseId, code); } var headers = Object.keys(response.headers || {}); headers.forEach(function (headerName) { var header = response.headers[headerName]; var headerId = responseId + "/headers/" + headerName; validateSchema(header, headerId, primitiveTypes); }); if (response.schema) { var validTypes = schemaTypes.concat("file"); if (validTypes.indexOf(response.schema.type) === -1) { throw ono.syntax( "Validation failed. %s has an invalid response schema type (%s)", responseId, response.schema.type); } else { validateSchema(response.schema, responseId + "/schema", validTypes); } } }
[ "function", "validateResponse", "(", "code", ",", "response", ",", "responseId", ")", "{", "if", "(", "code", "!==", "\"default\"", "&&", "(", "code", "<", "100", "||", "code", ">", "599", ")", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has an invalid response code (%s)\"", ",", "responseId", ",", "code", ")", ";", "}", "var", "headers", "=", "Object", ".", "keys", "(", "response", ".", "headers", "||", "{", "}", ")", ";", "headers", ".", "forEach", "(", "function", "(", "headerName", ")", "{", "var", "header", "=", "response", ".", "headers", "[", "headerName", "]", ";", "var", "headerId", "=", "responseId", "+", "\"/headers/\"", "+", "headerName", ";", "validateSchema", "(", "header", ",", "headerId", ",", "primitiveTypes", ")", ";", "}", ")", ";", "if", "(", "response", ".", "schema", ")", "{", "var", "validTypes", "=", "schemaTypes", ".", "concat", "(", "\"file\"", ")", ";", "if", "(", "validTypes", ".", "indexOf", "(", "response", ".", "schema", ".", "type", ")", "===", "-", "1", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has an invalid response schema type (%s)\"", ",", "responseId", ",", "response", ".", "schema", ".", "type", ")", ";", "}", "else", "{", "validateSchema", "(", "response", ".", "schema", ",", "responseId", "+", "\"/schema\"", ",", "validTypes", ")", ";", "}", "}", "}" ]
Validates the given response object. @param {string} code - The HTTP response code (or "default") @param {object} response - A Response object, from the Swagger API @param {string} responseId - A value that uniquely identifies the response
[ "Validates", "the", "given", "response", "object", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L272-L294
17,427
APIDevTools/swagger-parser
lib/validators/spec.js
validateSchema
function validateSchema (schema, schemaId, validTypes) { if (validTypes.indexOf(schema.type) === -1) { throw ono.syntax( "Validation failed. %s has an invalid type (%s)", schemaId, schema.type); } if (schema.type === "array" && !schema.items) { throw ono.syntax('Validation failed. %s is an array, so it must include an "items" schema', schemaId); } }
javascript
function validateSchema (schema, schemaId, validTypes) { if (validTypes.indexOf(schema.type) === -1) { throw ono.syntax( "Validation failed. %s has an invalid type (%s)", schemaId, schema.type); } if (schema.type === "array" && !schema.items) { throw ono.syntax('Validation failed. %s is an array, so it must include an "items" schema', schemaId); } }
[ "function", "validateSchema", "(", "schema", ",", "schemaId", ",", "validTypes", ")", "{", "if", "(", "validTypes", ".", "indexOf", "(", "schema", ".", "type", ")", "===", "-", "1", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. %s has an invalid type (%s)\"", ",", "schemaId", ",", "schema", ".", "type", ")", ";", "}", "if", "(", "schema", ".", "type", "===", "\"array\"", "&&", "!", "schema", ".", "items", ")", "{", "throw", "ono", ".", "syntax", "(", "'Validation failed. %s is an array, so it must include an \"items\" schema'", ",", "schemaId", ")", ";", "}", "}" ]
Validates the given Swagger schema object. @param {object} schema - A Schema object, from the Swagger API @param {string} schemaId - A value that uniquely identifies the schema object @param {string[]} validTypes - An array of the allowed schema types
[ "Validates", "the", "given", "Swagger", "schema", "object", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L303-L312
17,428
APIDevTools/swagger-parser
lib/validators/spec.js
validateRequiredPropertiesExist
function validateRequiredPropertiesExist (schema, schemaId) { /** * Recursively collects all properties of the schema and its ancestors. They are added to the props object. */ function collectProperties (schemaObj, props) { if (schemaObj.properties) { for (var property in schemaObj.properties) { if (schemaObj.properties.hasOwnProperty(property)) { props[property] = schemaObj.properties[property]; } } } if (schemaObj.allOf) { schemaObj.allOf.forEach(function (parent) { collectProperties(parent, props); }); } } if (schema.required && Array.isArray(schema.required)) { var props = {}; collectProperties(schema, props); schema.required.forEach(function (requiredProperty) { if (!props[requiredProperty]) { throw ono.syntax("Validation failed. Property '%s' listed as required but does not exist in '%s'", requiredProperty, schemaId); } }); } }
javascript
function validateRequiredPropertiesExist (schema, schemaId) { /** * Recursively collects all properties of the schema and its ancestors. They are added to the props object. */ function collectProperties (schemaObj, props) { if (schemaObj.properties) { for (var property in schemaObj.properties) { if (schemaObj.properties.hasOwnProperty(property)) { props[property] = schemaObj.properties[property]; } } } if (schemaObj.allOf) { schemaObj.allOf.forEach(function (parent) { collectProperties(parent, props); }); } } if (schema.required && Array.isArray(schema.required)) { var props = {}; collectProperties(schema, props); schema.required.forEach(function (requiredProperty) { if (!props[requiredProperty]) { throw ono.syntax("Validation failed. Property '%s' listed as required but does not exist in '%s'", requiredProperty, schemaId); } }); } }
[ "function", "validateRequiredPropertiesExist", "(", "schema", ",", "schemaId", ")", "{", "/**\n * Recursively collects all properties of the schema and its ancestors. They are added to the props object.\n */", "function", "collectProperties", "(", "schemaObj", ",", "props", ")", "{", "if", "(", "schemaObj", ".", "properties", ")", "{", "for", "(", "var", "property", "in", "schemaObj", ".", "properties", ")", "{", "if", "(", "schemaObj", ".", "properties", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "props", "[", "property", "]", "=", "schemaObj", ".", "properties", "[", "property", "]", ";", "}", "}", "}", "if", "(", "schemaObj", ".", "allOf", ")", "{", "schemaObj", ".", "allOf", ".", "forEach", "(", "function", "(", "parent", ")", "{", "collectProperties", "(", "parent", ",", "props", ")", ";", "}", ")", ";", "}", "}", "if", "(", "schema", ".", "required", "&&", "Array", ".", "isArray", "(", "schema", ".", "required", ")", ")", "{", "var", "props", "=", "{", "}", ";", "collectProperties", "(", "schema", ",", "props", ")", ";", "schema", ".", "required", ".", "forEach", "(", "function", "(", "requiredProperty", ")", "{", "if", "(", "!", "props", "[", "requiredProperty", "]", ")", "{", "throw", "ono", ".", "syntax", "(", "\"Validation failed. Property '%s' listed as required but does not exist in '%s'\"", ",", "requiredProperty", ",", "schemaId", ")", ";", "}", "}", ")", ";", "}", "}" ]
Validates that the declared properties of the given Swagger schema object actually exist. @param {object} schema - A Schema object, from the Swagger API @param {string} schemaId - A value that uniquely identifies the schema object
[ "Validates", "that", "the", "declared", "properties", "of", "the", "given", "Swagger", "schema", "object", "actually", "exist", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L320-L349
17,429
APIDevTools/swagger-parser
lib/validators/spec.js
collectProperties
function collectProperties (schemaObj, props) { if (schemaObj.properties) { for (var property in schemaObj.properties) { if (schemaObj.properties.hasOwnProperty(property)) { props[property] = schemaObj.properties[property]; } } } if (schemaObj.allOf) { schemaObj.allOf.forEach(function (parent) { collectProperties(parent, props); }); } }
javascript
function collectProperties (schemaObj, props) { if (schemaObj.properties) { for (var property in schemaObj.properties) { if (schemaObj.properties.hasOwnProperty(property)) { props[property] = schemaObj.properties[property]; } } } if (schemaObj.allOf) { schemaObj.allOf.forEach(function (parent) { collectProperties(parent, props); }); } }
[ "function", "collectProperties", "(", "schemaObj", ",", "props", ")", "{", "if", "(", "schemaObj", ".", "properties", ")", "{", "for", "(", "var", "property", "in", "schemaObj", ".", "properties", ")", "{", "if", "(", "schemaObj", ".", "properties", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "props", "[", "property", "]", "=", "schemaObj", ".", "properties", "[", "property", "]", ";", "}", "}", "}", "if", "(", "schemaObj", ".", "allOf", ")", "{", "schemaObj", ".", "allOf", ".", "forEach", "(", "function", "(", "parent", ")", "{", "collectProperties", "(", "parent", ",", "props", ")", ";", "}", ")", ";", "}", "}" ]
Recursively collects all properties of the schema and its ancestors. They are added to the props object.
[ "Recursively", "collects", "all", "properties", "of", "the", "schema", "and", "its", "ancestors", ".", "They", "are", "added", "to", "the", "props", "object", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/spec.js#L324-L337
17,430
APIDevTools/swagger-parser
lib/validators/schema.js
validateSchema
function validateSchema (api) { // Choose the appropriate schema (Swagger or OpenAPI) var schema = api.swagger ? require("swagger-schema-official/schema.json") : require("openapi-schema-validation/schema/openapi-3.0.json"); var isValid = ZSchema.validate(api, schema); if (!isValid) { var err = ZSchema.getLastError(); var message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details); throw ono.syntax(err, { details: err.details }, message); } }
javascript
function validateSchema (api) { // Choose the appropriate schema (Swagger or OpenAPI) var schema = api.swagger ? require("swagger-schema-official/schema.json") : require("openapi-schema-validation/schema/openapi-3.0.json"); var isValid = ZSchema.validate(api, schema); if (!isValid) { var err = ZSchema.getLastError(); var message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details); throw ono.syntax(err, { details: err.details }, message); } }
[ "function", "validateSchema", "(", "api", ")", "{", "// Choose the appropriate schema (Swagger or OpenAPI)", "var", "schema", "=", "api", ".", "swagger", "?", "require", "(", "\"swagger-schema-official/schema.json\"", ")", ":", "require", "(", "\"openapi-schema-validation/schema/openapi-3.0.json\"", ")", ";", "var", "isValid", "=", "ZSchema", ".", "validate", "(", "api", ",", "schema", ")", ";", "if", "(", "!", "isValid", ")", "{", "var", "err", "=", "ZSchema", ".", "getLastError", "(", ")", ";", "var", "message", "=", "\"Swagger schema validation failed. \\n\"", "+", "formatZSchemaError", "(", "err", ".", "details", ")", ";", "throw", "ono", ".", "syntax", "(", "err", ",", "{", "details", ":", "err", ".", "details", "}", ",", "message", ")", ";", "}", "}" ]
Validates the given Swagger API against the Swagger 2.0 or 3.0 schema. @param {SwaggerObject} api
[ "Validates", "the", "given", "Swagger", "API", "against", "the", "Swagger", "2", ".", "0", "or", "3", ".", "0", "schema", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/schema.js#L16-L29
17,431
APIDevTools/swagger-parser
lib/validators/schema.js
initializeZSchema
function initializeZSchema () { ZSchema = new ZSchema({ breakOnFirstError: true, noExtraKeywords: true, ignoreUnknownFormats: false, reportPathAsArray: true }); }
javascript
function initializeZSchema () { ZSchema = new ZSchema({ breakOnFirstError: true, noExtraKeywords: true, ignoreUnknownFormats: false, reportPathAsArray: true }); }
[ "function", "initializeZSchema", "(", ")", "{", "ZSchema", "=", "new", "ZSchema", "(", "{", "breakOnFirstError", ":", "true", ",", "noExtraKeywords", ":", "true", ",", "ignoreUnknownFormats", ":", "false", ",", "reportPathAsArray", ":", "true", "}", ")", ";", "}" ]
Performs one-time initialization logic to prepare for Swagger Schema validation.
[ "Performs", "one", "-", "time", "initialization", "logic", "to", "prepare", "for", "Swagger", "Schema", "validation", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/schema.js#L34-L41
17,432
APIDevTools/swagger-parser
lib/validators/schema.js
formatZSchemaError
function formatZSchemaError (errors, indent) { indent = indent || " "; var message = ""; errors.forEach(function (error, index) { message += util.format("%s%s at #/%s\n", indent, error.message, error.path.join("/")); if (error.inner) { message += formatZSchemaError(error.inner, indent + " "); } }); return message; }
javascript
function formatZSchemaError (errors, indent) { indent = indent || " "; var message = ""; errors.forEach(function (error, index) { message += util.format("%s%s at #/%s\n", indent, error.message, error.path.join("/")); if (error.inner) { message += formatZSchemaError(error.inner, indent + " "); } }); return message; }
[ "function", "formatZSchemaError", "(", "errors", ",", "indent", ")", "{", "indent", "=", "indent", "||", "\" \"", ";", "var", "message", "=", "\"\"", ";", "errors", ".", "forEach", "(", "function", "(", "error", ",", "index", ")", "{", "message", "+=", "util", ".", "format", "(", "\"%s%s at #/%s\\n\"", ",", "indent", ",", "error", ".", "message", ",", "error", ".", "path", ".", "join", "(", "\"/\"", ")", ")", ";", "if", "(", "error", ".", "inner", ")", "{", "message", "+=", "formatZSchemaError", "(", "error", ".", "inner", ",", "indent", "+", "\" \"", ")", ";", "}", "}", ")", ";", "return", "message", ";", "}" ]
Z-Schema validation errors are a nested tree structure. This function crawls that tree and builds an error message string. @param {object[]} errors - The Z-Schema error details @param {string} [indent] - The whitespace used to indent the error message @returns {string}
[ "Z", "-", "Schema", "validation", "errors", "are", "a", "nested", "tree", "structure", ".", "This", "function", "crawls", "that", "tree", "and", "builds", "an", "error", "message", "string", "." ]
3cbf3357ea64a31ca66d9c460be97947f12dfb51
https://github.com/APIDevTools/swagger-parser/blob/3cbf3357ea64a31ca66d9c460be97947f12dfb51/lib/validators/schema.js#L51-L61
17,433
bvaughn/redux-search
source/selectors.js
createFilterFunction
function createFilterFunction (resource) { return resource.has instanceof Function ? id => resource.has(id) : id => resource[id] }
javascript
function createFilterFunction (resource) { return resource.has instanceof Function ? id => resource.has(id) : id => resource[id] }
[ "function", "createFilterFunction", "(", "resource", ")", "{", "return", "resource", ".", "has", "instanceof", "Function", "?", "id", "=>", "resource", ".", "has", "(", "id", ")", ":", "id", "=>", "resource", "[", "id", "]", "}" ]
Creates a default filter function capable of handling Maps and Objects.
[ "Creates", "a", "default", "filter", "function", "capable", "of", "handling", "Maps", "and", "Objects", "." ]
f6e770ee30d8bcdb713b731a28d757aaabbc9560
https://github.com/bvaughn/redux-search/blob/f6e770ee30d8bcdb713b731a28d757aaabbc9560/source/selectors.js#L47-L51
17,434
QingWei-Li/laue
dist/laue.js
genTicks
function genTicks(min, max, count) { var assign; if (max < min) { (assign = [max, min], min = assign[0], max = assign[1]); } var step = tickStep(min, max, count); var first = Math.floor(min / step) * step; var ticks$$1 = [first]; var cur = first; while (cur < max) { cur += step; ticks$$1.push(cur); } if (Math.abs(min - ticks$$1[1]) < step) { ticks$$1.shift(); ticks$$1[0] = min; } if (Math.abs(max - ticks$$1[ticks$$1.length - 2]) < step) { ticks$$1.pop(); ticks$$1[ticks$$1.length - 1] = max; } return ticks$$1 }
javascript
function genTicks(min, max, count) { var assign; if (max < min) { (assign = [max, min], min = assign[0], max = assign[1]); } var step = tickStep(min, max, count); var first = Math.floor(min / step) * step; var ticks$$1 = [first]; var cur = first; while (cur < max) { cur += step; ticks$$1.push(cur); } if (Math.abs(min - ticks$$1[1]) < step) { ticks$$1.shift(); ticks$$1[0] = min; } if (Math.abs(max - ticks$$1[ticks$$1.length - 2]) < step) { ticks$$1.pop(); ticks$$1[ticks$$1.length - 1] = max; } return ticks$$1 }
[ "function", "genTicks", "(", "min", ",", "max", ",", "count", ")", "{", "var", "assign", ";", "if", "(", "max", "<", "min", ")", "{", "(", "assign", "=", "[", "max", ",", "min", "]", ",", "min", "=", "assign", "[", "0", "]", ",", "max", "=", "assign", "[", "1", "]", ")", ";", "}", "var", "step", "=", "tickStep", "(", "min", ",", "max", ",", "count", ")", ";", "var", "first", "=", "Math", ".", "floor", "(", "min", "/", "step", ")", "*", "step", ";", "var", "ticks$$1", "=", "[", "first", "]", ";", "var", "cur", "=", "first", ";", "while", "(", "cur", "<", "max", ")", "{", "cur", "+=", "step", ";", "ticks$$1", ".", "push", "(", "cur", ")", ";", "}", "if", "(", "Math", ".", "abs", "(", "min", "-", "ticks$$1", "[", "1", "]", ")", "<", "step", ")", "{", "ticks$$1", ".", "shift", "(", ")", ";", "ticks$$1", "[", "0", "]", "=", "min", ";", "}", "if", "(", "Math", ".", "abs", "(", "max", "-", "ticks$$1", "[", "ticks$$1", ".", "length", "-", "2", "]", ")", "<", "step", ")", "{", "ticks$$1", ".", "pop", "(", ")", ";", "ticks$$1", "[", "ticks$$1", ".", "length", "-", "1", "]", "=", "max", ";", "}", "return", "ticks$$1", "}" ]
Returns nick ticks
[ "Returns", "nick", "ticks" ]
65f9a4ce0c5971ec6fe1d927d9f8e471bfa88df5
https://github.com/QingWei-Li/laue/blob/65f9a4ce0c5971ec6fe1d927d9f8e471bfa88df5/dist/laue.js#L316-L344
17,435
mathjax/MathJax-node
lib/main.js
function () { var styles = document.head.getElementsByTagName("style"); CHTMLSTYLES = styles[styles.length-1].innerHTML; this.pxPerInch = 96; this.defaultEx = 6; this.defaultEm = 6 / CHTML.TEX.x_height * 1000; this.defaultWidth = 100; }
javascript
function () { var styles = document.head.getElementsByTagName("style"); CHTMLSTYLES = styles[styles.length-1].innerHTML; this.pxPerInch = 96; this.defaultEx = 6; this.defaultEm = 6 / CHTML.TEX.x_height * 1000; this.defaultWidth = 100; }
[ "function", "(", ")", "{", "var", "styles", "=", "document", ".", "head", ".", "getElementsByTagName", "(", "\"style\"", ")", ";", "CHTMLSTYLES", "=", "styles", "[", "styles", ".", "length", "-", "1", "]", ".", "innerHTML", ";", "this", ".", "pxPerInch", "=", "96", ";", "this", ".", "defaultEx", "=", "6", ";", "this", ".", "defaultEm", "=", "6", "/", "CHTML", ".", "TEX", ".", "x_height", "*", "1000", ";", "this", ".", "defaultWidth", "=", "100", ";", "}" ]
Set up the default ex-size and width
[ "Set", "up", "the", "default", "ex", "-", "size", "and", "width" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L389-L396
17,436
mathjax/MathJax-node
lib/main.js
Insert
function Insert(dst,src) { for (var id in src) {if (src.hasOwnProperty(id)) { // allow for concatenation of arrays? if (typeof src[id] === 'object' && !(src[id] instanceof Array) && (typeof dst[id] === 'object' || typeof dst[id] === 'function')) {Insert(dst[id],src[id])} else {dst[id] = src[id]} }} return dst; }
javascript
function Insert(dst,src) { for (var id in src) {if (src.hasOwnProperty(id)) { // allow for concatenation of arrays? if (typeof src[id] === 'object' && !(src[id] instanceof Array) && (typeof dst[id] === 'object' || typeof dst[id] === 'function')) {Insert(dst[id],src[id])} else {dst[id] = src[id]} }} return dst; }
[ "function", "Insert", "(", "dst", ",", "src", ")", "{", "for", "(", "var", "id", "in", "src", ")", "{", "if", "(", "src", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "// allow for concatenation of arrays?", "if", "(", "typeof", "src", "[", "id", "]", "===", "'object'", "&&", "!", "(", "src", "[", "id", "]", "instanceof", "Array", ")", "&&", "(", "typeof", "dst", "[", "id", "]", "===", "'object'", "||", "typeof", "dst", "[", "id", "]", "===", "'function'", ")", ")", "{", "Insert", "(", "dst", "[", "id", "]", ",", "src", "[", "id", "]", ")", "}", "else", "{", "dst", "[", "id", "]", "=", "src", "[", "id", "]", "}", "}", "}", "return", "dst", ";", "}" ]
Insert one objects into another
[ "Insert", "one", "objects", "into", "another" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L574-L582
17,437
mathjax/MathJax-node
lib/main.js
StartMathJax
function StartMathJax() { serverState = STATE.STARTED; var script = document.createElement("script"); script.src = MathJaxPath; script.onerror = function () {AddError("Can't load MathJax.js from "+MathJaxPath)}; document.head.appendChild(script); }
javascript
function StartMathJax() { serverState = STATE.STARTED; var script = document.createElement("script"); script.src = MathJaxPath; script.onerror = function () {AddError("Can't load MathJax.js from "+MathJaxPath)}; document.head.appendChild(script); }
[ "function", "StartMathJax", "(", ")", "{", "serverState", "=", "STATE", ".", "STARTED", ";", "var", "script", "=", "document", ".", "createElement", "(", "\"script\"", ")", ";", "script", ".", "src", "=", "MathJaxPath", ";", "script", ".", "onerror", "=", "function", "(", ")", "{", "AddError", "(", "\"Can't load MathJax.js from \"", "+", "MathJaxPath", ")", "}", ";", "document", ".", "head", ".", "appendChild", "(", "script", ")", ";", "}" ]
Load MathJax into the DOM
[ "Load", "MathJax", "into", "the", "DOM" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L587-L593
17,438
mathjax/MathJax-node
lib/main.js
AddError
function AddError(message,nopush) { if (displayErrors) console.error(message); if (!nopush) errors.push(message); }
javascript
function AddError(message,nopush) { if (displayErrors) console.error(message); if (!nopush) errors.push(message); }
[ "function", "AddError", "(", "message", ",", "nopush", ")", "{", "if", "(", "displayErrors", ")", "console", ".", "error", "(", "message", ")", ";", "if", "(", "!", "nopush", ")", "errors", ".", "push", "(", "message", ")", ";", "}" ]
Add an error to the error list and display it on the console
[ "Add", "an", "error", "to", "the", "error", "list", "and", "display", "it", "on", "the", "console" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L608-L611
17,439
mathjax/MathJax-node
lib/main.js
GetSpeech
function GetSpeech(result) { if (!data.speakText) return; result.speakText = "Equation"; if (data.format !== "MathML") result.speakText = data.math; else { var jax = MathJax.Hub.getAllJax()[0]; if (jax.root.alttext) result.speakText = jax.root.alttext; } }
javascript
function GetSpeech(result) { if (!data.speakText) return; result.speakText = "Equation"; if (data.format !== "MathML") result.speakText = data.math; else { var jax = MathJax.Hub.getAllJax()[0]; if (jax.root.alttext) result.speakText = jax.root.alttext; } }
[ "function", "GetSpeech", "(", "result", ")", "{", "if", "(", "!", "data", ".", "speakText", ")", "return", ";", "result", ".", "speakText", "=", "\"Equation\"", ";", "if", "(", "data", ".", "format", "!==", "\"MathML\"", ")", "result", ".", "speakText", "=", "data", ".", "math", ";", "else", "{", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getAllJax", "(", ")", "[", "0", "]", ";", "if", "(", "jax", ".", "root", ".", "alttext", ")", "result", ".", "speakText", "=", "jax", ".", "root", ".", "alttext", ";", "}", "}" ]
Creates speech string and updates the MathML to include it, if needed
[ "Creates", "speech", "string", "and", "updates", "the", "MathML", "to", "include", "it", "if", "needed" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L643-L651
17,440
mathjax/MathJax-node
lib/main.js
GetHTML
function GetHTML(result) { if (data.css) result.css = CHTMLSTYLES; if (!data.html && !data.htmlNode) return; var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return; var script = jax.SourceElement(), html = script.previousSibling; // add speech text if there isn't one if (data.speakText){ var labelTarget = html.querySelector('.mjx-math'); for (child of labelTarget.childNodes) child.setAttribute("aria-hidden",true); if (!labelTarget.getAttribute("aria-label")){ labelTarget.setAttribute("aria-label",result.speakText); } } // remove automatically generated IDs var ids = html.querySelectorAll('[id^="MJXc-Node-"]'); for (var i = 0; i < ids.length; i++){ ids[i].removeAttribute("id"); } // remove extreneous frame element var frame = html.querySelector('[id^="MathJax-Element-"]'); if (frame){ // in display-mode, the frame is inside the display-style wrapper html.insertBefore(frame.firstChild, frame); html.removeChild(frame); } else{ // otherwise (inline-mode) the frame is the root element html.removeAttribute("id"); } if (data.html) result.html = html.outerHTML; if (data.htmlNode) result.htmlNode = html; }
javascript
function GetHTML(result) { if (data.css) result.css = CHTMLSTYLES; if (!data.html && !data.htmlNode) return; var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return; var script = jax.SourceElement(), html = script.previousSibling; // add speech text if there isn't one if (data.speakText){ var labelTarget = html.querySelector('.mjx-math'); for (child of labelTarget.childNodes) child.setAttribute("aria-hidden",true); if (!labelTarget.getAttribute("aria-label")){ labelTarget.setAttribute("aria-label",result.speakText); } } // remove automatically generated IDs var ids = html.querySelectorAll('[id^="MJXc-Node-"]'); for (var i = 0; i < ids.length; i++){ ids[i].removeAttribute("id"); } // remove extreneous frame element var frame = html.querySelector('[id^="MathJax-Element-"]'); if (frame){ // in display-mode, the frame is inside the display-style wrapper html.insertBefore(frame.firstChild, frame); html.removeChild(frame); } else{ // otherwise (inline-mode) the frame is the root element html.removeAttribute("id"); } if (data.html) result.html = html.outerHTML; if (data.htmlNode) result.htmlNode = html; }
[ "function", "GetHTML", "(", "result", ")", "{", "if", "(", "data", ".", "css", ")", "result", ".", "css", "=", "CHTMLSTYLES", ";", "if", "(", "!", "data", ".", "html", "&&", "!", "data", ".", "htmlNode", ")", "return", ";", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getAllJax", "(", ")", "[", "0", "]", ";", "if", "(", "!", "jax", ")", "return", ";", "var", "script", "=", "jax", ".", "SourceElement", "(", ")", ",", "html", "=", "script", ".", "previousSibling", ";", "// add speech text if there isn't one", "if", "(", "data", ".", "speakText", ")", "{", "var", "labelTarget", "=", "html", ".", "querySelector", "(", "'.mjx-math'", ")", ";", "for", "(", "child", "of", "labelTarget", ".", "childNodes", ")", "child", ".", "setAttribute", "(", "\"aria-hidden\"", ",", "true", ")", ";", "if", "(", "!", "labelTarget", ".", "getAttribute", "(", "\"aria-label\"", ")", ")", "{", "labelTarget", ".", "setAttribute", "(", "\"aria-label\"", ",", "result", ".", "speakText", ")", ";", "}", "}", "// remove automatically generated IDs", "var", "ids", "=", "html", ".", "querySelectorAll", "(", "'[id^=\"MJXc-Node-\"]'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "ids", "[", "i", "]", ".", "removeAttribute", "(", "\"id\"", ")", ";", "}", "// remove extreneous frame element", "var", "frame", "=", "html", ".", "querySelector", "(", "'[id^=\"MathJax-Element-\"]'", ")", ";", "if", "(", "frame", ")", "{", "// in display-mode, the frame is inside the display-style wrapper", "html", ".", "insertBefore", "(", "frame", ".", "firstChild", ",", "frame", ")", ";", "html", ".", "removeChild", "(", "frame", ")", ";", "}", "else", "{", "// otherwise (inline-mode) the frame is the root element", "html", ".", "removeAttribute", "(", "\"id\"", ")", ";", "}", "if", "(", "data", ".", "html", ")", "result", ".", "html", "=", "html", ".", "outerHTML", ";", "if", "(", "data", ".", "htmlNode", ")", "result", ".", "htmlNode", "=", "html", ";", "}" ]
Create HTML and CSS output, if requested
[ "Create", "HTML", "and", "CSS", "output", "if", "requested" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L656-L688
17,441
mathjax/MathJax-node
lib/main.js
GetSVG
function GetSVG(result) { if (!data.svg && !data.svgNode) return; var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return; var script = jax.SourceElement(), svg = script.previousSibling.getElementsByTagName("svg")[0]; svg.setAttribute("xmlns","http://www.w3.org/2000/svg"); // // Add the speech text and mark the SVG appropriately // if (data.speakText){ for (var i=0, m=svg.childNodes.length; i < m; i++) svg.childNodes[i].setAttribute("aria-hidden",true); // Note: if aria-label exists, getSpeech preserved it in speakText // remove aria-label since labelled-by title is preferred svg.removeAttribute("aria-label"); ID++; var id = "MathJax-SVG-"+ID+"-Title"; svg.setAttribute("aria-labelledby",id); var node = MathJax.HTML.Element("title",{id:id},[result.speakText]); svg.insertBefore(node,svg.firstChild); } if (data.svg){ // // SVG data is modified to add linebreaks for readability, // and to put back the xlink namespace that is removed in HTML5 // var svgdata = svg.outerHTML.replace(/><([^/])/g,">\n<$1") .replace(/(<\/[a-z]*>)(?=<\/)/g,"$1\n") .replace(/(<(?:use|image) [^>]*)(href=)/g,' $1xlink:$2'); // // Add the requested data to the results // result.svg = svgdata; } if (data.svgNode) result.svgNode = svg; result.width = svg.getAttribute("width"); result.height = svg.getAttribute("height"); result.style = svg.style.cssText; }
javascript
function GetSVG(result) { if (!data.svg && !data.svgNode) return; var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return; var script = jax.SourceElement(), svg = script.previousSibling.getElementsByTagName("svg")[0]; svg.setAttribute("xmlns","http://www.w3.org/2000/svg"); // // Add the speech text and mark the SVG appropriately // if (data.speakText){ for (var i=0, m=svg.childNodes.length; i < m; i++) svg.childNodes[i].setAttribute("aria-hidden",true); // Note: if aria-label exists, getSpeech preserved it in speakText // remove aria-label since labelled-by title is preferred svg.removeAttribute("aria-label"); ID++; var id = "MathJax-SVG-"+ID+"-Title"; svg.setAttribute("aria-labelledby",id); var node = MathJax.HTML.Element("title",{id:id},[result.speakText]); svg.insertBefore(node,svg.firstChild); } if (data.svg){ // // SVG data is modified to add linebreaks for readability, // and to put back the xlink namespace that is removed in HTML5 // var svgdata = svg.outerHTML.replace(/><([^/])/g,">\n<$1") .replace(/(<\/[a-z]*>)(?=<\/)/g,"$1\n") .replace(/(<(?:use|image) [^>]*)(href=)/g,' $1xlink:$2'); // // Add the requested data to the results // result.svg = svgdata; } if (data.svgNode) result.svgNode = svg; result.width = svg.getAttribute("width"); result.height = svg.getAttribute("height"); result.style = svg.style.cssText; }
[ "function", "GetSVG", "(", "result", ")", "{", "if", "(", "!", "data", ".", "svg", "&&", "!", "data", ".", "svgNode", ")", "return", ";", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getAllJax", "(", ")", "[", "0", "]", ";", "if", "(", "!", "jax", ")", "return", ";", "var", "script", "=", "jax", ".", "SourceElement", "(", ")", ",", "svg", "=", "script", ".", "previousSibling", ".", "getElementsByTagName", "(", "\"svg\"", ")", "[", "0", "]", ";", "svg", ".", "setAttribute", "(", "\"xmlns\"", ",", "\"http://www.w3.org/2000/svg\"", ")", ";", "//", "// Add the speech text and mark the SVG appropriately", "//", "if", "(", "data", ".", "speakText", ")", "{", "for", "(", "var", "i", "=", "0", ",", "m", "=", "svg", ".", "childNodes", ".", "length", ";", "i", "<", "m", ";", "i", "++", ")", "svg", ".", "childNodes", "[", "i", "]", ".", "setAttribute", "(", "\"aria-hidden\"", ",", "true", ")", ";", "// Note: if aria-label exists, getSpeech preserved it in speakText", "// remove aria-label since labelled-by title is preferred", "svg", ".", "removeAttribute", "(", "\"aria-label\"", ")", ";", "ID", "++", ";", "var", "id", "=", "\"MathJax-SVG-\"", "+", "ID", "+", "\"-Title\"", ";", "svg", ".", "setAttribute", "(", "\"aria-labelledby\"", ",", "id", ")", ";", "var", "node", "=", "MathJax", ".", "HTML", ".", "Element", "(", "\"title\"", ",", "{", "id", ":", "id", "}", ",", "[", "result", ".", "speakText", "]", ")", ";", "svg", ".", "insertBefore", "(", "node", ",", "svg", ".", "firstChild", ")", ";", "}", "if", "(", "data", ".", "svg", ")", "{", "//", "// SVG data is modified to add linebreaks for readability,", "// and to put back the xlink namespace that is removed in HTML5", "//", "var", "svgdata", "=", "svg", ".", "outerHTML", ".", "replace", "(", "/", "><([^/])", "/", "g", ",", "\">\\n<$1\"", ")", ".", "replace", "(", "/", "(<\\/[a-z]*>)(?=<\\/)", "/", "g", ",", "\"$1\\n\"", ")", ".", "replace", "(", "/", "(<(?:use|image) [^>]*)(href=)", "/", "g", ",", "' $1xlink:$2'", ")", ";", "//", "// Add the requested data to the results", "//", "result", ".", "svg", "=", "svgdata", ";", "}", "if", "(", "data", ".", "svgNode", ")", "result", ".", "svgNode", "=", "svg", ";", "result", ".", "width", "=", "svg", ".", "getAttribute", "(", "\"width\"", ")", ";", "result", ".", "height", "=", "svg", ".", "getAttribute", "(", "\"height\"", ")", ";", "result", ".", "style", "=", "svg", ".", "style", ".", "cssText", ";", "}" ]
Create SVG output, if requested
[ "Create", "SVG", "output", "if", "requested" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L693-L733
17,442
mathjax/MathJax-node
lib/main.js
StartQueue
function StartQueue() { data = callback = originalData = null; // clear existing equation, if any errors = sErrors; sErrors = []; // clear any errors if (!queue.length) return; // return if nothing to do serverState = STATE.BUSY; var result = {}, $$ = window.Array; // // Get the math data and callback // and set the content with the proper script type // var item = queue.shift(); data = item[0]; callback = item[1]; originalData = item[2]; content.innerHTML = ""; MathJax.HTML.addElement(content,"script",{type: "math/"+TYPES[data.format]},[data.math]); html.setAttribute("xmlns:"+data.xmlns,"http://www.w3.org/1998/Math/MathML"); // // Set the SVG and TeX parameters // according to the requested data // var CHTML = MathJax.OutputJax.CommonHTML, SVG = MathJax.OutputJax.SVG, TEX = MathJax.InputJax.TeX, HUB = MathJax.Hub; SVG.defaultEx = CHTML.defaultEx = data.ex; SVG.defaultWidth = CHTMLdefaultWidth = data.width * data.ex; SVG.config.linebreaks.automatic = CHTML.config.linebreaks.automatic = data.linebreaks; SVG.config.linebreaks.width = CHTML.config.linebreaks.width = data.width * data.ex; SVG.config.useFontCache = data.useFontCache; SVG.config.useGlobalCache = data.useGlobalCache; TEX.config.equationNumbers.autoNumber = data.equationNumbers; // // Set the state from data.state or clear it // GetState(data.state); // // Get the renderer to use // var renderer = ( (data.html || data.htmlNode || data.css) ? "CommonHTML" : (data.svg || data.svgNode) ? "SVG" : "None" ); // // Set up a timeout timer to restart MathJax if it runs too long, // Then push the Typeset call, the MathML, speech, and SVG calls, // and our TypesetDone routine // timer = setTimeout(RestartMathJax,data.timeout); HUB.Queue( $$(SetRenderer,renderer), $$("Process",HUB), $$(TypesetDone,result), $$(GetSpeech,result), $$(GetMML,result), $$(GetHTML,result), $$(RerenderSVG,result), $$(GetSVG,result), $$(ReturnResult,result) ); }
javascript
function StartQueue() { data = callback = originalData = null; // clear existing equation, if any errors = sErrors; sErrors = []; // clear any errors if (!queue.length) return; // return if nothing to do serverState = STATE.BUSY; var result = {}, $$ = window.Array; // // Get the math data and callback // and set the content with the proper script type // var item = queue.shift(); data = item[0]; callback = item[1]; originalData = item[2]; content.innerHTML = ""; MathJax.HTML.addElement(content,"script",{type: "math/"+TYPES[data.format]},[data.math]); html.setAttribute("xmlns:"+data.xmlns,"http://www.w3.org/1998/Math/MathML"); // // Set the SVG and TeX parameters // according to the requested data // var CHTML = MathJax.OutputJax.CommonHTML, SVG = MathJax.OutputJax.SVG, TEX = MathJax.InputJax.TeX, HUB = MathJax.Hub; SVG.defaultEx = CHTML.defaultEx = data.ex; SVG.defaultWidth = CHTMLdefaultWidth = data.width * data.ex; SVG.config.linebreaks.automatic = CHTML.config.linebreaks.automatic = data.linebreaks; SVG.config.linebreaks.width = CHTML.config.linebreaks.width = data.width * data.ex; SVG.config.useFontCache = data.useFontCache; SVG.config.useGlobalCache = data.useGlobalCache; TEX.config.equationNumbers.autoNumber = data.equationNumbers; // // Set the state from data.state or clear it // GetState(data.state); // // Get the renderer to use // var renderer = ( (data.html || data.htmlNode || data.css) ? "CommonHTML" : (data.svg || data.svgNode) ? "SVG" : "None" ); // // Set up a timeout timer to restart MathJax if it runs too long, // Then push the Typeset call, the MathML, speech, and SVG calls, // and our TypesetDone routine // timer = setTimeout(RestartMathJax,data.timeout); HUB.Queue( $$(SetRenderer,renderer), $$("Process",HUB), $$(TypesetDone,result), $$(GetSpeech,result), $$(GetMML,result), $$(GetHTML,result), $$(RerenderSVG,result), $$(GetSVG,result), $$(ReturnResult,result) ); }
[ "function", "StartQueue", "(", ")", "{", "data", "=", "callback", "=", "originalData", "=", "null", ";", "// clear existing equation, if any", "errors", "=", "sErrors", ";", "sErrors", "=", "[", "]", ";", "// clear any errors", "if", "(", "!", "queue", ".", "length", ")", "return", ";", "// return if nothing to do", "serverState", "=", "STATE", ".", "BUSY", ";", "var", "result", "=", "{", "}", ",", "$$", "=", "window", ".", "Array", ";", "//", "// Get the math data and callback", "// and set the content with the proper script type", "//", "var", "item", "=", "queue", ".", "shift", "(", ")", ";", "data", "=", "item", "[", "0", "]", ";", "callback", "=", "item", "[", "1", "]", ";", "originalData", "=", "item", "[", "2", "]", ";", "content", ".", "innerHTML", "=", "\"\"", ";", "MathJax", ".", "HTML", ".", "addElement", "(", "content", ",", "\"script\"", ",", "{", "type", ":", "\"math/\"", "+", "TYPES", "[", "data", ".", "format", "]", "}", ",", "[", "data", ".", "math", "]", ")", ";", "html", ".", "setAttribute", "(", "\"xmlns:\"", "+", "data", ".", "xmlns", ",", "\"http://www.w3.org/1998/Math/MathML\"", ")", ";", "//", "// Set the SVG and TeX parameters", "// according to the requested data", "//", "var", "CHTML", "=", "MathJax", ".", "OutputJax", ".", "CommonHTML", ",", "SVG", "=", "MathJax", ".", "OutputJax", ".", "SVG", ",", "TEX", "=", "MathJax", ".", "InputJax", ".", "TeX", ",", "HUB", "=", "MathJax", ".", "Hub", ";", "SVG", ".", "defaultEx", "=", "CHTML", ".", "defaultEx", "=", "data", ".", "ex", ";", "SVG", ".", "defaultWidth", "=", "CHTMLdefaultWidth", "=", "data", ".", "width", "*", "data", ".", "ex", ";", "SVG", ".", "config", ".", "linebreaks", ".", "automatic", "=", "CHTML", ".", "config", ".", "linebreaks", ".", "automatic", "=", "data", ".", "linebreaks", ";", "SVG", ".", "config", ".", "linebreaks", ".", "width", "=", "CHTML", ".", "config", ".", "linebreaks", ".", "width", "=", "data", ".", "width", "*", "data", ".", "ex", ";", "SVG", ".", "config", ".", "useFontCache", "=", "data", ".", "useFontCache", ";", "SVG", ".", "config", ".", "useGlobalCache", "=", "data", ".", "useGlobalCache", ";", "TEX", ".", "config", ".", "equationNumbers", ".", "autoNumber", "=", "data", ".", "equationNumbers", ";", "//", "// Set the state from data.state or clear it", "//", "GetState", "(", "data", ".", "state", ")", ";", "//", "// Get the renderer to use", "//", "var", "renderer", "=", "(", "(", "data", ".", "html", "||", "data", ".", "htmlNode", "||", "data", ".", "css", ")", "?", "\"CommonHTML\"", ":", "(", "data", ".", "svg", "||", "data", ".", "svgNode", ")", "?", "\"SVG\"", ":", "\"None\"", ")", ";", "//", "// Set up a timeout timer to restart MathJax if it runs too long,", "// Then push the Typeset call, the MathML, speech, and SVG calls,", "// and our TypesetDone routine", "//", "timer", "=", "setTimeout", "(", "RestartMathJax", ",", "data", ".", "timeout", ")", ";", "HUB", ".", "Queue", "(", "$$", "(", "SetRenderer", ",", "renderer", ")", ",", "$$", "(", "\"Process\"", ",", "HUB", ")", ",", "$$", "(", "TypesetDone", ",", "result", ")", ",", "$$", "(", "GetSpeech", ",", "result", ")", ",", "$$", "(", "GetMML", ",", "result", ")", ",", "$$", "(", "GetHTML", ",", "result", ")", ",", "$$", "(", "RerenderSVG", ",", "result", ")", ",", "$$", "(", "GetSVG", ",", "result", ")", ",", "$$", "(", "ReturnResult", ",", "result", ")", ")", ";", "}" ]
Start typesetting the queued expressions
[ "Start", "typesetting", "the", "queued", "expressions" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L740-L805
17,443
mathjax/MathJax-node
lib/main.js
GetState
function GetState(state) { var SVG = MathJax.OutputJax.SVG, TEX = MathJax.InputJax.TeX, MML = MathJax.ElementJax.mml, AMS = MathJax.Extension["TeX/AMSmath"], HUB = MathJax.Hub, HTML = MathJax.HTML, GLYPH = (SVG.BBOX||{}).GLYPH; if (state && state.AMS) { AMS.startNumber = state.AMS.startNumber; AMS.labels = state.AMS.labels; AMS.IDs = state.AMS.IDs; MML.SUPER.ID = state.mmlID; GLYPH.glyphs = state.glyphs; GLYPH.defs = state.defs; GLYPH.n = state.n; ID = state.ID; } else { if (state) {state.AMS = {}} if (SVG.resetGlyphs) SVG.resetGlyphs(true); if (data.useGlobalCache) { state.glyphs = {}; state.defs = HTML.Element("defs"); state.n = 0; } if (TEX.resetEquationNumbers) TEX.resetEquationNumbers(); MML.SUPER.ID = ID = 0; MathJax.OutputJax.CommonHTML.ID = 0; } }
javascript
function GetState(state) { var SVG = MathJax.OutputJax.SVG, TEX = MathJax.InputJax.TeX, MML = MathJax.ElementJax.mml, AMS = MathJax.Extension["TeX/AMSmath"], HUB = MathJax.Hub, HTML = MathJax.HTML, GLYPH = (SVG.BBOX||{}).GLYPH; if (state && state.AMS) { AMS.startNumber = state.AMS.startNumber; AMS.labels = state.AMS.labels; AMS.IDs = state.AMS.IDs; MML.SUPER.ID = state.mmlID; GLYPH.glyphs = state.glyphs; GLYPH.defs = state.defs; GLYPH.n = state.n; ID = state.ID; } else { if (state) {state.AMS = {}} if (SVG.resetGlyphs) SVG.resetGlyphs(true); if (data.useGlobalCache) { state.glyphs = {}; state.defs = HTML.Element("defs"); state.n = 0; } if (TEX.resetEquationNumbers) TEX.resetEquationNumbers(); MML.SUPER.ID = ID = 0; MathJax.OutputJax.CommonHTML.ID = 0; } }
[ "function", "GetState", "(", "state", ")", "{", "var", "SVG", "=", "MathJax", ".", "OutputJax", ".", "SVG", ",", "TEX", "=", "MathJax", ".", "InputJax", ".", "TeX", ",", "MML", "=", "MathJax", ".", "ElementJax", ".", "mml", ",", "AMS", "=", "MathJax", ".", "Extension", "[", "\"TeX/AMSmath\"", "]", ",", "HUB", "=", "MathJax", ".", "Hub", ",", "HTML", "=", "MathJax", ".", "HTML", ",", "GLYPH", "=", "(", "SVG", ".", "BBOX", "||", "{", "}", ")", ".", "GLYPH", ";", "if", "(", "state", "&&", "state", ".", "AMS", ")", "{", "AMS", ".", "startNumber", "=", "state", ".", "AMS", ".", "startNumber", ";", "AMS", ".", "labels", "=", "state", ".", "AMS", ".", "labels", ";", "AMS", ".", "IDs", "=", "state", ".", "AMS", ".", "IDs", ";", "MML", ".", "SUPER", ".", "ID", "=", "state", ".", "mmlID", ";", "GLYPH", ".", "glyphs", "=", "state", ".", "glyphs", ";", "GLYPH", ".", "defs", "=", "state", ".", "defs", ";", "GLYPH", ".", "n", "=", "state", ".", "n", ";", "ID", "=", "state", ".", "ID", ";", "}", "else", "{", "if", "(", "state", ")", "{", "state", ".", "AMS", "=", "{", "}", "}", "if", "(", "SVG", ".", "resetGlyphs", ")", "SVG", ".", "resetGlyphs", "(", "true", ")", ";", "if", "(", "data", ".", "useGlobalCache", ")", "{", "state", ".", "glyphs", "=", "{", "}", ";", "state", ".", "defs", "=", "HTML", ".", "Element", "(", "\"defs\"", ")", ";", "state", ".", "n", "=", "0", ";", "}", "if", "(", "TEX", ".", "resetEquationNumbers", ")", "TEX", ".", "resetEquationNumbers", "(", ")", ";", "MML", ".", "SUPER", ".", "ID", "=", "ID", "=", "0", ";", "MathJax", ".", "OutputJax", ".", "CommonHTML", ".", "ID", "=", "0", ";", "}", "}" ]
Update the MathJax values from the state, or clear them if there is no state.
[ "Update", "the", "MathJax", "values", "from", "the", "state", "or", "clear", "them", "if", "there", "is", "no", "state", "." ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L811-L840
17,444
mathjax/MathJax-node
lib/main.js
TypesetDone
function TypesetDone(result) { if (timer) {clearTimeout(timer); timer = null} html.removeAttribute("xmlns:"+data.xmlns); }
javascript
function TypesetDone(result) { if (timer) {clearTimeout(timer); timer = null} html.removeAttribute("xmlns:"+data.xmlns); }
[ "function", "TypesetDone", "(", "result", ")", "{", "if", "(", "timer", ")", "{", "clearTimeout", "(", "timer", ")", ";", "timer", "=", "null", "}", "html", ".", "removeAttribute", "(", "\"xmlns:\"", "+", "data", ".", "xmlns", ")", ";", "}" ]
When the expression is typeset, clear the timeout timer, if any, and update the MathJax state,
[ "When", "the", "expression", "is", "typeset", "clear", "the", "timeout", "timer", "if", "any", "and", "update", "the", "MathJax", "state" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L847-L850
17,445
mathjax/MathJax-node
lib/main.js
ReturnResult
function ReturnResult(result) { if (errors.length) { result.errors = errors; } var state = data.state; if (state) { var AMS = MathJax.Extension["TeX/AMSmath"]; var GLYPH = (MathJax.OutputJax.SVG||{}).BBOX.GLYPH; state.AMS.startNumber = AMS.startNumber; state.AMS.labels = AMS.labels; state.AMS.IDs = AMS.IDs; state.mmlID = MathJax.ElementJax.mml.SUPER.ID; state.glyphs = GLYPH.glyphs; state.defs = GLYPH.defs; state.n = GLYPH.n; state.ID = ID; } serverState = STATE.READY; callback(result, originalData); if (serverState === STATE.READY) StartQueue(); }
javascript
function ReturnResult(result) { if (errors.length) { result.errors = errors; } var state = data.state; if (state) { var AMS = MathJax.Extension["TeX/AMSmath"]; var GLYPH = (MathJax.OutputJax.SVG||{}).BBOX.GLYPH; state.AMS.startNumber = AMS.startNumber; state.AMS.labels = AMS.labels; state.AMS.IDs = AMS.IDs; state.mmlID = MathJax.ElementJax.mml.SUPER.ID; state.glyphs = GLYPH.glyphs; state.defs = GLYPH.defs; state.n = GLYPH.n; state.ID = ID; } serverState = STATE.READY; callback(result, originalData); if (serverState === STATE.READY) StartQueue(); }
[ "function", "ReturnResult", "(", "result", ")", "{", "if", "(", "errors", ".", "length", ")", "{", "result", ".", "errors", "=", "errors", ";", "}", "var", "state", "=", "data", ".", "state", ";", "if", "(", "state", ")", "{", "var", "AMS", "=", "MathJax", ".", "Extension", "[", "\"TeX/AMSmath\"", "]", ";", "var", "GLYPH", "=", "(", "MathJax", ".", "OutputJax", ".", "SVG", "||", "{", "}", ")", ".", "BBOX", ".", "GLYPH", ";", "state", ".", "AMS", ".", "startNumber", "=", "AMS", ".", "startNumber", ";", "state", ".", "AMS", ".", "labels", "=", "AMS", ".", "labels", ";", "state", ".", "AMS", ".", "IDs", "=", "AMS", ".", "IDs", ";", "state", ".", "mmlID", "=", "MathJax", ".", "ElementJax", ".", "mml", ".", "SUPER", ".", "ID", ";", "state", ".", "glyphs", "=", "GLYPH", ".", "glyphs", ";", "state", ".", "defs", "=", "GLYPH", ".", "defs", ";", "state", ".", "n", "=", "GLYPH", ".", "n", ";", "state", ".", "ID", "=", "ID", ";", "}", "serverState", "=", "STATE", ".", "READY", ";", "callback", "(", "result", ",", "originalData", ")", ";", "if", "(", "serverState", "===", "STATE", ".", "READY", ")", "StartQueue", "(", ")", ";", "}" ]
Return the result object, and do the next queued expression
[ "Return", "the", "result", "object", "and", "do", "the", "next", "queued", "expression" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L856-L876
17,446
mathjax/MathJax-node
lib/main.js
function (data, callback) { if (!callback || typeof(callback) !== "function") { if (displayErrors) console.error("Missing callback"); return; } var options = {}; for (var id in defaults) {if (defaults.hasOwnProperty(id)) { options[id] = (data.hasOwnProperty(id) ? data[id]: defaults[id]); }} if (data.state) {options.state = data.state} if (!TYPES[options.format]) {ReportError("Unknown format: "+options.format,callback); return} queue.push([options,callback,Object.assign({},data)]); if (serverState == STATE.STOPPED) {RestartMathJax()} if (serverState == STATE.READY) StartQueue(); }
javascript
function (data, callback) { if (!callback || typeof(callback) !== "function") { if (displayErrors) console.error("Missing callback"); return; } var options = {}; for (var id in defaults) {if (defaults.hasOwnProperty(id)) { options[id] = (data.hasOwnProperty(id) ? data[id]: defaults[id]); }} if (data.state) {options.state = data.state} if (!TYPES[options.format]) {ReportError("Unknown format: "+options.format,callback); return} queue.push([options,callback,Object.assign({},data)]); if (serverState == STATE.STOPPED) {RestartMathJax()} if (serverState == STATE.READY) StartQueue(); }
[ "function", "(", "data", ",", "callback", ")", "{", "if", "(", "!", "callback", "||", "typeof", "(", "callback", ")", "!==", "\"function\"", ")", "{", "if", "(", "displayErrors", ")", "console", ".", "error", "(", "\"Missing callback\"", ")", ";", "return", ";", "}", "var", "options", "=", "{", "}", ";", "for", "(", "var", "id", "in", "defaults", ")", "{", "if", "(", "defaults", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "options", "[", "id", "]", "=", "(", "data", ".", "hasOwnProperty", "(", "id", ")", "?", "data", "[", "id", "]", ":", "defaults", "[", "id", "]", ")", ";", "}", "}", "if", "(", "data", ".", "state", ")", "{", "options", ".", "state", "=", "data", ".", "state", "}", "if", "(", "!", "TYPES", "[", "options", ".", "format", "]", ")", "{", "ReportError", "(", "\"Unknown format: \"", "+", "options", ".", "format", ",", "callback", ")", ";", "return", "}", "queue", ".", "push", "(", "[", "options", ",", "callback", ",", "Object", ".", "assign", "(", "{", "}", ",", "data", ")", "]", ")", ";", "if", "(", "serverState", "==", "STATE", ".", "STOPPED", ")", "{", "RestartMathJax", "(", ")", "}", "if", "(", "serverState", "==", "STATE", ".", "READY", ")", "StartQueue", "(", ")", ";", "}" ]
The API call to typeset an equation %%% cache results? %%% check types and values of parameters callback API for compatibility with MathJax
[ "The", "API", "call", "to", "typeset", "an", "equation", "%%%", "cache", "results?", "%%%", "check", "types", "and", "values", "of", "parameters", "callback", "API", "for", "compatibility", "with", "MathJax" ]
c7e5bf3baf4af820e68be58cb93ade38b8e19cbe
https://github.com/mathjax/MathJax-node/blob/c7e5bf3baf4af820e68be58cb93ade38b8e19cbe/lib/main.js#L926-L940
17,447
messageformat/messageformat
packages/formatters/lib/duration.js
duration
function duration(value) { if (!isFinite(value)) return String(value); var sign = ''; if (value < 0) { sign = '-'; value = Math.abs(value); } else { value = Number(value); } var sec = value % 60; var parts = [Math.round(sec) === sec ? sec : sec.toFixed(3)]; if (value < 60) { parts.unshift(0); // at least one : is required } else { value = Math.round((value - parts[0]) / 60); parts.unshift(value % 60); // minutes if (value >= 60) { value = Math.round((value - parts[0]) / 60); parts.unshift(value); // hours } } var first = parts.shift(); return ( sign + first + ':' + parts .map(function(n) { return n < 10 ? '0' + String(n) : String(n); }) .join(':') ); }
javascript
function duration(value) { if (!isFinite(value)) return String(value); var sign = ''; if (value < 0) { sign = '-'; value = Math.abs(value); } else { value = Number(value); } var sec = value % 60; var parts = [Math.round(sec) === sec ? sec : sec.toFixed(3)]; if (value < 60) { parts.unshift(0); // at least one : is required } else { value = Math.round((value - parts[0]) / 60); parts.unshift(value % 60); // minutes if (value >= 60) { value = Math.round((value - parts[0]) / 60); parts.unshift(value); // hours } } var first = parts.shift(); return ( sign + first + ':' + parts .map(function(n) { return n < 10 ? '0' + String(n) : String(n); }) .join(':') ); }
[ "function", "duration", "(", "value", ")", "{", "if", "(", "!", "isFinite", "(", "value", ")", ")", "return", "String", "(", "value", ")", ";", "var", "sign", "=", "''", ";", "if", "(", "value", "<", "0", ")", "{", "sign", "=", "'-'", ";", "value", "=", "Math", ".", "abs", "(", "value", ")", ";", "}", "else", "{", "value", "=", "Number", "(", "value", ")", ";", "}", "var", "sec", "=", "value", "%", "60", ";", "var", "parts", "=", "[", "Math", ".", "round", "(", "sec", ")", "===", "sec", "?", "sec", ":", "sec", ".", "toFixed", "(", "3", ")", "]", ";", "if", "(", "value", "<", "60", ")", "{", "parts", ".", "unshift", "(", "0", ")", ";", "// at least one : is required", "}", "else", "{", "value", "=", "Math", ".", "round", "(", "(", "value", "-", "parts", "[", "0", "]", ")", "/", "60", ")", ";", "parts", ".", "unshift", "(", "value", "%", "60", ")", ";", "// minutes", "if", "(", "value", ">=", "60", ")", "{", "value", "=", "Math", ".", "round", "(", "(", "value", "-", "parts", "[", "0", "]", ")", "/", "60", ")", ";", "parts", ".", "unshift", "(", "value", ")", ";", "// hours", "}", "}", "var", "first", "=", "parts", ".", "shift", "(", ")", ";", "return", "(", "sign", "+", "first", "+", "':'", "+", "parts", ".", "map", "(", "function", "(", "n", ")", "{", "return", "n", "<", "10", "?", "'0'", "+", "String", "(", "n", ")", ":", "String", "(", "n", ")", ";", "}", ")", ".", "join", "(", "':'", ")", ")", ";", "}" ]
Represent a duration in seconds as a string Input should be a finite number; output will include one or two `:` separators, and match the pattern `hhhh:mm:ss`, possibly with a leading `-` for negative values and a trailing `.sss` part for non-integer input @memberof Formatters @param {number|string} value - A finite number, or its string representation @example var mf = new MessageFormat(); mf.compile('It has been {D, duration}')({ D: 123 }) // 'It has been 2:03' mf.compile('Countdown: {D, duration}')({ D: -151200.42 }) // 'Countdown: -42:00:00.420'
[ "Represent", "a", "duration", "in", "seconds", "as", "a", "string" ]
6378fc35ed774675f4a8849a1348717344e6a13a
https://github.com/messageformat/messageformat/blob/6378fc35ed774675f4a8849a1348717344e6a13a/packages/formatters/lib/duration.js#L20-L52
17,448
letsgetrandy/brototype
brototype.js
Bromise
function Bromise(object, method, args) { this.object = object; this.method = method; this.args = args.length > 1 ? args.slice(1) : []; }
javascript
function Bromise(object, method, args) { this.object = object; this.method = method; this.args = args.length > 1 ? args.slice(1) : []; }
[ "function", "Bromise", "(", "object", ",", "method", ",", "args", ")", "{", "this", ".", "object", "=", "object", ";", "this", ".", "method", "=", "method", ";", "this", ".", "args", "=", "args", ".", "length", ">", "1", "?", "args", ".", "slice", "(", "1", ")", ":", "[", "]", ";", "}" ]
Bromise... it's stronger than a Promise
[ "Bromise", "...", "it", "s", "stronger", "than", "a", "Promise" ]
731b02f614971341e6677adc763cb3efafb64c35
https://github.com/letsgetrandy/brototype/blob/731b02f614971341e6677adc763cb3efafb64c35/brototype.js#L6-L10
17,449
nwjs-community/nw-builder
lib/versions.js
function(downloadUrl, manifestUrl, flavor) { return getManifest(manifestUrl) .then(function(manifest) { return { desiredVersion: manifest.stable.replace('v', ''), downloadUrl: downloadUrl, manifestUrl: manifestUrl, flavor: flavor } }) .then(this.getVersion); }
javascript
function(downloadUrl, manifestUrl, flavor) { return getManifest(manifestUrl) .then(function(manifest) { return { desiredVersion: manifest.stable.replace('v', ''), downloadUrl: downloadUrl, manifestUrl: manifestUrl, flavor: flavor } }) .then(this.getVersion); }
[ "function", "(", "downloadUrl", ",", "manifestUrl", ",", "flavor", ")", "{", "return", "getManifest", "(", "manifestUrl", ")", ".", "then", "(", "function", "(", "manifest", ")", "{", "return", "{", "desiredVersion", ":", "manifest", ".", "stable", ".", "replace", "(", "'v'", ",", "''", ")", ",", "downloadUrl", ":", "downloadUrl", ",", "manifestUrl", ":", "manifestUrl", ",", "flavor", ":", "flavor", "}", "}", ")", ".", "then", "(", "this", ".", "getVersion", ")", ";", "}" ]
Gets the latest stable version @param {string} downloadUrl @param {string} manifestUrl @param {string} flavor @returns {promise} which resolves to a {Version}
[ "Gets", "the", "latest", "stable", "version" ]
d2208f47d374c2eca75de09a14310ccee903abf5
https://github.com/nwjs-community/nw-builder/blob/d2208f47d374c2eca75de09a14310ccee903abf5/lib/versions.js#L152-L163
17,450
gcanti/tcomb
lib/update.js
$apply
function $apply(f, value) { if (process.env.NODE_ENV !== 'production') { assert(isFunction(f), 'Invalid argument f supplied to immutability helper { $apply: f } (expected a function)'); } return f(value); }
javascript
function $apply(f, value) { if (process.env.NODE_ENV !== 'production') { assert(isFunction(f), 'Invalid argument f supplied to immutability helper { $apply: f } (expected a function)'); } return f(value); }
[ "function", "$apply", "(", "f", ",", "value", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "assert", "(", "isFunction", "(", "f", ")", ",", "'Invalid argument f supplied to immutability helper { $apply: f } (expected a function)'", ")", ";", "}", "return", "f", "(", "value", ")", ";", "}" ]
built-in commands
[ "built", "-", "in", "commands" ]
bef7690a072c056a8604efd376fb4c959a407557
https://github.com/gcanti/tcomb/blob/bef7690a072c056a8604efd376fb4c959a407557/lib/update.js#L64-L69
17,451
gcanti/tcomb
lib/list.js
List
function List(value, path) { if (process.env.NODE_ENV === 'production') { if (identity) { return value; // just trust the input if elements must not be hydrated } } if (process.env.NODE_ENV !== 'production') { path = path || [displayName]; assert(isArray(value), function () { return 'Invalid value ' + assert.stringify(value) + ' supplied to ' + path.join('/') + ' (expected an array of ' + typeNameCache + ')'; }); } var idempotent = true; // will remain true if I can reutilise the input var ret = []; // make a temporary copy, will be discarded if idempotent remains true for (var i = 0, len = value.length; i < len; i++ ) { var actual = value[i]; var instance = create(type, actual, ( process.env.NODE_ENV !== 'production' ? path.concat(i + ': ' + typeNameCache) : null )); idempotent = idempotent && ( actual === instance ); ret.push(instance); } if (idempotent) { // implements idempotency ret = value; } if (process.env.NODE_ENV !== 'production') { Object.freeze(ret); } return ret; }
javascript
function List(value, path) { if (process.env.NODE_ENV === 'production') { if (identity) { return value; // just trust the input if elements must not be hydrated } } if (process.env.NODE_ENV !== 'production') { path = path || [displayName]; assert(isArray(value), function () { return 'Invalid value ' + assert.stringify(value) + ' supplied to ' + path.join('/') + ' (expected an array of ' + typeNameCache + ')'; }); } var idempotent = true; // will remain true if I can reutilise the input var ret = []; // make a temporary copy, will be discarded if idempotent remains true for (var i = 0, len = value.length; i < len; i++ ) { var actual = value[i]; var instance = create(type, actual, ( process.env.NODE_ENV !== 'production' ? path.concat(i + ': ' + typeNameCache) : null )); idempotent = idempotent && ( actual === instance ); ret.push(instance); } if (idempotent) { // implements idempotency ret = value; } if (process.env.NODE_ENV !== 'production') { Object.freeze(ret); } return ret; }
[ "function", "List", "(", "value", ",", "path", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "===", "'production'", ")", "{", "if", "(", "identity", ")", "{", "return", "value", ";", "// just trust the input if elements must not be hydrated", "}", "}", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "path", "=", "path", "||", "[", "displayName", "]", ";", "assert", "(", "isArray", "(", "value", ")", ",", "function", "(", ")", "{", "return", "'Invalid value '", "+", "assert", ".", "stringify", "(", "value", ")", "+", "' supplied to '", "+", "path", ".", "join", "(", "'/'", ")", "+", "' (expected an array of '", "+", "typeNameCache", "+", "')'", ";", "}", ")", ";", "}", "var", "idempotent", "=", "true", ";", "// will remain true if I can reutilise the input", "var", "ret", "=", "[", "]", ";", "// make a temporary copy, will be discarded if idempotent remains true", "for", "(", "var", "i", "=", "0", ",", "len", "=", "value", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "actual", "=", "value", "[", "i", "]", ";", "var", "instance", "=", "create", "(", "type", ",", "actual", ",", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "path", ".", "concat", "(", "i", "+", "': '", "+", "typeNameCache", ")", ":", "null", ")", ")", ";", "idempotent", "=", "idempotent", "&&", "(", "actual", "===", "instance", ")", ";", "ret", ".", "push", "(", "instance", ")", ";", "}", "if", "(", "idempotent", ")", "{", "// implements idempotency", "ret", "=", "value", ";", "}", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "Object", ".", "freeze", "(", "ret", ")", ";", "}", "return", "ret", ";", "}" ]
the list is identity iif type is identity
[ "the", "list", "is", "identity", "iif", "type", "is", "identity" ]
bef7690a072c056a8604efd376fb4c959a407557
https://github.com/gcanti/tcomb/blob/bef7690a072c056a8604efd376fb4c959a407557/lib/list.js#L25-L56
17,452
nordnet/cordova-universal-links-plugin
hooks/lib/android/webSiteHook.js
generateWebHook
function generateWebHook(cordovaContext, pluginPreferences) { var projectRoot = cordovaContext.opts.projectRoot; var configXmlHelper = new ConfigXmlHelper(cordovaContext); var packageName = configXmlHelper.getPackageName('android'); var template = readTemplate(projectRoot); // if template was not found - exit if (template == null || template.length == 0) { return; } // generate hook content var linksToInsert = generateLinksSet(projectRoot, packageName, pluginPreferences); var hookContent = template.replace(LINK_PLACEHOLDER, linksToInsert); // save hook saveWebHook(projectRoot, hookContent); }
javascript
function generateWebHook(cordovaContext, pluginPreferences) { var projectRoot = cordovaContext.opts.projectRoot; var configXmlHelper = new ConfigXmlHelper(cordovaContext); var packageName = configXmlHelper.getPackageName('android'); var template = readTemplate(projectRoot); // if template was not found - exit if (template == null || template.length == 0) { return; } // generate hook content var linksToInsert = generateLinksSet(projectRoot, packageName, pluginPreferences); var hookContent = template.replace(LINK_PLACEHOLDER, linksToInsert); // save hook saveWebHook(projectRoot, hookContent); }
[ "function", "generateWebHook", "(", "cordovaContext", ",", "pluginPreferences", ")", "{", "var", "projectRoot", "=", "cordovaContext", ".", "opts", ".", "projectRoot", ";", "var", "configXmlHelper", "=", "new", "ConfigXmlHelper", "(", "cordovaContext", ")", ";", "var", "packageName", "=", "configXmlHelper", ".", "getPackageName", "(", "'android'", ")", ";", "var", "template", "=", "readTemplate", "(", "projectRoot", ")", ";", "// if template was not found - exit", "if", "(", "template", "==", "null", "||", "template", ".", "length", "==", "0", ")", "{", "return", ";", "}", "// generate hook content", "var", "linksToInsert", "=", "generateLinksSet", "(", "projectRoot", ",", "packageName", ",", "pluginPreferences", ")", ";", "var", "hookContent", "=", "template", ".", "replace", "(", "LINK_PLACEHOLDER", ",", "linksToInsert", ")", ";", "// save hook", "saveWebHook", "(", "projectRoot", ",", "hookContent", ")", ";", "}" ]
region Public API Generate website hook for android application. @param {Object} cordovaContext - cordova context object @param {Object} pluginPreferences - plugin preferences from config.xml file; already parsed
[ "region", "Public", "API", "Generate", "website", "hook", "for", "android", "application", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/webSiteHook.js#L31-L48
17,453
nordnet/cordova-universal-links-plugin
hooks/lib/android/webSiteHook.js
readTemplate
function readTemplate(projectRoot) { var filePath = path.join(projectRoot, WEB_HOOK_TPL_FILE_PATH); var tplData = null; try { tplData = fs.readFileSync(filePath, 'utf8'); } catch (err) { console.warn('Template file for android web hook is not found!'); console.warn(err); } return tplData; }
javascript
function readTemplate(projectRoot) { var filePath = path.join(projectRoot, WEB_HOOK_TPL_FILE_PATH); var tplData = null; try { tplData = fs.readFileSync(filePath, 'utf8'); } catch (err) { console.warn('Template file for android web hook is not found!'); console.warn(err); } return tplData; }
[ "function", "readTemplate", "(", "projectRoot", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "projectRoot", ",", "WEB_HOOK_TPL_FILE_PATH", ")", ";", "var", "tplData", "=", "null", ";", "try", "{", "tplData", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "'utf8'", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "warn", "(", "'Template file for android web hook is not found!'", ")", ";", "console", ".", "warn", "(", "err", ")", ";", "}", "return", "tplData", ";", "}" ]
region Public API Read hook teplate from plugin directory. @param {String} projectRoot - absolute path to cordova's project root @return {String} data from the template file
[ "region", "Public", "API", "Read", "hook", "teplate", "from", "plugin", "directory", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/webSiteHook.js#L60-L72
17,454
nordnet/cordova-universal-links-plugin
hooks/lib/android/webSiteHook.js
saveWebHook
function saveWebHook(projectRoot, hookContent) { var filePath = path.join(projectRoot, WEB_HOOK_FILE_PATH); var isSaved = true; // ensure directory exists createDirectoryIfNeeded(path.dirname(filePath)); // write data to file try { fs.writeFileSync(filePath, hookContent, 'utf8'); } catch (err) { console.warn('Failed to create android web hook!'); console.warn(err); isSaved = false; } return isSaved; }
javascript
function saveWebHook(projectRoot, hookContent) { var filePath = path.join(projectRoot, WEB_HOOK_FILE_PATH); var isSaved = true; // ensure directory exists createDirectoryIfNeeded(path.dirname(filePath)); // write data to file try { fs.writeFileSync(filePath, hookContent, 'utf8'); } catch (err) { console.warn('Failed to create android web hook!'); console.warn(err); isSaved = false; } return isSaved; }
[ "function", "saveWebHook", "(", "projectRoot", ",", "hookContent", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "projectRoot", ",", "WEB_HOOK_FILE_PATH", ")", ";", "var", "isSaved", "=", "true", ";", "// ensure directory exists", "createDirectoryIfNeeded", "(", "path", ".", "dirname", "(", "filePath", ")", ")", ";", "// write data to file", "try", "{", "fs", ".", "writeFileSync", "(", "filePath", ",", "hookContent", ",", "'utf8'", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "warn", "(", "'Failed to create android web hook!'", ")", ";", "console", ".", "warn", "(", "err", ")", ";", "isSaved", "=", "false", ";", "}", "return", "isSaved", ";", "}" ]
Save data to website hook file. @param {String} projectRoot - absolute path to project root @param {String} hookContent - data to save @return {boolean} true - if data was saved; otherwise - false;
[ "Save", "data", "to", "website", "hook", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/webSiteHook.js#L130-L147
17,455
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
generateEntitlements
function generateEntitlements(cordovaContext, pluginPreferences) { context = cordovaContext; var currentEntitlements = getEntitlementsFileContent(); var newEntitlements = injectPreferences(currentEntitlements, pluginPreferences); saveContentToEntitlementsFile(newEntitlements); }
javascript
function generateEntitlements(cordovaContext, pluginPreferences) { context = cordovaContext; var currentEntitlements = getEntitlementsFileContent(); var newEntitlements = injectPreferences(currentEntitlements, pluginPreferences); saveContentToEntitlementsFile(newEntitlements); }
[ "function", "generateEntitlements", "(", "cordovaContext", ",", "pluginPreferences", ")", "{", "context", "=", "cordovaContext", ";", "var", "currentEntitlements", "=", "getEntitlementsFileContent", "(", ")", ";", "var", "newEntitlements", "=", "injectPreferences", "(", "currentEntitlements", ",", "pluginPreferences", ")", ";", "saveContentToEntitlementsFile", "(", "newEntitlements", ")", ";", "}" ]
region Public API Generate entitlements file content. @param {Object} cordovaContext - cordova context object @param {Object} pluginPreferences - plugin preferences from config.xml; already parsed
[ "region", "Public", "API", "Generate", "entitlements", "file", "content", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L32-L39
17,456
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
saveContentToEntitlementsFile
function saveContentToEntitlementsFile(content) { var plistContent = plist.build(content); var filePath = pathToEntitlementsFile(); // ensure that file exists mkpath.sync(path.dirname(filePath)); // save it's content fs.writeFileSync(filePath, plistContent, 'utf8'); }
javascript
function saveContentToEntitlementsFile(content) { var plistContent = plist.build(content); var filePath = pathToEntitlementsFile(); // ensure that file exists mkpath.sync(path.dirname(filePath)); // save it's content fs.writeFileSync(filePath, plistContent, 'utf8'); }
[ "function", "saveContentToEntitlementsFile", "(", "content", ")", "{", "var", "plistContent", "=", "plist", ".", "build", "(", "content", ")", ";", "var", "filePath", "=", "pathToEntitlementsFile", "(", ")", ";", "// ensure that file exists", "mkpath", ".", "sync", "(", "path", ".", "dirname", "(", "filePath", ")", ")", ";", "// save it's content", "fs", ".", "writeFileSync", "(", "filePath", ",", "plistContent", ",", "'utf8'", ")", ";", "}" ]
region Work with entitlements file Save data to entitlements file. @param {Object} content - data to save; JSON object that will be transformed into xml
[ "region", "Work", "with", "entitlements", "file", "Save", "data", "to", "entitlements", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L50-L59
17,457
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
getEntitlementsFileContent
function getEntitlementsFileContent() { var pathToFile = pathToEntitlementsFile(); var content; try { content = fs.readFileSync(pathToFile, 'utf8'); } catch (err) { return defaultEntitlementsFile(); } return plist.parse(content); }
javascript
function getEntitlementsFileContent() { var pathToFile = pathToEntitlementsFile(); var content; try { content = fs.readFileSync(pathToFile, 'utf8'); } catch (err) { return defaultEntitlementsFile(); } return plist.parse(content); }
[ "function", "getEntitlementsFileContent", "(", ")", "{", "var", "pathToFile", "=", "pathToEntitlementsFile", "(", ")", ";", "var", "content", ";", "try", "{", "content", "=", "fs", ".", "readFileSync", "(", "pathToFile", ",", "'utf8'", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "defaultEntitlementsFile", "(", ")", ";", "}", "return", "plist", ".", "parse", "(", "content", ")", ";", "}" ]
Read data from existing entitlements file. If none exist - default value is returned @return {String} entitlements file content
[ "Read", "data", "from", "existing", "entitlements", "file", ".", "If", "none", "exist", "-", "default", "value", "is", "returned" ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L66-L77
17,458
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
injectPreferences
function injectPreferences(currentEntitlements, pluginPreferences) { var newEntitlements = currentEntitlements; var content = generateAssociatedDomainsContent(pluginPreferences); newEntitlements[ASSOCIATED_DOMAINS] = content; return newEntitlements; }
javascript
function injectPreferences(currentEntitlements, pluginPreferences) { var newEntitlements = currentEntitlements; var content = generateAssociatedDomainsContent(pluginPreferences); newEntitlements[ASSOCIATED_DOMAINS] = content; return newEntitlements; }
[ "function", "injectPreferences", "(", "currentEntitlements", ",", "pluginPreferences", ")", "{", "var", "newEntitlements", "=", "currentEntitlements", ";", "var", "content", "=", "generateAssociatedDomainsContent", "(", "pluginPreferences", ")", ";", "newEntitlements", "[", "ASSOCIATED_DOMAINS", "]", "=", "content", ";", "return", "newEntitlements", ";", "}" ]
Inject list of hosts into entitlements file. @param {Object} currentEntitlements - entitlements where to inject preferences @param {Object} pluginPreferences - list of hosts from config.xml @return {Object} new entitlements content
[ "Inject", "list", "of", "hosts", "into", "entitlements", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L95-L102
17,459
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
generateAssociatedDomainsContent
function generateAssociatedDomainsContent(pluginPreferences) { var domainsList = []; // generate list of host links pluginPreferences.hosts.forEach(function(host) { var link = domainsListEntryForHost(host); if (domainsList.indexOf(link) == -1) { domainsList.push(link); } }); return domainsList; }
javascript
function generateAssociatedDomainsContent(pluginPreferences) { var domainsList = []; // generate list of host links pluginPreferences.hosts.forEach(function(host) { var link = domainsListEntryForHost(host); if (domainsList.indexOf(link) == -1) { domainsList.push(link); } }); return domainsList; }
[ "function", "generateAssociatedDomainsContent", "(", "pluginPreferences", ")", "{", "var", "domainsList", "=", "[", "]", ";", "// generate list of host links", "pluginPreferences", ".", "hosts", ".", "forEach", "(", "function", "(", "host", ")", "{", "var", "link", "=", "domainsListEntryForHost", "(", "host", ")", ";", "if", "(", "domainsList", ".", "indexOf", "(", "link", ")", "==", "-", "1", ")", "{", "domainsList", ".", "push", "(", "link", ")", ";", "}", "}", ")", ";", "return", "domainsList", ";", "}" ]
Generate content for associated-domains dictionary in the entitlements file. @param {Object} pluginPreferences - list of hosts from conig.xml @return {Object} associated-domains dictionary content
[ "Generate", "content", "for", "associated", "-", "domains", "dictionary", "in", "the", "entitlements", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L110-L122
17,460
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
pathToEntitlementsFile
function pathToEntitlementsFile() { if (entitlementsFilePath === undefined) { entitlementsFilePath = path.join(getProjectRoot(), 'platforms', 'ios', getProjectName(), 'Resources', getProjectName() + '.entitlements'); } return entitlementsFilePath; }
javascript
function pathToEntitlementsFile() { if (entitlementsFilePath === undefined) { entitlementsFilePath = path.join(getProjectRoot(), 'platforms', 'ios', getProjectName(), 'Resources', getProjectName() + '.entitlements'); } return entitlementsFilePath; }
[ "function", "pathToEntitlementsFile", "(", ")", "{", "if", "(", "entitlementsFilePath", "===", "undefined", ")", "{", "entitlementsFilePath", "=", "path", ".", "join", "(", "getProjectRoot", "(", ")", ",", "'platforms'", ",", "'ios'", ",", "getProjectName", "(", ")", ",", "'Resources'", ",", "getProjectName", "(", ")", "+", "'.entitlements'", ")", ";", "}", "return", "entitlementsFilePath", ";", "}" ]
region Path helper methods Path to entitlements file. @return {String} absolute path to entitlements file
[ "region", "Path", "helper", "methods", "Path", "to", "entitlements", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L143-L149
17,461
nordnet/cordova-universal-links-plugin
hooks/lib/ios/projectEntitlements.js
getProjectName
function getProjectName() { if (projectName === undefined) { var configXmlHelper = new ConfigXmlHelper(context); projectName = configXmlHelper.getProjectName(); } return projectName; }
javascript
function getProjectName() { if (projectName === undefined) { var configXmlHelper = new ConfigXmlHelper(context); projectName = configXmlHelper.getProjectName(); } return projectName; }
[ "function", "getProjectName", "(", ")", "{", "if", "(", "projectName", "===", "undefined", ")", "{", "var", "configXmlHelper", "=", "new", "ConfigXmlHelper", "(", "context", ")", ";", "projectName", "=", "configXmlHelper", ".", "getProjectName", "(", ")", ";", "}", "return", "projectName", ";", "}" ]
Name of the project from config.xml @return {String} project name
[ "Name", "of", "the", "project", "from", "config", ".", "xml" ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/projectEntitlements.js#L165-L172
17,462
nordnet/cordova-universal-links-plugin
hooks/iosBeforePrepareHook.js
run
function run(ctx) { var projectRoot = ctx.opts.projectRoot; var iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios'); var configXmlHelper = new ConfigXmlHelper(ctx); var newProjectName = configXmlHelper.getProjectName(); var oldProjectName = getOldProjectName(iosProjectFilePath); // if name has not changed - do nothing if (oldProjectName.length && oldProjectName === newProjectName) { return; } console.log('Project name has changed. Renaming .entitlements file.'); // if it does - rename it var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements'); var newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements'); try { fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath); } catch (err) { console.warn('Failed to rename .entitlements file.'); console.warn(err); } }
javascript
function run(ctx) { var projectRoot = ctx.opts.projectRoot; var iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios'); var configXmlHelper = new ConfigXmlHelper(ctx); var newProjectName = configXmlHelper.getProjectName(); var oldProjectName = getOldProjectName(iosProjectFilePath); // if name has not changed - do nothing if (oldProjectName.length && oldProjectName === newProjectName) { return; } console.log('Project name has changed. Renaming .entitlements file.'); // if it does - rename it var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements'); var newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements'); try { fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath); } catch (err) { console.warn('Failed to rename .entitlements file.'); console.warn(err); } }
[ "function", "run", "(", "ctx", ")", "{", "var", "projectRoot", "=", "ctx", ".", "opts", ".", "projectRoot", ";", "var", "iosProjectFilePath", "=", "path", ".", "join", "(", "projectRoot", ",", "'platforms'", ",", "'ios'", ")", ";", "var", "configXmlHelper", "=", "new", "ConfigXmlHelper", "(", "ctx", ")", ";", "var", "newProjectName", "=", "configXmlHelper", ".", "getProjectName", "(", ")", ";", "var", "oldProjectName", "=", "getOldProjectName", "(", "iosProjectFilePath", ")", ";", "// if name has not changed - do nothing", "if", "(", "oldProjectName", ".", "length", "&&", "oldProjectName", "===", "newProjectName", ")", "{", "return", ";", "}", "console", ".", "log", "(", "'Project name has changed. Renaming .entitlements file.'", ")", ";", "// if it does - rename it", "var", "oldEntitlementsFilePath", "=", "path", ".", "join", "(", "iosProjectFilePath", ",", "oldProjectName", ",", "'Resources'", ",", "oldProjectName", "+", "'.entitlements'", ")", ";", "var", "newEntitlementsFilePath", "=", "path", ".", "join", "(", "iosProjectFilePath", ",", "oldProjectName", ",", "'Resources'", ",", "newProjectName", "+", "'.entitlements'", ")", ";", "try", "{", "fs", ".", "renameSync", "(", "oldEntitlementsFilePath", ",", "newEntitlementsFilePath", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "warn", "(", "'Failed to rename .entitlements file.'", ")", ";", "console", ".", "warn", "(", "err", ")", ";", "}", "}" ]
Run the hook logic. @param {Object} ctx - cordova context object
[ "Run", "the", "hook", "logic", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/iosBeforePrepareHook.js#L20-L45
17,463
nordnet/cordova-universal-links-plugin
hooks/iosBeforePrepareHook.js
getOldProjectName
function getOldProjectName(projectDir) { var files = []; try { files = fs.readdirSync(projectDir); } catch (err) { return ''; } var projectFile = ''; files.forEach(function(fileName) { if (path.extname(fileName) === '.xcodeproj') { projectFile = path.basename(fileName, '.xcodeproj'); } }); return projectFile; }
javascript
function getOldProjectName(projectDir) { var files = []; try { files = fs.readdirSync(projectDir); } catch (err) { return ''; } var projectFile = ''; files.forEach(function(fileName) { if (path.extname(fileName) === '.xcodeproj') { projectFile = path.basename(fileName, '.xcodeproj'); } }); return projectFile; }
[ "function", "getOldProjectName", "(", "projectDir", ")", "{", "var", "files", "=", "[", "]", ";", "try", "{", "files", "=", "fs", ".", "readdirSync", "(", "projectDir", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "''", ";", "}", "var", "projectFile", "=", "''", ";", "files", ".", "forEach", "(", "function", "(", "fileName", ")", "{", "if", "(", "path", ".", "extname", "(", "fileName", ")", "===", "'.xcodeproj'", ")", "{", "projectFile", "=", "path", ".", "basename", "(", "fileName", ",", "'.xcodeproj'", ")", ";", "}", "}", ")", ";", "return", "projectFile", ";", "}" ]
region Private API Get old name of the project. Name is detected by the name of the .xcodeproj file. @param {String} projectDir absolute path to ios project directory @return {String} old project name
[ "region", "Private", "API", "Get", "old", "name", "of", "the", "project", ".", "Name", "is", "detected", "by", "the", "name", "of", "the", ".", "xcodeproj", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/iosBeforePrepareHook.js#L56-L72
17,464
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
writePreferences
function writePreferences(cordovaContext, pluginPreferences) { var pathToManifest = path.join(cordovaContext.opts.projectRoot, 'platforms', 'android', 'AndroidManifest.xml'); var manifestSource = xmlHelper.readXmlAsJson(pathToManifest); var cleanManifest; var updatedManifest; // remove old intent-filters cleanManifest = removeOldOptions(manifestSource); // inject intent-filters based on plugin preferences updatedManifest = injectOptions(cleanManifest, pluginPreferences); // save new version of the AndroidManifest xmlHelper.writeJsonAsXml(updatedManifest, pathToManifest); }
javascript
function writePreferences(cordovaContext, pluginPreferences) { var pathToManifest = path.join(cordovaContext.opts.projectRoot, 'platforms', 'android', 'AndroidManifest.xml'); var manifestSource = xmlHelper.readXmlAsJson(pathToManifest); var cleanManifest; var updatedManifest; // remove old intent-filters cleanManifest = removeOldOptions(manifestSource); // inject intent-filters based on plugin preferences updatedManifest = injectOptions(cleanManifest, pluginPreferences); // save new version of the AndroidManifest xmlHelper.writeJsonAsXml(updatedManifest, pathToManifest); }
[ "function", "writePreferences", "(", "cordovaContext", ",", "pluginPreferences", ")", "{", "var", "pathToManifest", "=", "path", ".", "join", "(", "cordovaContext", ".", "opts", ".", "projectRoot", ",", "'platforms'", ",", "'android'", ",", "'AndroidManifest.xml'", ")", ";", "var", "manifestSource", "=", "xmlHelper", ".", "readXmlAsJson", "(", "pathToManifest", ")", ";", "var", "cleanManifest", ";", "var", "updatedManifest", ";", "// remove old intent-filters", "cleanManifest", "=", "removeOldOptions", "(", "manifestSource", ")", ";", "// inject intent-filters based on plugin preferences", "updatedManifest", "=", "injectOptions", "(", "cleanManifest", ",", "pluginPreferences", ")", ";", "// save new version of the AndroidManifest", "xmlHelper", ".", "writeJsonAsXml", "(", "updatedManifest", ",", "pathToManifest", ")", ";", "}" ]
region Public API Inject preferences into AndroidManifest.xml file. @param {Object} cordovaContext - cordova context object @param {Object} pluginPreferences - plugin preferences as JSON object; already parsed
[ "region", "Public", "API", "Inject", "preferences", "into", "AndroidManifest", ".", "xml", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L20-L34
17,465
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
removeOldOptions
function removeOldOptions(manifestData) { var cleanManifest = manifestData; var activities = manifestData['manifest']['application'][0]['activity']; activities.forEach(removeIntentFiltersFromActivity); cleanManifest['manifest']['application'][0]['activity'] = activities; return cleanManifest; }
javascript
function removeOldOptions(manifestData) { var cleanManifest = manifestData; var activities = manifestData['manifest']['application'][0]['activity']; activities.forEach(removeIntentFiltersFromActivity); cleanManifest['manifest']['application'][0]['activity'] = activities; return cleanManifest; }
[ "function", "removeOldOptions", "(", "manifestData", ")", "{", "var", "cleanManifest", "=", "manifestData", ";", "var", "activities", "=", "manifestData", "[", "'manifest'", "]", "[", "'application'", "]", "[", "0", "]", "[", "'activity'", "]", ";", "activities", ".", "forEach", "(", "removeIntentFiltersFromActivity", ")", ";", "cleanManifest", "[", "'manifest'", "]", "[", "'application'", "]", "[", "0", "]", "[", "'activity'", "]", "=", "activities", ";", "return", "cleanManifest", ";", "}" ]
region Manifest cleanup methods Remove old intent-filters from the manifest file. @param {Object} manifestData - manifest content as JSON object @return {Object} manifest data without old intent-filters
[ "region", "Manifest", "cleanup", "methods", "Remove", "old", "intent", "-", "filters", "from", "the", "manifest", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L46-L54
17,466
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
removeIntentFiltersFromActivity
function removeIntentFiltersFromActivity(activity) { var oldIntentFilters = activity['intent-filter']; var newIntentFilters = []; if (oldIntentFilters == null || oldIntentFilters.length == 0) { return; } oldIntentFilters.forEach(function(intentFilter) { if (!isIntentFilterForUniversalLinks(intentFilter)) { newIntentFilters.push(intentFilter); } }); activity['intent-filter'] = newIntentFilters; }
javascript
function removeIntentFiltersFromActivity(activity) { var oldIntentFilters = activity['intent-filter']; var newIntentFilters = []; if (oldIntentFilters == null || oldIntentFilters.length == 0) { return; } oldIntentFilters.forEach(function(intentFilter) { if (!isIntentFilterForUniversalLinks(intentFilter)) { newIntentFilters.push(intentFilter); } }); activity['intent-filter'] = newIntentFilters; }
[ "function", "removeIntentFiltersFromActivity", "(", "activity", ")", "{", "var", "oldIntentFilters", "=", "activity", "[", "'intent-filter'", "]", ";", "var", "newIntentFilters", "=", "[", "]", ";", "if", "(", "oldIntentFilters", "==", "null", "||", "oldIntentFilters", ".", "length", "==", "0", ")", "{", "return", ";", "}", "oldIntentFilters", ".", "forEach", "(", "function", "(", "intentFilter", ")", "{", "if", "(", "!", "isIntentFilterForUniversalLinks", "(", "intentFilter", ")", ")", "{", "newIntentFilters", ".", "push", "(", "intentFilter", ")", ";", "}", "}", ")", ";", "activity", "[", "'intent-filter'", "]", "=", "newIntentFilters", ";", "}" ]
Remove old intent filters from the given activity. @param {Object} activity - activity, from which we need to remove intent-filters. Changes applied to the passed object.
[ "Remove", "old", "intent", "filters", "from", "the", "given", "activity", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L62-L77
17,467
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
isIntentFilterForUniversalLinks
function isIntentFilterForUniversalLinks(intentFilter) { var actions = intentFilter['action']; var categories = intentFilter['category']; var data = intentFilter['data']; return isActionForUniversalLinks(actions) && isCategoriesForUniversalLinks(categories) && isDataTagForUniversalLinks(data); }
javascript
function isIntentFilterForUniversalLinks(intentFilter) { var actions = intentFilter['action']; var categories = intentFilter['category']; var data = intentFilter['data']; return isActionForUniversalLinks(actions) && isCategoriesForUniversalLinks(categories) && isDataTagForUniversalLinks(data); }
[ "function", "isIntentFilterForUniversalLinks", "(", "intentFilter", ")", "{", "var", "actions", "=", "intentFilter", "[", "'action'", "]", ";", "var", "categories", "=", "intentFilter", "[", "'category'", "]", ";", "var", "data", "=", "intentFilter", "[", "'data'", "]", ";", "return", "isActionForUniversalLinks", "(", "actions", ")", "&&", "isCategoriesForUniversalLinks", "(", "categories", ")", "&&", "isDataTagForUniversalLinks", "(", "data", ")", ";", "}" ]
Check if given intent-filter is for Universal Links. @param {Object} intentFilter - intent-filter to check @return {Boolean} true - if intent-filter for Universal Links; otherwise - false;
[ "Check", "if", "given", "intent", "-", "filter", "is", "for", "Universal", "Links", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L85-L93
17,468
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
isActionForUniversalLinks
function isActionForUniversalLinks(actions) { // there can be only 1 action if (actions == null || actions.length != 1) { return false; } var action = actions[0]['$']['android:name']; return ('android.intent.action.VIEW' === action); }
javascript
function isActionForUniversalLinks(actions) { // there can be only 1 action if (actions == null || actions.length != 1) { return false; } var action = actions[0]['$']['android:name']; return ('android.intent.action.VIEW' === action); }
[ "function", "isActionForUniversalLinks", "(", "actions", ")", "{", "// there can be only 1 action", "if", "(", "actions", "==", "null", "||", "actions", ".", "length", "!=", "1", ")", "{", "return", "false", ";", "}", "var", "action", "=", "actions", "[", "0", "]", "[", "'$'", "]", "[", "'android:name'", "]", ";", "return", "(", "'android.intent.action.VIEW'", "===", "action", ")", ";", "}" ]
Check if actions from the intent-filter corresponds to actions for Universal Links. @param {Array} actions - list of actions in the intent-filter @return {Boolean} true - if action for Universal Links; otherwise - false
[ "Check", "if", "actions", "from", "the", "intent", "-", "filter", "corresponds", "to", "actions", "for", "Universal", "Links", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L101-L110
17,469
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
isCategoriesForUniversalLinks
function isCategoriesForUniversalLinks(categories) { // there can be only 2 categories if (categories == null || categories.length != 2) { return false; } var isBrowsable = false; var isDefault = false; // check intent categories categories.forEach(function(category) { var categoryName = category['$']['android:name']; if (!isBrowsable) { isBrowsable = 'android.intent.category.BROWSABLE' === categoryName; } if (!isDefault) { isDefault = 'android.intent.category.DEFAULT' === categoryName; } }); return isDefault && isBrowsable; }
javascript
function isCategoriesForUniversalLinks(categories) { // there can be only 2 categories if (categories == null || categories.length != 2) { return false; } var isBrowsable = false; var isDefault = false; // check intent categories categories.forEach(function(category) { var categoryName = category['$']['android:name']; if (!isBrowsable) { isBrowsable = 'android.intent.category.BROWSABLE' === categoryName; } if (!isDefault) { isDefault = 'android.intent.category.DEFAULT' === categoryName; } }); return isDefault && isBrowsable; }
[ "function", "isCategoriesForUniversalLinks", "(", "categories", ")", "{", "// there can be only 2 categories", "if", "(", "categories", "==", "null", "||", "categories", ".", "length", "!=", "2", ")", "{", "return", "false", ";", "}", "var", "isBrowsable", "=", "false", ";", "var", "isDefault", "=", "false", ";", "// check intent categories", "categories", ".", "forEach", "(", "function", "(", "category", ")", "{", "var", "categoryName", "=", "category", "[", "'$'", "]", "[", "'android:name'", "]", ";", "if", "(", "!", "isBrowsable", ")", "{", "isBrowsable", "=", "'android.intent.category.BROWSABLE'", "===", "categoryName", ";", "}", "if", "(", "!", "isDefault", ")", "{", "isDefault", "=", "'android.intent.category.DEFAULT'", "===", "categoryName", ";", "}", "}", ")", ";", "return", "isDefault", "&&", "isBrowsable", ";", "}" ]
Check if categories in the intent-filter corresponds to categories for Universal Links. @param {Array} categories - list of categories in the intent-filter @return {Boolean} true - if action for Universal Links; otherwise - false
[ "Check", "if", "categories", "in", "the", "intent", "-", "filter", "corresponds", "to", "categories", "for", "Universal", "Links", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L118-L140
17,470
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
isDataTagForUniversalLinks
function isDataTagForUniversalLinks(data) { // can have only 1 data tag in the intent-filter if (data == null || data.length != 1) { return false; } var dataHost = data[0]['$']['android:host']; var dataScheme = data[0]['$']['android:scheme']; var hostIsSet = dataHost != null && dataHost.length > 0; var schemeIsSet = dataScheme != null && dataScheme.length > 0; return hostIsSet && schemeIsSet; }
javascript
function isDataTagForUniversalLinks(data) { // can have only 1 data tag in the intent-filter if (data == null || data.length != 1) { return false; } var dataHost = data[0]['$']['android:host']; var dataScheme = data[0]['$']['android:scheme']; var hostIsSet = dataHost != null && dataHost.length > 0; var schemeIsSet = dataScheme != null && dataScheme.length > 0; return hostIsSet && schemeIsSet; }
[ "function", "isDataTagForUniversalLinks", "(", "data", ")", "{", "// can have only 1 data tag in the intent-filter", "if", "(", "data", "==", "null", "||", "data", ".", "length", "!=", "1", ")", "{", "return", "false", ";", "}", "var", "dataHost", "=", "data", "[", "0", "]", "[", "'$'", "]", "[", "'android:host'", "]", ";", "var", "dataScheme", "=", "data", "[", "0", "]", "[", "'$'", "]", "[", "'android:scheme'", "]", ";", "var", "hostIsSet", "=", "dataHost", "!=", "null", "&&", "dataHost", ".", "length", ">", "0", ";", "var", "schemeIsSet", "=", "dataScheme", "!=", "null", "&&", "dataScheme", ".", "length", ">", "0", ";", "return", "hostIsSet", "&&", "schemeIsSet", ";", "}" ]
Check if data tag from intent-filter corresponds to data for Universal Links. @param {Array} data - list of data tags in the intent-filter @return {Boolean} true - if data tag for Universal Links; otherwise - false
[ "Check", "if", "data", "tag", "from", "intent", "-", "filter", "corresponds", "to", "data", "for", "Universal", "Links", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L148-L160
17,471
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
injectOptions
function injectOptions(manifestData, pluginPreferences) { var changedManifest = manifestData; var activitiesList = changedManifest['manifest']['application'][0]['activity']; var launchActivityIndex = getMainLaunchActivityIndex(activitiesList); var ulIntentFilters = []; var launchActivity; if (launchActivityIndex < 0) { console.warn('Could not find launch activity in the AndroidManifest file. Can\'t inject Universal Links preferences.'); return; } // get launch activity launchActivity = activitiesList[launchActivityIndex]; // generate intent-filters pluginPreferences.hosts.forEach(function(host) { host.paths.forEach(function(hostPath) { ulIntentFilters.push(createIntentFilter(host.name, host.scheme, hostPath)); }); }); // add Universal Links intent-filters to the launch activity launchActivity['intent-filter'] = launchActivity['intent-filter'].concat(ulIntentFilters); return changedManifest; }
javascript
function injectOptions(manifestData, pluginPreferences) { var changedManifest = manifestData; var activitiesList = changedManifest['manifest']['application'][0]['activity']; var launchActivityIndex = getMainLaunchActivityIndex(activitiesList); var ulIntentFilters = []; var launchActivity; if (launchActivityIndex < 0) { console.warn('Could not find launch activity in the AndroidManifest file. Can\'t inject Universal Links preferences.'); return; } // get launch activity launchActivity = activitiesList[launchActivityIndex]; // generate intent-filters pluginPreferences.hosts.forEach(function(host) { host.paths.forEach(function(hostPath) { ulIntentFilters.push(createIntentFilter(host.name, host.scheme, hostPath)); }); }); // add Universal Links intent-filters to the launch activity launchActivity['intent-filter'] = launchActivity['intent-filter'].concat(ulIntentFilters); return changedManifest; }
[ "function", "injectOptions", "(", "manifestData", ",", "pluginPreferences", ")", "{", "var", "changedManifest", "=", "manifestData", ";", "var", "activitiesList", "=", "changedManifest", "[", "'manifest'", "]", "[", "'application'", "]", "[", "0", "]", "[", "'activity'", "]", ";", "var", "launchActivityIndex", "=", "getMainLaunchActivityIndex", "(", "activitiesList", ")", ";", "var", "ulIntentFilters", "=", "[", "]", ";", "var", "launchActivity", ";", "if", "(", "launchActivityIndex", "<", "0", ")", "{", "console", ".", "warn", "(", "'Could not find launch activity in the AndroidManifest file. Can\\'t inject Universal Links preferences.'", ")", ";", "return", ";", "}", "// get launch activity", "launchActivity", "=", "activitiesList", "[", "launchActivityIndex", "]", ";", "// generate intent-filters", "pluginPreferences", ".", "hosts", ".", "forEach", "(", "function", "(", "host", ")", "{", "host", ".", "paths", ".", "forEach", "(", "function", "(", "hostPath", ")", "{", "ulIntentFilters", ".", "push", "(", "createIntentFilter", "(", "host", ".", "name", ",", "host", ".", "scheme", ",", "hostPath", ")", ")", ";", "}", ")", ";", "}", ")", ";", "// add Universal Links intent-filters to the launch activity", "launchActivity", "[", "'intent-filter'", "]", "=", "launchActivity", "[", "'intent-filter'", "]", ".", "concat", "(", "ulIntentFilters", ")", ";", "return", "changedManifest", ";", "}" ]
region Methods to inject preferences into AndroidManifest.xml file Inject options into manifest file. @param {Object} manifestData - manifest content where preferences should be injected @param {Object} pluginPreferences - plugin preferences from config.xml; already parsed @return {Object} updated manifest data with corresponding intent-filters
[ "region", "Methods", "to", "inject", "preferences", "into", "AndroidManifest", ".", "xml", "file", "Inject", "options", "into", "manifest", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L173-L199
17,472
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
getMainLaunchActivityIndex
function getMainLaunchActivityIndex(activities) { var launchActivityIndex = -1; activities.some(function(activity, index) { if (isLaunchActivity(activity)) { launchActivityIndex = index; return true; } return false; }); return launchActivityIndex; }
javascript
function getMainLaunchActivityIndex(activities) { var launchActivityIndex = -1; activities.some(function(activity, index) { if (isLaunchActivity(activity)) { launchActivityIndex = index; return true; } return false; }); return launchActivityIndex; }
[ "function", "getMainLaunchActivityIndex", "(", "activities", ")", "{", "var", "launchActivityIndex", "=", "-", "1", ";", "activities", ".", "some", "(", "function", "(", "activity", ",", "index", ")", "{", "if", "(", "isLaunchActivity", "(", "activity", ")", ")", "{", "launchActivityIndex", "=", "index", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "return", "launchActivityIndex", ";", "}" ]
Find index of the applications launcher activity. @param {Array} activities - list of all activities in the app @return {Integer} index of the launch activity; -1 - if none was found
[ "Find", "index", "of", "the", "applications", "launcher", "activity", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L207-L219
17,473
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
createIntentFilter
function createIntentFilter(host, scheme, pathName) { var intentFilter = { '$': { 'android:autoVerify': 'true' }, 'action': [{ '$': { 'android:name': 'android.intent.action.VIEW' } }], 'category': [{ '$': { 'android:name': 'android.intent.category.DEFAULT' } }, { '$': { 'android:name': 'android.intent.category.BROWSABLE' } }], 'data': [{ '$': { 'android:host': host, 'android:scheme': scheme } }] }; injectPathComponentIntoIntentFilter(intentFilter, pathName); return intentFilter; }
javascript
function createIntentFilter(host, scheme, pathName) { var intentFilter = { '$': { 'android:autoVerify': 'true' }, 'action': [{ '$': { 'android:name': 'android.intent.action.VIEW' } }], 'category': [{ '$': { 'android:name': 'android.intent.category.DEFAULT' } }, { '$': { 'android:name': 'android.intent.category.BROWSABLE' } }], 'data': [{ '$': { 'android:host': host, 'android:scheme': scheme } }] }; injectPathComponentIntoIntentFilter(intentFilter, pathName); return intentFilter; }
[ "function", "createIntentFilter", "(", "host", ",", "scheme", ",", "pathName", ")", "{", "var", "intentFilter", "=", "{", "'$'", ":", "{", "'android:autoVerify'", ":", "'true'", "}", ",", "'action'", ":", "[", "{", "'$'", ":", "{", "'android:name'", ":", "'android.intent.action.VIEW'", "}", "}", "]", ",", "'category'", ":", "[", "{", "'$'", ":", "{", "'android:name'", ":", "'android.intent.category.DEFAULT'", "}", "}", ",", "{", "'$'", ":", "{", "'android:name'", ":", "'android.intent.category.BROWSABLE'", "}", "}", "]", ",", "'data'", ":", "[", "{", "'$'", ":", "{", "'android:host'", ":", "host", ",", "'android:scheme'", ":", "scheme", "}", "}", "]", "}", ";", "injectPathComponentIntoIntentFilter", "(", "intentFilter", ",", "pathName", ")", ";", "return", "intentFilter", ";", "}" ]
Create JSON object that represent intent-filter for universal link. @param {String} host - host name @param {String} scheme - host scheme @param {String} pathName - host path @return {Object} intent-filter as a JSON object
[ "Create", "JSON", "object", "that", "represent", "intent", "-", "filter", "for", "universal", "link", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L260-L290
17,474
nordnet/cordova-universal-links-plugin
hooks/lib/android/manifestWriter.js
injectPathComponentIntoIntentFilter
function injectPathComponentIntoIntentFilter(intentFilter, pathName) { if (pathName == null || pathName === '*') { return; } var attrKey = 'android:path'; if (pathName.indexOf('*') >= 0) { attrKey = 'android:pathPattern'; pathName = pathName.replace(/\*/g, '.*'); } if (pathName.indexOf('/') != 0) { pathName = '/' + pathName; } intentFilter['data'][0]['$'][attrKey] = pathName; }
javascript
function injectPathComponentIntoIntentFilter(intentFilter, pathName) { if (pathName == null || pathName === '*') { return; } var attrKey = 'android:path'; if (pathName.indexOf('*') >= 0) { attrKey = 'android:pathPattern'; pathName = pathName.replace(/\*/g, '.*'); } if (pathName.indexOf('/') != 0) { pathName = '/' + pathName; } intentFilter['data'][0]['$'][attrKey] = pathName; }
[ "function", "injectPathComponentIntoIntentFilter", "(", "intentFilter", ",", "pathName", ")", "{", "if", "(", "pathName", "==", "null", "||", "pathName", "===", "'*'", ")", "{", "return", ";", "}", "var", "attrKey", "=", "'android:path'", ";", "if", "(", "pathName", ".", "indexOf", "(", "'*'", ")", ">=", "0", ")", "{", "attrKey", "=", "'android:pathPattern'", ";", "pathName", "=", "pathName", ".", "replace", "(", "/", "\\*", "/", "g", ",", "'.*'", ")", ";", "}", "if", "(", "pathName", ".", "indexOf", "(", "'/'", ")", "!=", "0", ")", "{", "pathName", "=", "'/'", "+", "pathName", ";", "}", "intentFilter", "[", "'data'", "]", "[", "0", "]", "[", "'$'", "]", "[", "attrKey", "]", "=", "pathName", ";", "}" ]
Inject host path into provided intent-filter. @param {Object} intentFilter - intent-filter object where path component should be injected @param {String} pathName - host path to inject
[ "Inject", "host", "path", "into", "provided", "intent", "-", "filter", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/android/manifestWriter.js#L298-L314
17,475
nordnet/cordova-universal-links-plugin
hooks/lib/configXmlParser.js
readPreferences
function readPreferences(cordovaContext) { // read data from projects root config.xml file var configXml = new ConfigXmlHelper(cordovaContext).read(); if (configXml == null) { console.warn('config.xml not found! Please, check that it exist\'s in your project\'s root directory.'); return null; } // look for data from the <universal-links> tag var ulXmlPreferences = configXml.widget['universal-links']; if (ulXmlPreferences == null || ulXmlPreferences.length == 0) { console.warn('<universal-links> tag is not set in the config.xml. Universal Links plugin is not going to work.'); return null; } var xmlPreferences = ulXmlPreferences[0]; // read hosts var hosts = constructHostsList(xmlPreferences); // read ios team ID var iosTeamId = getTeamIdPreference(xmlPreferences); return { 'hosts': hosts, 'iosTeamId': iosTeamId }; }
javascript
function readPreferences(cordovaContext) { // read data from projects root config.xml file var configXml = new ConfigXmlHelper(cordovaContext).read(); if (configXml == null) { console.warn('config.xml not found! Please, check that it exist\'s in your project\'s root directory.'); return null; } // look for data from the <universal-links> tag var ulXmlPreferences = configXml.widget['universal-links']; if (ulXmlPreferences == null || ulXmlPreferences.length == 0) { console.warn('<universal-links> tag is not set in the config.xml. Universal Links plugin is not going to work.'); return null; } var xmlPreferences = ulXmlPreferences[0]; // read hosts var hosts = constructHostsList(xmlPreferences); // read ios team ID var iosTeamId = getTeamIdPreference(xmlPreferences); return { 'hosts': hosts, 'iosTeamId': iosTeamId }; }
[ "function", "readPreferences", "(", "cordovaContext", ")", "{", "// read data from projects root config.xml file", "var", "configXml", "=", "new", "ConfigXmlHelper", "(", "cordovaContext", ")", ".", "read", "(", ")", ";", "if", "(", "configXml", "==", "null", ")", "{", "console", ".", "warn", "(", "'config.xml not found! Please, check that it exist\\'s in your project\\'s root directory.'", ")", ";", "return", "null", ";", "}", "// look for data from the <universal-links> tag", "var", "ulXmlPreferences", "=", "configXml", ".", "widget", "[", "'universal-links'", "]", ";", "if", "(", "ulXmlPreferences", "==", "null", "||", "ulXmlPreferences", ".", "length", "==", "0", ")", "{", "console", ".", "warn", "(", "'<universal-links> tag is not set in the config.xml. Universal Links plugin is not going to work.'", ")", ";", "return", "null", ";", "}", "var", "xmlPreferences", "=", "ulXmlPreferences", "[", "0", "]", ";", "// read hosts", "var", "hosts", "=", "constructHostsList", "(", "xmlPreferences", ")", ";", "// read ios team ID", "var", "iosTeamId", "=", "getTeamIdPreference", "(", "xmlPreferences", ")", ";", "return", "{", "'hosts'", ":", "hosts", ",", "'iosTeamId'", ":", "iosTeamId", "}", ";", "}" ]
region Public API Read plugin preferences from the config.xml file. @param {Object} cordovaContext - cordova context object @return {Array} list of host objects
[ "region", "Public", "API", "Read", "plugin", "preferences", "from", "the", "config", ".", "xml", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/configXmlParser.js#L20-L47
17,476
nordnet/cordova-universal-links-plugin
hooks/lib/configXmlParser.js
constructHostsList
function constructHostsList(xmlPreferences) { var hostsList = []; // look for defined hosts var xmlHostList = xmlPreferences['host']; if (xmlHostList == null || xmlHostList.length == 0) { return []; } xmlHostList.forEach(function(xmlElement) { var host = constructHostEntry(xmlElement); if (host) { hostsList.push(host); } }); return hostsList; }
javascript
function constructHostsList(xmlPreferences) { var hostsList = []; // look for defined hosts var xmlHostList = xmlPreferences['host']; if (xmlHostList == null || xmlHostList.length == 0) { return []; } xmlHostList.forEach(function(xmlElement) { var host = constructHostEntry(xmlElement); if (host) { hostsList.push(host); } }); return hostsList; }
[ "function", "constructHostsList", "(", "xmlPreferences", ")", "{", "var", "hostsList", "=", "[", "]", ";", "// look for defined hosts", "var", "xmlHostList", "=", "xmlPreferences", "[", "'host'", "]", ";", "if", "(", "xmlHostList", "==", "null", "||", "xmlHostList", ".", "length", "==", "0", ")", "{", "return", "[", "]", ";", "}", "xmlHostList", ".", "forEach", "(", "function", "(", "xmlElement", ")", "{", "var", "host", "=", "constructHostEntry", "(", "xmlElement", ")", ";", "if", "(", "host", ")", "{", "hostsList", ".", "push", "(", "host", ")", ";", "}", "}", ")", ";", "return", "hostsList", ";", "}" ]
Construct list of host objects, defined in xml file. @param {Object} xmlPreferences - plugin preferences from config.xml as JSON object @return {Array} array of JSON objects, where each entry defines host data from config.xml.
[ "Construct", "list", "of", "host", "objects", "defined", "in", "xml", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/configXmlParser.js#L67-L84
17,477
nordnet/cordova-universal-links-plugin
hooks/lib/configXmlParser.js
constructHostEntry
function constructHostEntry(xmlElement) { var host = { scheme: DEFAULT_SCHEME, name: '', paths: [] }; var hostProperties = xmlElement['$']; if (hostProperties == null || hostProperties.length == 0) { return null; } // read host name host.name = hostProperties.name; // read scheme if defined if (hostProperties['scheme'] != null) { host.scheme = hostProperties.scheme; } // construct paths list, defined for the given host host.paths = constructPaths(xmlElement); return host; }
javascript
function constructHostEntry(xmlElement) { var host = { scheme: DEFAULT_SCHEME, name: '', paths: [] }; var hostProperties = xmlElement['$']; if (hostProperties == null || hostProperties.length == 0) { return null; } // read host name host.name = hostProperties.name; // read scheme if defined if (hostProperties['scheme'] != null) { host.scheme = hostProperties.scheme; } // construct paths list, defined for the given host host.paths = constructPaths(xmlElement); return host; }
[ "function", "constructHostEntry", "(", "xmlElement", ")", "{", "var", "host", "=", "{", "scheme", ":", "DEFAULT_SCHEME", ",", "name", ":", "''", ",", "paths", ":", "[", "]", "}", ";", "var", "hostProperties", "=", "xmlElement", "[", "'$'", "]", ";", "if", "(", "hostProperties", "==", "null", "||", "hostProperties", ".", "length", "==", "0", ")", "{", "return", "null", ";", "}", "// read host name", "host", ".", "name", "=", "hostProperties", ".", "name", ";", "// read scheme if defined", "if", "(", "hostProperties", "[", "'scheme'", "]", "!=", "null", ")", "{", "host", ".", "scheme", "=", "hostProperties", ".", "scheme", ";", "}", "// construct paths list, defined for the given host", "host", ".", "paths", "=", "constructPaths", "(", "xmlElement", ")", ";", "return", "host", ";", "}" ]
Construct host object from xml data. @param {Object} xmlElement - xml data to process. @return {Object} host entry as JSON object
[ "Construct", "host", "object", "from", "xml", "data", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/configXmlParser.js#L92-L116
17,478
nordnet/cordova-universal-links-plugin
hooks/lib/configXmlParser.js
constructPaths
function constructPaths(xmlElement) { if (xmlElement['path'] == null) { return ['*']; } var paths = []; xmlElement.path.some(function(pathElement) { var url = pathElement['$']['url']; // Ignore explicit paths if '*' is defined if (url === '*') { paths = ['*']; return true; } paths.push(url); }); return paths; }
javascript
function constructPaths(xmlElement) { if (xmlElement['path'] == null) { return ['*']; } var paths = []; xmlElement.path.some(function(pathElement) { var url = pathElement['$']['url']; // Ignore explicit paths if '*' is defined if (url === '*') { paths = ['*']; return true; } paths.push(url); }); return paths; }
[ "function", "constructPaths", "(", "xmlElement", ")", "{", "if", "(", "xmlElement", "[", "'path'", "]", "==", "null", ")", "{", "return", "[", "'*'", "]", ";", "}", "var", "paths", "=", "[", "]", ";", "xmlElement", ".", "path", ".", "some", "(", "function", "(", "pathElement", ")", "{", "var", "url", "=", "pathElement", "[", "'$'", "]", "[", "'url'", "]", ";", "// Ignore explicit paths if '*' is defined", "if", "(", "url", "===", "'*'", ")", "{", "paths", "=", "[", "'*'", "]", ";", "return", "true", ";", "}", "paths", ".", "push", "(", "url", ")", ";", "}", ")", ";", "return", "paths", ";", "}" ]
Construct list of path objects from the xml data. @param {Object} xmlElement - xml data to process @return {Array} list of path entries, each on is a JSON object
[ "Construct", "list", "of", "path", "objects", "from", "the", "xml", "data", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/configXmlParser.js#L124-L143
17,479
nordnet/cordova-universal-links-plugin
hooks/lib/ios/appleAppSiteAssociationFile.js
createNewAssociationFiles
function createNewAssociationFiles(pluginPreferences) { var teamId = pluginPreferences.iosTeamId; if (!teamId) { teamId = IOS_TEAM_ID; } pluginPreferences.hosts.forEach(function(host) { var content = generateFileContentForHost(host, teamId); saveContentToFile(host.name, content); }); }
javascript
function createNewAssociationFiles(pluginPreferences) { var teamId = pluginPreferences.iosTeamId; if (!teamId) { teamId = IOS_TEAM_ID; } pluginPreferences.hosts.forEach(function(host) { var content = generateFileContentForHost(host, teamId); saveContentToFile(host.name, content); }); }
[ "function", "createNewAssociationFiles", "(", "pluginPreferences", ")", "{", "var", "teamId", "=", "pluginPreferences", ".", "iosTeamId", ";", "if", "(", "!", "teamId", ")", "{", "teamId", "=", "IOS_TEAM_ID", ";", "}", "pluginPreferences", ".", "hosts", ".", "forEach", "(", "function", "(", "host", ")", "{", "var", "content", "=", "generateFileContentForHost", "(", "host", ",", "teamId", ")", ";", "saveContentToFile", "(", "host", ".", "name", ",", "content", ")", ";", "}", ")", ";", "}" ]
Generate new set of apple-app-site-association files. @param {Object} pluginPreferences - list of hosts from config.xml
[ "Generate", "new", "set", "of", "apple", "-", "app", "-", "site", "-", "association", "files", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/appleAppSiteAssociationFile.js#L64-L74
17,480
nordnet/cordova-universal-links-plugin
hooks/lib/ios/appleAppSiteAssociationFile.js
generateFileContentForHost
function generateFileContentForHost(host, teamId) { var appID = teamId + '.' + getBundleId(); var paths = host.paths.slice(); // if paths are '*' - we should add '/' to it to support root domains. // https://github.com/nordnet/cordova-universal-links-plugin/issues/46 if (paths.length == 1 && paths[0] === '*') { paths.push('/'); } return { "applinks": { "apps": [], "details": [{ "appID": appID, "paths": paths }] } }; }
javascript
function generateFileContentForHost(host, teamId) { var appID = teamId + '.' + getBundleId(); var paths = host.paths.slice(); // if paths are '*' - we should add '/' to it to support root domains. // https://github.com/nordnet/cordova-universal-links-plugin/issues/46 if (paths.length == 1 && paths[0] === '*') { paths.push('/'); } return { "applinks": { "apps": [], "details": [{ "appID": appID, "paths": paths }] } }; }
[ "function", "generateFileContentForHost", "(", "host", ",", "teamId", ")", "{", "var", "appID", "=", "teamId", "+", "'.'", "+", "getBundleId", "(", ")", ";", "var", "paths", "=", "host", ".", "paths", ".", "slice", "(", ")", ";", "// if paths are '*' - we should add '/' to it to support root domains.", "// https://github.com/nordnet/cordova-universal-links-plugin/issues/46", "if", "(", "paths", ".", "length", "==", "1", "&&", "paths", "[", "0", "]", "===", "'*'", ")", "{", "paths", ".", "push", "(", "'/'", ")", ";", "}", "return", "{", "\"applinks\"", ":", "{", "\"apps\"", ":", "[", "]", ",", "\"details\"", ":", "[", "{", "\"appID\"", ":", "appID", ",", "\"paths\"", ":", "paths", "}", "]", "}", "}", ";", "}" ]
Generate content of the apple-app-site-association file for the specific host. @param {Object} host - host information @return {Object} content of the file as JSON object
[ "Generate", "content", "of", "the", "apple", "-", "app", "-", "site", "-", "association", "file", "for", "the", "specific", "host", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/appleAppSiteAssociationFile.js#L82-L101
17,481
nordnet/cordova-universal-links-plugin
hooks/lib/ios/appleAppSiteAssociationFile.js
saveContentToFile
function saveContentToFile(filePrefix, content) { var dirPath = getWebHookDirectory(); var filePath = path.join(dirPath, filePrefix + '#' + ASSOCIATION_FILE_NAME); // create all directories from file path createDirectoriesIfNeeded(dirPath); // write content to the file try { fs.writeFileSync(filePath, JSON.stringify(content, null, 2), 'utf8'); } catch (err) { console.log(err); } }
javascript
function saveContentToFile(filePrefix, content) { var dirPath = getWebHookDirectory(); var filePath = path.join(dirPath, filePrefix + '#' + ASSOCIATION_FILE_NAME); // create all directories from file path createDirectoriesIfNeeded(dirPath); // write content to the file try { fs.writeFileSync(filePath, JSON.stringify(content, null, 2), 'utf8'); } catch (err) { console.log(err); } }
[ "function", "saveContentToFile", "(", "filePrefix", ",", "content", ")", "{", "var", "dirPath", "=", "getWebHookDirectory", "(", ")", ";", "var", "filePath", "=", "path", ".", "join", "(", "dirPath", ",", "filePrefix", "+", "'#'", "+", "ASSOCIATION_FILE_NAME", ")", ";", "// create all directories from file path", "createDirectoriesIfNeeded", "(", "dirPath", ")", ";", "// write content to the file", "try", "{", "fs", ".", "writeFileSync", "(", "filePath", ",", "JSON", ".", "stringify", "(", "content", ",", "null", ",", "2", ")", ",", "'utf8'", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "}" ]
Save data to the the apple-app-site-association file. @param {String} filePrefix - prefix for the generated file; usually - hostname @param {Object} content - file content as JSON object
[ "Save", "data", "to", "the", "the", "apple", "-", "app", "-", "site", "-", "association", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/appleAppSiteAssociationFile.js#L109-L122
17,482
nordnet/cordova-universal-links-plugin
hooks/lib/ios/appleAppSiteAssociationFile.js
getBundleId
function getBundleId() { if (bundleId === undefined) { var configXmlHelper = new ConfigXmlHelper(context); bundleId = configXmlHelper.getPackageName('ios'); } return bundleId; }
javascript
function getBundleId() { if (bundleId === undefined) { var configXmlHelper = new ConfigXmlHelper(context); bundleId = configXmlHelper.getPackageName('ios'); } return bundleId; }
[ "function", "getBundleId", "(", ")", "{", "if", "(", "bundleId", "===", "undefined", ")", "{", "var", "configXmlHelper", "=", "new", "ConfigXmlHelper", "(", "context", ")", ";", "bundleId", "=", "configXmlHelper", ".", "getPackageName", "(", "'ios'", ")", ";", "}", "return", "bundleId", ";", "}" ]
Get bundle id from the config.xml file. @return {String} bundle id
[ "Get", "bundle", "id", "from", "the", "config", ".", "xml", "file", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/appleAppSiteAssociationFile.js#L164-L171
17,483
nordnet/cordova-universal-links-plugin
hooks/lib/configXmlHelper.js
getCordovaConfigParser
function getCordovaConfigParser(configFilePath) { var ConfigParser; // If we are running Cordova 5.4 or abova - use parser from cordova-common. // Otherwise - from cordova-lib. try { ConfigParser = context.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser'); } catch (e) { ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser') } return new ConfigParser(configFilePath); }
javascript
function getCordovaConfigParser(configFilePath) { var ConfigParser; // If we are running Cordova 5.4 or abova - use parser from cordova-common. // Otherwise - from cordova-lib. try { ConfigParser = context.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser'); } catch (e) { ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser') } return new ConfigParser(configFilePath); }
[ "function", "getCordovaConfigParser", "(", "configFilePath", ")", "{", "var", "ConfigParser", ";", "// If we are running Cordova 5.4 or abova - use parser from cordova-common.", "// Otherwise - from cordova-lib.", "try", "{", "ConfigParser", "=", "context", ".", "requireCordovaModule", "(", "'cordova-common/src/ConfigParser/ConfigParser'", ")", ";", "}", "catch", "(", "e", ")", "{", "ConfigParser", "=", "context", ".", "requireCordovaModule", "(", "'cordova-lib/src/configparser/ConfigParser'", ")", "}", "return", "new", "ConfigParser", "(", "configFilePath", ")", ";", "}" ]
region Private API Get config parser from cordova library. @param {String} configFilePath absolute path to the config.xml file @return {Object}
[ "region", "Private", "API", "Get", "config", "parser", "from", "cordova", "library", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/configXmlHelper.js#L86-L98
17,484
nordnet/cordova-universal-links-plugin
hooks/afterPrepareHook.js
run
function run(cordovaContext) { var pluginPreferences = configParser.readPreferences(cordovaContext); var platformsList = cordovaContext.opts.platforms; // if no preferences are found - exit if (pluginPreferences == null) { return; } // if no host is defined - exit if (pluginPreferences.hosts == null || pluginPreferences.hosts.length == 0) { console.warn('No host is specified in the config.xml. Universal Links plugin is not going to work.'); return; } platformsList.forEach(function(platform) { switch (platform) { case ANDROID: { activateUniversalLinksInAndroid(cordovaContext, pluginPreferences); break; } case IOS: { activateUniversalLinksInIos(cordovaContext, pluginPreferences); break; } } }); }
javascript
function run(cordovaContext) { var pluginPreferences = configParser.readPreferences(cordovaContext); var platformsList = cordovaContext.opts.platforms; // if no preferences are found - exit if (pluginPreferences == null) { return; } // if no host is defined - exit if (pluginPreferences.hosts == null || pluginPreferences.hosts.length == 0) { console.warn('No host is specified in the config.xml. Universal Links plugin is not going to work.'); return; } platformsList.forEach(function(platform) { switch (platform) { case ANDROID: { activateUniversalLinksInAndroid(cordovaContext, pluginPreferences); break; } case IOS: { activateUniversalLinksInIos(cordovaContext, pluginPreferences); break; } } }); }
[ "function", "run", "(", "cordovaContext", ")", "{", "var", "pluginPreferences", "=", "configParser", ".", "readPreferences", "(", "cordovaContext", ")", ";", "var", "platformsList", "=", "cordovaContext", ".", "opts", ".", "platforms", ";", "// if no preferences are found - exit", "if", "(", "pluginPreferences", "==", "null", ")", "{", "return", ";", "}", "// if no host is defined - exit", "if", "(", "pluginPreferences", ".", "hosts", "==", "null", "||", "pluginPreferences", ".", "hosts", ".", "length", "==", "0", ")", "{", "console", ".", "warn", "(", "'No host is specified in the config.xml. Universal Links plugin is not going to work.'", ")", ";", "return", ";", "}", "platformsList", ".", "forEach", "(", "function", "(", "platform", ")", "{", "switch", "(", "platform", ")", "{", "case", "ANDROID", ":", "{", "activateUniversalLinksInAndroid", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "break", ";", "}", "case", "IOS", ":", "{", "activateUniversalLinksInIos", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "break", ";", "}", "}", "}", ")", ";", "}" ]
Execute hook. @param {Object} cordovaContext - cordova context object
[ "Execute", "hook", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/afterPrepareHook.js#L26-L55
17,485
nordnet/cordova-universal-links-plugin
hooks/afterPrepareHook.js
activateUniversalLinksInAndroid
function activateUniversalLinksInAndroid(cordovaContext, pluginPreferences) { // inject preferenes into AndroidManifest.xml androidManifestWriter.writePreferences(cordovaContext, pluginPreferences); // generate html file with the <link> tags that you should inject on the website. androidWebHook.generate(cordovaContext, pluginPreferences); }
javascript
function activateUniversalLinksInAndroid(cordovaContext, pluginPreferences) { // inject preferenes into AndroidManifest.xml androidManifestWriter.writePreferences(cordovaContext, pluginPreferences); // generate html file with the <link> tags that you should inject on the website. androidWebHook.generate(cordovaContext, pluginPreferences); }
[ "function", "activateUniversalLinksInAndroid", "(", "cordovaContext", ",", "pluginPreferences", ")", "{", "// inject preferenes into AndroidManifest.xml", "androidManifestWriter", ".", "writePreferences", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "// generate html file with the <link> tags that you should inject on the website.", "androidWebHook", ".", "generate", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "}" ]
Activate Deep Links for Android application. @param {Object} cordovaContext - cordova context object @param {Object} pluginPreferences - plugin preferences from the config.xml file. Basically, content from <universal-links> tag.
[ "Activate", "Deep", "Links", "for", "Android", "application", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/afterPrepareHook.js#L63-L69
17,486
nordnet/cordova-universal-links-plugin
hooks/afterPrepareHook.js
activateUniversalLinksInIos
function activateUniversalLinksInIos(cordovaContext, pluginPreferences) { // modify xcode project preferences iosProjectPreferences.enableAssociativeDomainsCapability(cordovaContext); // generate entitlements file iosProjectEntitlements.generateAssociatedDomainsEntitlements(cordovaContext, pluginPreferences); // generate apple-site-association-file iosAppSiteAssociationFile.generate(cordovaContext, pluginPreferences); }
javascript
function activateUniversalLinksInIos(cordovaContext, pluginPreferences) { // modify xcode project preferences iosProjectPreferences.enableAssociativeDomainsCapability(cordovaContext); // generate entitlements file iosProjectEntitlements.generateAssociatedDomainsEntitlements(cordovaContext, pluginPreferences); // generate apple-site-association-file iosAppSiteAssociationFile.generate(cordovaContext, pluginPreferences); }
[ "function", "activateUniversalLinksInIos", "(", "cordovaContext", ",", "pluginPreferences", ")", "{", "// modify xcode project preferences", "iosProjectPreferences", ".", "enableAssociativeDomainsCapability", "(", "cordovaContext", ")", ";", "// generate entitlements file", "iosProjectEntitlements", ".", "generateAssociatedDomainsEntitlements", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "// generate apple-site-association-file", "iosAppSiteAssociationFile", ".", "generate", "(", "cordovaContext", ",", "pluginPreferences", ")", ";", "}" ]
Activate Universal Links for iOS application. @param {Object} cordovaContext - cordova context object @param {Object} pluginPreferences - plugin preferences from the config.xml file. Basically, content from <universal-links> tag.
[ "Activate", "Universal", "Links", "for", "iOS", "application", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/afterPrepareHook.js#L77-L86
17,487
nordnet/cordova-universal-links-plugin
hooks/lib/ios/xcodePreferences.js
enableAssociativeDomainsCapability
function enableAssociativeDomainsCapability(cordovaContext) { context = cordovaContext; var projectFile = loadProjectFile(); // adjust preferences activateAssociativeDomains(projectFile.xcode); // add entitlements file to pbxfilereference addPbxReference(projectFile.xcode); // save changes projectFile.write(); }
javascript
function enableAssociativeDomainsCapability(cordovaContext) { context = cordovaContext; var projectFile = loadProjectFile(); // adjust preferences activateAssociativeDomains(projectFile.xcode); // add entitlements file to pbxfilereference addPbxReference(projectFile.xcode); // save changes projectFile.write(); }
[ "function", "enableAssociativeDomainsCapability", "(", "cordovaContext", ")", "{", "context", "=", "cordovaContext", ";", "var", "projectFile", "=", "loadProjectFile", "(", ")", ";", "// adjust preferences", "activateAssociativeDomains", "(", "projectFile", ".", "xcode", ")", ";", "// add entitlements file to pbxfilereference", "addPbxReference", "(", "projectFile", ".", "xcode", ")", ";", "// save changes", "projectFile", ".", "write", "(", ")", ";", "}" ]
region Public API Activate associated domains capability for the application. @param {Object} cordovaContext - cordova context object
[ "region", "Public", "API", "Activate", "associated", "domains", "capability", "for", "the", "application", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/xcodePreferences.js#L27-L40
17,488
nordnet/cordova-universal-links-plugin
hooks/lib/ios/xcodePreferences.js
addPbxReference
function addPbxReference(xcodeProject) { var fileReferenceSection = nonComments(xcodeProject.pbxFileReferenceSection()); var entitlementsFileName = path.basename(pathToEntitlementsFile()); if (isPbxReferenceAlreadySet(fileReferenceSection, entitlementsFileName)) { console.log('Entitlements file is in reference section.'); return; } console.log('Entitlements file is not in references section, adding it'); xcodeProject.addResourceFile(entitlementsFileName); }
javascript
function addPbxReference(xcodeProject) { var fileReferenceSection = nonComments(xcodeProject.pbxFileReferenceSection()); var entitlementsFileName = path.basename(pathToEntitlementsFile()); if (isPbxReferenceAlreadySet(fileReferenceSection, entitlementsFileName)) { console.log('Entitlements file is in reference section.'); return; } console.log('Entitlements file is not in references section, adding it'); xcodeProject.addResourceFile(entitlementsFileName); }
[ "function", "addPbxReference", "(", "xcodeProject", ")", "{", "var", "fileReferenceSection", "=", "nonComments", "(", "xcodeProject", ".", "pbxFileReferenceSection", "(", ")", ")", ";", "var", "entitlementsFileName", "=", "path", ".", "basename", "(", "pathToEntitlementsFile", "(", ")", ")", ";", "if", "(", "isPbxReferenceAlreadySet", "(", "fileReferenceSection", ",", "entitlementsFileName", ")", ")", "{", "console", ".", "log", "(", "'Entitlements file is in reference section.'", ")", ";", "return", ";", "}", "console", ".", "log", "(", "'Entitlements file is not in references section, adding it'", ")", ";", "xcodeProject", ".", "addResourceFile", "(", "entitlementsFileName", ")", ";", "}" ]
region PBXReference methods Add .entitlemets file into the project. @param {Object} xcodeProject - xcode project preferences; all changes are made in that instance
[ "region", "PBXReference", "methods", "Add", ".", "entitlemets", "file", "into", "the", "project", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/xcodePreferences.js#L92-L103
17,489
nordnet/cordova-universal-links-plugin
hooks/lib/ios/xcodePreferences.js
loadProjectFile
function loadProjectFile() { var platform_ios; var projectFile; try { // try pre-5.0 cordova structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios']; projectFile = platform_ios.parseProjectFile(iosPlatformPath()); } catch (e) { // let's try cordova 5.0 structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios'); projectFile = platform_ios.parseProjectFile(iosPlatformPath()); } return projectFile; }
javascript
function loadProjectFile() { var platform_ios; var projectFile; try { // try pre-5.0 cordova structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios']; projectFile = platform_ios.parseProjectFile(iosPlatformPath()); } catch (e) { // let's try cordova 5.0 structure platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios'); projectFile = platform_ios.parseProjectFile(iosPlatformPath()); } return projectFile; }
[ "function", "loadProjectFile", "(", ")", "{", "var", "platform_ios", ";", "var", "projectFile", ";", "try", "{", "// try pre-5.0 cordova structure", "platform_ios", "=", "context", ".", "requireCordovaModule", "(", "'cordova-lib/src/plugman/platforms'", ")", "[", "'ios'", "]", ";", "projectFile", "=", "platform_ios", ".", "parseProjectFile", "(", "iosPlatformPath", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "// let's try cordova 5.0 structure", "platform_ios", "=", "context", ".", "requireCordovaModule", "(", "'cordova-lib/src/plugman/platforms/ios'", ")", ";", "projectFile", "=", "platform_ios", ".", "parseProjectFile", "(", "iosPlatformPath", "(", ")", ")", ";", "}", "return", "projectFile", ";", "}" ]
region Xcode project file helpers Load iOS project file from platform specific folder. @return {Object} projectFile - project file information
[ "region", "Xcode", "project", "file", "helpers", "Load", "iOS", "project", "file", "from", "platform", "specific", "folder", "." ]
9f2e812a0bf686279f94f68983707bc36efd7b11
https://github.com/nordnet/cordova-universal-links-plugin/blob/9f2e812a0bf686279f94f68983707bc36efd7b11/hooks/lib/ios/xcodePreferences.js#L135-L150
17,490
SassDoc/sassdoc
src/sassdoc.js
refresh
function refresh (env) { return safeWipe(env.dest, { force: true, parent: is.string(env.src) || is.array(env.src) ? g2b(env.src) : null, silent: true, }) .then(() => mkdir(env.dest)) .then(() => { env.logger.log(`Folder \`${env.displayDest}\` successfully refreshed.`) }) .catch(err => { // Friendly error for already existing directory. throw new errors.SassDocError(err.message) }) }
javascript
function refresh (env) { return safeWipe(env.dest, { force: true, parent: is.string(env.src) || is.array(env.src) ? g2b(env.src) : null, silent: true, }) .then(() => mkdir(env.dest)) .then(() => { env.logger.log(`Folder \`${env.displayDest}\` successfully refreshed.`) }) .catch(err => { // Friendly error for already existing directory. throw new errors.SassDocError(err.message) }) }
[ "function", "refresh", "(", "env", ")", "{", "return", "safeWipe", "(", "env", ".", "dest", ",", "{", "force", ":", "true", ",", "parent", ":", "is", ".", "string", "(", "env", ".", "src", ")", "||", "is", ".", "array", "(", "env", ".", "src", ")", "?", "g2b", "(", "env", ".", "src", ")", ":", "null", ",", "silent", ":", "true", ",", "}", ")", ".", "then", "(", "(", ")", "=>", "mkdir", "(", "env", ".", "dest", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "env", ".", "logger", ".", "log", "(", "`", "\\`", "${", "env", ".", "displayDest", "}", "\\`", "`", ")", "}", ")", ".", "catch", "(", "err", "=>", "{", "// Friendly error for already existing directory.", "throw", "new", "errors", ".", "SassDocError", "(", "err", ".", "message", ")", "}", ")", "}" ]
Safely wipe and re-create the destination directory. @return {Promise}
[ "Safely", "wipe", "and", "re", "-", "create", "the", "destination", "directory", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L90-L104
17,491
SassDoc/sassdoc
src/sassdoc.js
theme
function theme (env) { let promise = env.theme(env.dest, env) if (!is.promise(promise)) { let type = Object.prototype.toString.call(promise) throw new errors.Error(`Theme didn't return a promise, got ${type}.`) } return promise .then(() => { let displayTheme = env.displayTheme || 'anonymous' env.logger.log(`Theme \`${displayTheme}\` successfully rendered.`) }) }
javascript
function theme (env) { let promise = env.theme(env.dest, env) if (!is.promise(promise)) { let type = Object.prototype.toString.call(promise) throw new errors.Error(`Theme didn't return a promise, got ${type}.`) } return promise .then(() => { let displayTheme = env.displayTheme || 'anonymous' env.logger.log(`Theme \`${displayTheme}\` successfully rendered.`) }) }
[ "function", "theme", "(", "env", ")", "{", "let", "promise", "=", "env", ".", "theme", "(", "env", ".", "dest", ",", "env", ")", "if", "(", "!", "is", ".", "promise", "(", "promise", ")", ")", "{", "let", "type", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "promise", ")", "throw", "new", "errors", ".", "Error", "(", "`", "${", "type", "}", "`", ")", "}", "return", "promise", ".", "then", "(", "(", ")", "=>", "{", "let", "displayTheme", "=", "env", ".", "displayTheme", "||", "'anonymous'", "env", ".", "logger", ".", "log", "(", "`", "\\`", "${", "displayTheme", "}", "\\`", "`", ")", "}", ")", "}" ]
Render theme with parsed data context. @return {Promise}
[ "Render", "theme", "with", "parsed", "data", "context", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L110-L123
17,492
SassDoc/sassdoc
src/sassdoc.js
documentize
async function documentize (env) { init(env) let data = await baseDocumentize(env) try { await refresh(env) await theme(env) okay(env) } catch (err) { env.emit('error', err) throw err } return data }
javascript
async function documentize (env) { init(env) let data = await baseDocumentize(env) try { await refresh(env) await theme(env) okay(env) } catch (err) { env.emit('error', err) throw err } return data }
[ "async", "function", "documentize", "(", "env", ")", "{", "init", "(", "env", ")", "let", "data", "=", "await", "baseDocumentize", "(", "env", ")", "try", "{", "await", "refresh", "(", "env", ")", "await", "theme", "(", "env", ")", "okay", "(", "env", ")", "}", "catch", "(", "err", ")", "{", "env", ".", "emit", "(", "'error'", ",", "err", ")", "throw", "err", "}", "return", "data", "}" ]
Execute full SassDoc sequence from a source directory. @return {Promise}
[ "Execute", "full", "SassDoc", "sequence", "from", "a", "source", "directory", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L129-L143
17,493
SassDoc/sassdoc
src/sassdoc.js
stream
function stream (env) { let filter = parseFilter(env) filter.promise .then(data => { env.logger.log('Sass sources successfully parsed.') env.data = data onEmpty(data, env) }) /** * Returned Promise await the full sequence, * instead of just the parsing step. */ filter.promise = new Promise((resolve, reject) => { async function documentize () { try { init(env) await refresh(env) await theme(env) okay(env) resolve() } catch (err) { reject(err) env.emit('error', err) throw err } } filter .on('end', documentize) .on('error', err => env.emit('error', err)) .resume() // Drain. }) return filter }
javascript
function stream (env) { let filter = parseFilter(env) filter.promise .then(data => { env.logger.log('Sass sources successfully parsed.') env.data = data onEmpty(data, env) }) /** * Returned Promise await the full sequence, * instead of just the parsing step. */ filter.promise = new Promise((resolve, reject) => { async function documentize () { try { init(env) await refresh(env) await theme(env) okay(env) resolve() } catch (err) { reject(err) env.emit('error', err) throw err } } filter .on('end', documentize) .on('error', err => env.emit('error', err)) .resume() // Drain. }) return filter }
[ "function", "stream", "(", "env", ")", "{", "let", "filter", "=", "parseFilter", "(", "env", ")", "filter", ".", "promise", ".", "then", "(", "data", "=>", "{", "env", ".", "logger", ".", "log", "(", "'Sass sources successfully parsed.'", ")", "env", ".", "data", "=", "data", "onEmpty", "(", "data", ",", "env", ")", "}", ")", "/**\n * Returned Promise await the full sequence,\n * instead of just the parsing step.\n */", "filter", ".", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "async", "function", "documentize", "(", ")", "{", "try", "{", "init", "(", "env", ")", "await", "refresh", "(", "env", ")", "await", "theme", "(", "env", ")", "okay", "(", "env", ")", "resolve", "(", ")", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", "env", ".", "emit", "(", "'error'", ",", "err", ")", "throw", "err", "}", "}", "filter", ".", "on", "(", "'end'", ",", "documentize", ")", ".", "on", "(", "'error'", ",", "err", "=>", "env", ".", "emit", "(", "'error'", ",", "err", ")", ")", ".", "resume", "(", ")", "// Drain.", "}", ")", "return", "filter", "}" ]
Execute full SassDoc sequence from a Vinyl files stream. @return {Stream} @return {Promise} - as a property of Stream.
[ "Execute", "full", "SassDoc", "sequence", "from", "a", "Vinyl", "files", "stream", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L150-L188
17,494
SassDoc/sassdoc
src/sassdoc.js
stream
function stream (env) { let parseStream = parseFilter(env) let filter = through.obj((file, enc, cb) => cb(), function (cb) { parseStream.promise.then(data => { this.push(data) cb() }, cb) }) return pipe(parseStream, filter) }
javascript
function stream (env) { let parseStream = parseFilter(env) let filter = through.obj((file, enc, cb) => cb(), function (cb) { parseStream.promise.then(data => { this.push(data) cb() }, cb) }) return pipe(parseStream, filter) }
[ "function", "stream", "(", "env", ")", "{", "let", "parseStream", "=", "parseFilter", "(", "env", ")", "let", "filter", "=", "through", ".", "obj", "(", "(", "file", ",", "enc", ",", "cb", ")", "=>", "cb", "(", ")", ",", "function", "(", "cb", ")", "{", "parseStream", ".", "promise", ".", "then", "(", "data", "=>", "{", "this", ".", "push", "(", "data", ")", "cb", "(", ")", "}", ",", "cb", ")", "}", ")", "return", "pipe", "(", "parseStream", ",", "filter", ")", "}" ]
Don't pass files through, but pass final data at the end. @return {Stream}
[ "Don", "t", "pass", "files", "through", "but", "pass", "final", "data", "at", "the", "end", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L215-L226
17,495
SassDoc/sassdoc
src/sassdoc.js
baseDocumentize
async function baseDocumentize (env) { let filter = parseFilter(env) filter.promise .then(data => { env.logger.log(`Folder \`${env.src}\` successfully parsed.`) env.data = data onEmpty(data, env) env.logger.debug(() => { fs.writeFile( 'sassdoc-data.json', JSON.stringify(data, null, 2) + '\n', err => { if (err) throw err } ) return 'Dumping data to `sassdoc-data.json`.' }) }) let streams = [ vfs.src(env.src), recurse(), exclude(env.exclude || []), converter({ from: 'sass', to: 'scss' }), filter ] let pipeline = () => { return new Promise((resolve, reject) => { pipe(...streams, err => err ? reject(err) : resolve()) .resume() // Drain. }) } try { await pipeline() await filter.promise } catch (err) { env.emit('error', err) throw err } return env.data }
javascript
async function baseDocumentize (env) { let filter = parseFilter(env) filter.promise .then(data => { env.logger.log(`Folder \`${env.src}\` successfully parsed.`) env.data = data onEmpty(data, env) env.logger.debug(() => { fs.writeFile( 'sassdoc-data.json', JSON.stringify(data, null, 2) + '\n', err => { if (err) throw err } ) return 'Dumping data to `sassdoc-data.json`.' }) }) let streams = [ vfs.src(env.src), recurse(), exclude(env.exclude || []), converter({ from: 'sass', to: 'scss' }), filter ] let pipeline = () => { return new Promise((resolve, reject) => { pipe(...streams, err => err ? reject(err) : resolve()) .resume() // Drain. }) } try { await pipeline() await filter.promise } catch (err) { env.emit('error', err) throw err } return env.data }
[ "async", "function", "baseDocumentize", "(", "env", ")", "{", "let", "filter", "=", "parseFilter", "(", "env", ")", "filter", ".", "promise", ".", "then", "(", "data", "=>", "{", "env", ".", "logger", ".", "log", "(", "`", "\\`", "${", "env", ".", "src", "}", "\\`", "`", ")", "env", ".", "data", "=", "data", "onEmpty", "(", "data", ",", "env", ")", "env", ".", "logger", ".", "debug", "(", "(", ")", "=>", "{", "fs", ".", "writeFile", "(", "'sassdoc-data.json'", ",", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", "+", "'\\n'", ",", "err", "=>", "{", "if", "(", "err", ")", "throw", "err", "}", ")", "return", "'Dumping data to `sassdoc-data.json`.'", "}", ")", "}", ")", "let", "streams", "=", "[", "vfs", ".", "src", "(", "env", ".", "src", ")", ",", "recurse", "(", ")", ",", "exclude", "(", "env", ".", "exclude", "||", "[", "]", ")", ",", "converter", "(", "{", "from", ":", "'sass'", ",", "to", ":", "'scss'", "}", ")", ",", "filter", "]", "let", "pipeline", "=", "(", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "pipe", "(", "...", "streams", ",", "err", "=>", "err", "?", "reject", "(", "err", ")", ":", "resolve", "(", ")", ")", ".", "resume", "(", ")", "// Drain.", "}", ")", "}", "try", "{", "await", "pipeline", "(", ")", "await", "filter", ".", "promise", "}", "catch", "(", "err", ")", "{", "env", ".", "emit", "(", "'error'", ",", "err", ")", "throw", "err", "}", "return", "env", ".", "data", "}" ]
Source directory fetching and parsing.
[ "Source", "directory", "fetching", "and", "parsing", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L232-L279
17,496
SassDoc/sassdoc
src/sassdoc.js
onEmpty
function onEmpty (data, env) { let message = `SassDoc could not find anything to document.\n * Are you still using \`/**\` comments ? They're no more supported since 2.0. See <http://sassdoc.com/upgrading/#c-style-comments>.\n` if (!data.length && env.verbose) { env.emit('warning', new errors.Warning(message)) } }
javascript
function onEmpty (data, env) { let message = `SassDoc could not find anything to document.\n * Are you still using \`/**\` comments ? They're no more supported since 2.0. See <http://sassdoc.com/upgrading/#c-style-comments>.\n` if (!data.length && env.verbose) { env.emit('warning', new errors.Warning(message)) } }
[ "function", "onEmpty", "(", "data", ",", "env", ")", "{", "let", "message", "=", "`", "\\n", "\\`", "\\`", "\\n", "`", "if", "(", "!", "data", ".", "length", "&&", "env", ".", "verbose", ")", "{", "env", ".", "emit", "(", "'warning'", ",", "new", "errors", ".", "Warning", "(", "message", ")", ")", "}", "}" ]
Warn user on empty documentation. @param {Array} data @param {Object} env
[ "Warn", "user", "on", "empty", "documentation", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/sassdoc.js#L341-L349
17,497
SassDoc/sassdoc
src/cli.js
ensure
function ensure (env, options, names) { for (let k of Object.keys(names)) { let v = names[k] if (options[v]) { env[k] = options[v] env[k + 'Cwd'] = true } } }
javascript
function ensure (env, options, names) { for (let k of Object.keys(names)) { let v = names[k] if (options[v]) { env[k] = options[v] env[k + 'Cwd'] = true } } }
[ "function", "ensure", "(", "env", ",", "options", ",", "names", ")", "{", "for", "(", "let", "k", "of", "Object", ".", "keys", "(", "names", ")", ")", "{", "let", "v", "=", "names", "[", "k", "]", "if", "(", "options", "[", "v", "]", ")", "{", "env", "[", "k", "]", "=", "options", "[", "v", "]", "env", "[", "k", "+", "'Cwd'", "]", "=", "true", "}", "}", "}" ]
Ensure that CLI options take precedence over configuration values. For each name/option tuple, if the option is set, override configuration value.
[ "Ensure", "that", "CLI", "options", "take", "precedence", "over", "configuration", "values", "." ]
d34339d785e3a78cc1f61a98e268db49d61aa505
https://github.com/SassDoc/sassdoc/blob/d34339d785e3a78cc1f61a98e268db49d61aa505/src/cli.js#L94-L103
17,498
ruddell/ignite-jhipster
boilerplate/app/navigation/layouts.js
handleOpenURL
function handleOpenURL (event) { console.tron.log(event.url) let splitUrl = event.url.split('/') // ['https:', '', 'domain', 'route', 'params'] let importantParameters = splitUrl.splice(3) // ['route', 'params'] if (importantParameters.length === 0) { console.tron.log('Sending to home page') return null } if (importantParameters.length === 1) { switch (importantParameters[0]) { case 'register': console.tron.log(`Sending to Register Page`) registerScreen() break default: console.tron.warn(`Unhandled deep link: ${event.url}`) // default code block } } }
javascript
function handleOpenURL (event) { console.tron.log(event.url) let splitUrl = event.url.split('/') // ['https:', '', 'domain', 'route', 'params'] let importantParameters = splitUrl.splice(3) // ['route', 'params'] if (importantParameters.length === 0) { console.tron.log('Sending to home page') return null } if (importantParameters.length === 1) { switch (importantParameters[0]) { case 'register': console.tron.log(`Sending to Register Page`) registerScreen() break default: console.tron.warn(`Unhandled deep link: ${event.url}`) // default code block } } }
[ "function", "handleOpenURL", "(", "event", ")", "{", "console", ".", "tron", ".", "log", "(", "event", ".", "url", ")", "let", "splitUrl", "=", "event", ".", "url", ".", "split", "(", "'/'", ")", "// ['https:', '', 'domain', 'route', 'params']", "let", "importantParameters", "=", "splitUrl", ".", "splice", "(", "3", ")", "// ['route', 'params']", "if", "(", "importantParameters", ".", "length", "===", "0", ")", "{", "console", ".", "tron", ".", "log", "(", "'Sending to home page'", ")", "return", "null", "}", "if", "(", "importantParameters", ".", "length", "===", "1", ")", "{", "switch", "(", "importantParameters", "[", "0", "]", ")", "{", "case", "'register'", ":", "console", ".", "tron", ".", "log", "(", "`", "`", ")", "registerScreen", "(", ")", "break", "default", ":", "console", ".", "tron", ".", "warn", "(", "`", "${", "event", ".", "url", "}", "`", ")", "// default code block", "}", "}", "}" ]
for deep linking
[ "for", "deep", "linking" ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/boilerplate/app/navigation/layouts.js#L83-L102
17,499
ruddell/ignite-jhipster
src/boilerplate/index.js
mergePackageJsons
async function mergePackageJsons () { // transform our package.json incase we need to replace variables const rawJson = await template.generate({ directory: `${ignite.ignitePluginPath()}/boilerplate`, template: 'package.json.ejs', props: props }) const newPackageJson = JSON.parse(rawJson) // read in the react-native created package.json const currentPackage = filesystem.read('package.json', 'json') // deep merge, lol const newPackage = pipe( assoc( 'dependencies', merge(currentPackage.dependencies, newPackageJson.dependencies) ), assoc( 'devDependencies', merge(currentPackage.devDependencies, newPackageJson.devDependencies) ), assoc('scripts', merge(currentPackage.scripts, newPackageJson.scripts)), merge( __, omit(['dependencies', 'devDependencies', 'scripts'], newPackageJson) ) )(currentPackage) // write this out filesystem.write('package.json', newPackage, { jsonIndent: 2 }) }
javascript
async function mergePackageJsons () { // transform our package.json incase we need to replace variables const rawJson = await template.generate({ directory: `${ignite.ignitePluginPath()}/boilerplate`, template: 'package.json.ejs', props: props }) const newPackageJson = JSON.parse(rawJson) // read in the react-native created package.json const currentPackage = filesystem.read('package.json', 'json') // deep merge, lol const newPackage = pipe( assoc( 'dependencies', merge(currentPackage.dependencies, newPackageJson.dependencies) ), assoc( 'devDependencies', merge(currentPackage.devDependencies, newPackageJson.devDependencies) ), assoc('scripts', merge(currentPackage.scripts, newPackageJson.scripts)), merge( __, omit(['dependencies', 'devDependencies', 'scripts'], newPackageJson) ) )(currentPackage) // write this out filesystem.write('package.json', newPackage, { jsonIndent: 2 }) }
[ "async", "function", "mergePackageJsons", "(", ")", "{", "// transform our package.json incase we need to replace variables", "const", "rawJson", "=", "await", "template", ".", "generate", "(", "{", "directory", ":", "`", "${", "ignite", ".", "ignitePluginPath", "(", ")", "}", "`", ",", "template", ":", "'package.json.ejs'", ",", "props", ":", "props", "}", ")", "const", "newPackageJson", "=", "JSON", ".", "parse", "(", "rawJson", ")", "// read in the react-native created package.json", "const", "currentPackage", "=", "filesystem", ".", "read", "(", "'package.json'", ",", "'json'", ")", "// deep merge, lol", "const", "newPackage", "=", "pipe", "(", "assoc", "(", "'dependencies'", ",", "merge", "(", "currentPackage", ".", "dependencies", ",", "newPackageJson", ".", "dependencies", ")", ")", ",", "assoc", "(", "'devDependencies'", ",", "merge", "(", "currentPackage", ".", "devDependencies", ",", "newPackageJson", ".", "devDependencies", ")", ")", ",", "assoc", "(", "'scripts'", ",", "merge", "(", "currentPackage", ".", "scripts", ",", "newPackageJson", ".", "scripts", ")", ")", ",", "merge", "(", "__", ",", "omit", "(", "[", "'dependencies'", ",", "'devDependencies'", ",", "'scripts'", "]", ",", "newPackageJson", ")", ")", ")", "(", "currentPackage", ")", "// write this out", "filesystem", ".", "write", "(", "'package.json'", ",", "newPackage", ",", "{", "jsonIndent", ":", "2", "}", ")", "}" ]
Merge the package.json from our template into the one provided from react-native init.
[ "Merge", "the", "package", ".", "json", "from", "our", "template", "into", "the", "one", "provided", "from", "react", "-", "native", "init", "." ]
301c3aa9e4286715b0f5ad6f32f516672ea8d09d
https://github.com/ruddell/ignite-jhipster/blob/301c3aa9e4286715b0f5ad6f32f516672ea8d09d/src/boilerplate/index.js#L144-L175