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
partition
stringclasses
1 value
rollup/rollup
rollup.config.js
fixAcornEsmImport
function fixAcornEsmImport() { return { name: 'fix-acorn-esm-import', renderChunk(code, chunk, options) { if (/esm?/.test(options.format)) { let found = false; const fixedCode = code.replace(expectedAcornImport, () => { found = true; return newAcornImport; }); if (!found) { this.error( 'Could not find expected acorn import, please deactive this plugin and examine generated code.' ); } return fixedCode; } } }; }
javascript
function fixAcornEsmImport() { return { name: 'fix-acorn-esm-import', renderChunk(code, chunk, options) { if (/esm?/.test(options.format)) { let found = false; const fixedCode = code.replace(expectedAcornImport, () => { found = true; return newAcornImport; }); if (!found) { this.error( 'Could not find expected acorn import, please deactive this plugin and examine generated code.' ); } return fixedCode; } } }; }
[ "function", "fixAcornEsmImport", "(", ")", "{", "return", "{", "name", ":", "'fix-acorn-esm-import'", ",", "renderChunk", "(", "code", ",", "chunk", ",", "options", ")", "{", "if", "(", "/", "esm?", "/", ".", "test", "(", "options", ".", "format", ")", ")", "{", "let", "found", "=", "false", ";", "const", "fixedCode", "=", "code", ".", "replace", "(", "expectedAcornImport", ",", "(", ")", "=>", "{", "found", "=", "true", ";", "return", "newAcornImport", ";", "}", ")", ";", "if", "(", "!", "found", ")", "{", "this", ".", "error", "(", "'Could not find expected acorn import, please deactive this plugin and examine generated code.'", ")", ";", "}", "return", "fixedCode", ";", "}", "}", "}", ";", "}" ]
by default, rollup-plugin-commonjs will translate require statements as default imports which can cause issues for secondary tools that use the ESM version of acorn
[ "by", "default", "rollup", "-", "plugin", "-", "commonjs", "will", "translate", "require", "statements", "as", "default", "imports", "which", "can", "cause", "issues", "for", "secondary", "tools", "that", "use", "the", "ESM", "version", "of", "acorn" ]
7d669ebc19b8feb6a8a61fb84b95ea8df650dde1
https://github.com/rollup/rollup/blob/7d669ebc19b8feb6a8a61fb84b95ea8df650dde1/rollup.config.js#L49-L68
train
ipfs/js-ipfs
src/core/utils.js
parseIpfsPath
function parseIpfsPath (ipfsPath) { const invalidPathErr = new Error('invalid ipfs ref path') ipfsPath = ipfsPath.replace(/^\/ipfs\//, '') const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/) if (!matched) { throw invalidPathErr } const [hash, ...links] = matched[1].split('/') // check that a CID can be constructed with the hash if (isIpfs.cid(hash)) { return { hash, links } } else { throw invalidPathErr } }
javascript
function parseIpfsPath (ipfsPath) { const invalidPathErr = new Error('invalid ipfs ref path') ipfsPath = ipfsPath.replace(/^\/ipfs\//, '') const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/) if (!matched) { throw invalidPathErr } const [hash, ...links] = matched[1].split('/') // check that a CID can be constructed with the hash if (isIpfs.cid(hash)) { return { hash, links } } else { throw invalidPathErr } }
[ "function", "parseIpfsPath", "(", "ipfsPath", ")", "{", "const", "invalidPathErr", "=", "new", "Error", "(", "'invalid ipfs ref path'", ")", "ipfsPath", "=", "ipfsPath", ".", "replace", "(", "/", "^\\/ipfs\\/", "/", ",", "''", ")", "const", "matched", "=", "ipfsPath", ".", "match", "(", "/", "([^/]+(?:\\/[^/]+)*)\\/?$", "/", ")", "if", "(", "!", "matched", ")", "{", "throw", "invalidPathErr", "}", "const", "[", "hash", ",", "...", "links", "]", "=", "matched", "[", "1", "]", ".", "split", "(", "'/'", ")", "if", "(", "isIpfs", ".", "cid", "(", "hash", ")", ")", "{", "return", "{", "hash", ",", "links", "}", "}", "else", "{", "throw", "invalidPathErr", "}", "}" ]
Break an ipfs-path down into it's hash and an array of links. examples: b58Hash -> { hash: 'b58Hash', links: [] } b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']} /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] } @param {String} ipfsPath An ipfs-path @return {Object} { hash: base58 string, links: [string], ?err: Error } @throws on an invalid @param ipfsPath
[ "Break", "an", "ipfs", "-", "path", "down", "into", "it", "s", "hash", "and", "an", "array", "of", "links", "." ]
97e67601094acda3906549ecb0248fd09f1a8cc3
https://github.com/ipfs/js-ipfs/blob/97e67601094acda3906549ecb0248fd09f1a8cc3/src/core/utils.js#L23-L39
train
ipfs/js-ipfs
src/core/utils.js
follow
function follow (cid, links, err, obj) { if (err) { return cb(err) } if (!links.length) { // done tracing, obj is the target node return cb(null, cid.buffer) } const linkName = links[0] const nextObj = obj.links.find(link => link.name === linkName) if (!nextObj) { return cb(new Error( `no link named "${linkName}" under ${cid.toBaseEncodedString()}` )) } objectAPI.get(nextObj.cid, follow.bind(null, nextObj.cid, links.slice(1))) }
javascript
function follow (cid, links, err, obj) { if (err) { return cb(err) } if (!links.length) { // done tracing, obj is the target node return cb(null, cid.buffer) } const linkName = links[0] const nextObj = obj.links.find(link => link.name === linkName) if (!nextObj) { return cb(new Error( `no link named "${linkName}" under ${cid.toBaseEncodedString()}` )) } objectAPI.get(nextObj.cid, follow.bind(null, nextObj.cid, links.slice(1))) }
[ "function", "follow", "(", "cid", ",", "links", ",", "err", ",", "obj", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", "}", "if", "(", "!", "links", ".", "length", ")", "{", "return", "cb", "(", "null", ",", "cid", ".", "buffer", ")", "}", "const", "linkName", "=", "links", "[", "0", "]", "const", "nextObj", "=", "obj", ".", "links", ".", "find", "(", "link", "=>", "link", ".", "name", "===", "linkName", ")", "if", "(", "!", "nextObj", ")", "{", "return", "cb", "(", "new", "Error", "(", "`", "${", "linkName", "}", "${", "cid", ".", "toBaseEncodedString", "(", ")", "}", "`", ")", ")", "}", "objectAPI", ".", "get", "(", "nextObj", ".", "cid", ",", "follow", ".", "bind", "(", "null", ",", "nextObj", ".", "cid", ",", "links", ".", "slice", "(", "1", ")", ")", ")", "}" ]
recursively follow named links to the target node
[ "recursively", "follow", "named", "links", "to", "the", "target", "node" ]
97e67601094acda3906549ecb0248fd09f1a8cc3
https://github.com/ipfs/js-ipfs/blob/97e67601094acda3906549ecb0248fd09f1a8cc3/src/core/utils.js#L116-L135
train
ipfs/js-ipfs
src/core/components/files-regular/utils.js
parseRabinString
function parseRabinString (chunker) { const options = {} const parts = chunker.split('-') switch (parts.length) { case 1: options.avgChunkSize = 262144 break case 2: options.avgChunkSize = parseChunkSize(parts[1], 'avg') break case 4: options.minChunkSize = parseChunkSize(parts[1], 'min') options.avgChunkSize = parseChunkSize(parts[2], 'avg') options.maxChunkSize = parseChunkSize(parts[3], 'max') break default: throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"') } return options }
javascript
function parseRabinString (chunker) { const options = {} const parts = chunker.split('-') switch (parts.length) { case 1: options.avgChunkSize = 262144 break case 2: options.avgChunkSize = parseChunkSize(parts[1], 'avg') break case 4: options.minChunkSize = parseChunkSize(parts[1], 'min') options.avgChunkSize = parseChunkSize(parts[2], 'avg') options.maxChunkSize = parseChunkSize(parts[3], 'max') break default: throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"') } return options }
[ "function", "parseRabinString", "(", "chunker", ")", "{", "const", "options", "=", "{", "}", "const", "parts", "=", "chunker", ".", "split", "(", "'-'", ")", "switch", "(", "parts", ".", "length", ")", "{", "case", "1", ":", "options", ".", "avgChunkSize", "=", "262144", "break", "case", "2", ":", "options", ".", "avgChunkSize", "=", "parseChunkSize", "(", "parts", "[", "1", "]", ",", "'avg'", ")", "break", "case", "4", ":", "options", ".", "minChunkSize", "=", "parseChunkSize", "(", "parts", "[", "1", "]", ",", "'min'", ")", "options", ".", "avgChunkSize", "=", "parseChunkSize", "(", "parts", "[", "2", "]", ",", "'avg'", ")", "options", ".", "maxChunkSize", "=", "parseChunkSize", "(", "parts", "[", "3", "]", ",", "'max'", ")", "break", "default", ":", "throw", "new", "Error", "(", "'Incorrect chunker format (expected \"rabin\" \"rabin-[avg]\" or \"rabin-[min]-[avg]-[max]\"'", ")", "}", "return", "options", "}" ]
Parses rabin chunker string @param {String} chunker Chunker algorithm supported formats: "rabin" "rabin-{avg}" "rabin-{min}-{avg}-{max}" @return {Object} rabin chunker options
[ "Parses", "rabin", "chunker", "string" ]
97e67601094acda3906549ecb0248fd09f1a8cc3
https://github.com/ipfs/js-ipfs/blob/97e67601094acda3906549ecb0248fd09f1a8cc3/src/core/components/files-regular/utils.js#L70-L90
train
ipfs/js-ipfs
src/core/components/resolve.js
resolve
function resolve (cid, path, callback) { let value, remainderPath doUntil( (cb) => { self.block.get(cid, (err, block) => { if (err) return cb(err) const r = self._ipld.resolvers[cid.codec] if (!r) { return cb(new Error(`No resolver found for codec "${cid.codec}"`)) } r.resolver.resolve(block.data, path, (err, result) => { if (err) return cb(err) value = result.value remainderPath = result.remainderPath cb() }) }) }, () => { if (value && value['/']) { // If we've hit a CID, replace the current CID. cid = new CID(value['/']) path = remainderPath } else if (CID.isCID(value)) { // If we've hit a CID, replace the current CID. cid = value path = remainderPath } else { // We've hit a value. Return the current CID and the remaining path. return true } // Continue resolving unless the path is empty. return !path || path === '/' }, (err) => { if (err) return callback(err) callback(null, { cid, remainderPath: path }) } ) }
javascript
function resolve (cid, path, callback) { let value, remainderPath doUntil( (cb) => { self.block.get(cid, (err, block) => { if (err) return cb(err) const r = self._ipld.resolvers[cid.codec] if (!r) { return cb(new Error(`No resolver found for codec "${cid.codec}"`)) } r.resolver.resolve(block.data, path, (err, result) => { if (err) return cb(err) value = result.value remainderPath = result.remainderPath cb() }) }) }, () => { if (value && value['/']) { // If we've hit a CID, replace the current CID. cid = new CID(value['/']) path = remainderPath } else if (CID.isCID(value)) { // If we've hit a CID, replace the current CID. cid = value path = remainderPath } else { // We've hit a value. Return the current CID and the remaining path. return true } // Continue resolving unless the path is empty. return !path || path === '/' }, (err) => { if (err) return callback(err) callback(null, { cid, remainderPath: path }) } ) }
[ "function", "resolve", "(", "cid", ",", "path", ",", "callback", ")", "{", "let", "value", ",", "remainderPath", "doUntil", "(", "(", "cb", ")", "=>", "{", "self", ".", "block", ".", "get", "(", "cid", ",", "(", "err", ",", "block", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "const", "r", "=", "self", ".", "_ipld", ".", "resolvers", "[", "cid", ".", "codec", "]", "if", "(", "!", "r", ")", "{", "return", "cb", "(", "new", "Error", "(", "`", "${", "cid", ".", "codec", "}", "`", ")", ")", "}", "r", ".", "resolver", ".", "resolve", "(", "block", ".", "data", ",", "path", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "value", "=", "result", ".", "value", "remainderPath", "=", "result", ".", "remainderPath", "cb", "(", ")", "}", ")", "}", ")", "}", ",", "(", ")", "=>", "{", "if", "(", "value", "&&", "value", "[", "'/'", "]", ")", "{", "cid", "=", "new", "CID", "(", "value", "[", "'/'", "]", ")", "path", "=", "remainderPath", "}", "else", "if", "(", "CID", ".", "isCID", "(", "value", ")", ")", "{", "cid", "=", "value", "path", "=", "remainderPath", "}", "else", "{", "return", "true", "}", "return", "!", "path", "||", "path", "===", "'/'", "}", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "callback", "(", "null", ",", "{", "cid", ",", "remainderPath", ":", "path", "}", ")", "}", ")", "}" ]
Resolve the given CID + path to a CID.
[ "Resolve", "the", "given", "CID", "+", "path", "to", "a", "CID", "." ]
97e67601094acda3906549ecb0248fd09f1a8cc3
https://github.com/ipfs/js-ipfs/blob/97e67601094acda3906549ecb0248fd09f1a8cc3/src/core/components/resolve.js#L45-L88
train
angular/protractor
website/docgen/processors/add-links.js
function(doc) { // Heuristic for the custom docs in the lib/selenium-webdriver/ folder. if (doc.name && doc.name.startsWith('webdriver')) { return; } var template = _.template('https://github.com/angular/protractor/blob/' + '<%= linksHash %>/lib/<%= fileName %>.ts'); doc.sourceLink = template({ linksHash: linksHash, fileName: doc.fileName }); }
javascript
function(doc) { // Heuristic for the custom docs in the lib/selenium-webdriver/ folder. if (doc.name && doc.name.startsWith('webdriver')) { return; } var template = _.template('https://github.com/angular/protractor/blob/' + '<%= linksHash %>/lib/<%= fileName %>.ts'); doc.sourceLink = template({ linksHash: linksHash, fileName: doc.fileName }); }
[ "function", "(", "doc", ")", "{", "if", "(", "doc", ".", "name", "&&", "doc", ".", "name", ".", "startsWith", "(", "'webdriver'", ")", ")", "{", "return", ";", "}", "var", "template", "=", "_", ".", "template", "(", "'https://github.com/angular/protractor/blob/'", "+", "'<%= linksHash %>/lib/<%= fileName %>.ts'", ")", ";", "doc", ".", "sourceLink", "=", "template", "(", "{", "linksHash", ":", "linksHash", ",", "fileName", ":", "doc", ".", "fileName", "}", ")", ";", "}" ]
Add a link to the source code. @param {!Object} doc Current document.
[ "Add", "a", "link", "to", "the", "source", "code", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/add-links.js#L24-L36
train
angular/protractor
website/docgen/processors/add-links.js
function(str, doc) { var oldStr = null; while (str != oldStr) { oldStr = str; var matches = /{\s*@link[plain]*\s+([^]+?)\s*}/.exec(str); if (matches) { var str = str.replace( new RegExp('{\\s*@link[plain]*\\s+' + matches[1].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\\s*}'), toMarkdownLinkFormat(matches[1], doc, matches[0].indexOf('linkplain') == -1) ); } } return str; }
javascript
function(str, doc) { var oldStr = null; while (str != oldStr) { oldStr = str; var matches = /{\s*@link[plain]*\s+([^]+?)\s*}/.exec(str); if (matches) { var str = str.replace( new RegExp('{\\s*@link[plain]*\\s+' + matches[1].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\\s*}'), toMarkdownLinkFormat(matches[1], doc, matches[0].indexOf('linkplain') == -1) ); } } return str; }
[ "function", "(", "str", ",", "doc", ")", "{", "var", "oldStr", "=", "null", ";", "while", "(", "str", "!=", "oldStr", ")", "{", "oldStr", "=", "str", ";", "var", "matches", "=", "/", "{\\s*@link[plain]*\\s+([^]+?)\\s*}", "/", ".", "exec", "(", "str", ")", ";", "if", "(", "matches", ")", "{", "var", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "'{\\\\s*@link[plain]*\\\\s+'", "+", "\\\\", "+", "\\\\", ")", ",", "matches", "[", "1", "]", ".", "replace", "(", "/", "[-\\/\\\\^$*+?.()|[\\]{}]", "/", "g", ",", "'\\\\$&'", ")", ")", ";", "}", "}", "\\\\", "}" ]
Add links to @link annotations. For example: `{@link foo.bar}` will be transformed into `[foo.bar](foo.bar)` and `{@link foo.bar FooBar Link}` will be transfirned into `[FooBar Link](foo.bar)` @param {string} str The string with the annotations. @param {!Object} doc Current document. @return {string} A link in markdown format.
[ "Add", "links", "to" ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/add-links.js#L46-L61
train
angular/protractor
website/docgen/processors/add-links.js
function(param) { var str = param.typeExpression; var type = param.type; if (!type) { return escape(str); } var replaceWithLinkIfPresent = function(type) { if (type.name) { str = str.replace(type.name, toMarkdownLinkFormat(type.name)); } }; if (type.type === 'FunctionType') { _.each(type.params, replaceWithLinkIfPresent); } else if (type.type === 'TypeApplication') { // Is this an Array.<type>? var match = str.match(/Array\.<(.*)>/); if (match) { var typeInsideArray = match[1]; str = str.replace(typeInsideArray, toMarkdownLinkFormat(typeInsideArray)); } } else if (type.type === 'NameExpression') { replaceWithLinkIfPresent(type); } return escape(str); }
javascript
function(param) { var str = param.typeExpression; var type = param.type; if (!type) { return escape(str); } var replaceWithLinkIfPresent = function(type) { if (type.name) { str = str.replace(type.name, toMarkdownLinkFormat(type.name)); } }; if (type.type === 'FunctionType') { _.each(type.params, replaceWithLinkIfPresent); } else if (type.type === 'TypeApplication') { // Is this an Array.<type>? var match = str.match(/Array\.<(.*)>/); if (match) { var typeInsideArray = match[1]; str = str.replace(typeInsideArray, toMarkdownLinkFormat(typeInsideArray)); } } else if (type.type === 'NameExpression') { replaceWithLinkIfPresent(type); } return escape(str); }
[ "function", "(", "param", ")", "{", "var", "str", "=", "param", ".", "typeExpression", ";", "var", "type", "=", "param", ".", "type", ";", "if", "(", "!", "type", ")", "{", "return", "escape", "(", "str", ")", ";", "}", "var", "replaceWithLinkIfPresent", "=", "function", "(", "type", ")", "{", "if", "(", "type", ".", "name", ")", "{", "str", "=", "str", ".", "replace", "(", "type", ".", "name", ",", "toMarkdownLinkFormat", "(", "type", ".", "name", ")", ")", ";", "}", "}", ";", "if", "(", "type", ".", "type", "===", "'FunctionType'", ")", "{", "_", ".", "each", "(", "type", ".", "params", ",", "replaceWithLinkIfPresent", ")", ";", "}", "else", "if", "(", "type", ".", "type", "===", "'TypeApplication'", ")", "{", "var", "match", "=", "str", ".", "match", "(", "/", "Array\\.<(.*)>", "/", ")", ";", "if", "(", "match", ")", "{", "var", "typeInsideArray", "=", "match", "[", "1", "]", ";", "str", "=", "str", ".", "replace", "(", "typeInsideArray", ",", "toMarkdownLinkFormat", "(", "typeInsideArray", ")", ")", ";", "}", "}", "else", "if", "(", "type", ".", "type", "===", "'NameExpression'", ")", "{", "replaceWithLinkIfPresent", "(", "type", ")", ";", "}", "return", "escape", "(", "str", ")", ";", "}" ]
Create the param or return type. @param {!Object} param Parameter. @return {string} Escaped param string with links to the types.
[ "Create", "the", "param", "or", "return", "type", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/add-links.js#L128-L155
train
angular/protractor
website/js/api-controller.js
function(item) { var parts = item.displayName.split('.'); for (var i = parts.length - 1; i > 0; i--) { var name = parts.slice(0, i).join('.'); if (itemsByName[name]) { return itemsByName[name]; } } }
javascript
function(item) { var parts = item.displayName.split('.'); for (var i = parts.length - 1; i > 0; i--) { var name = parts.slice(0, i).join('.'); if (itemsByName[name]) { return itemsByName[name]; } } }
[ "function", "(", "item", ")", "{", "var", "parts", "=", "item", ".", "displayName", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "parts", ".", "length", "-", "1", ";", "i", ">", "0", ";", "i", "--", ")", "{", "var", "name", "=", "parts", ".", "slice", "(", "0", ",", "i", ")", ".", "join", "(", "'.'", ")", ";", "if", "(", "itemsByName", "[", "name", "]", ")", "{", "return", "itemsByName", "[", "name", "]", ";", "}", "}", "}" ]
Try to find a parent by matching the longest substring of the display name. @param item
[ "Try", "to", "find", "a", "parent", "by", "matching", "the", "longest", "substring", "of", "the", "display", "name", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/js/api-controller.js#L161-L169
train
angular/protractor
website/docgen/processors/tag-fixer.js
function(doc) { // Skip if the function has a name. if (doc.name) { return doc.name; } try { var node = doc.codeNode; // Is this a simple declaration? "var element = function() {". if (node.declarations && node.declarations.length) { return node.declarations[0].id.name; } // Is this an expression? "elementFinder.find = function() {". if (node.expression) { var parts = []; /** * Recursively create the function name by examining the object property. * @param obj Parsed object. * @return {string} The name of the function. */ function buildName(obj) { if (!obj) { return parts.join('.'); } if (obj.property && obj.property.name) { parts.unshift(obj.property.name); } if (obj.object && obj.object.name) { parts.unshift(obj.object.name); } return buildName(obj.object); } return buildName(node.expression.left); } } catch (e) { console.log('Could not find document name', doc.file, doc.endingLine); } }
javascript
function(doc) { // Skip if the function has a name. if (doc.name) { return doc.name; } try { var node = doc.codeNode; // Is this a simple declaration? "var element = function() {". if (node.declarations && node.declarations.length) { return node.declarations[0].id.name; } // Is this an expression? "elementFinder.find = function() {". if (node.expression) { var parts = []; /** * Recursively create the function name by examining the object property. * @param obj Parsed object. * @return {string} The name of the function. */ function buildName(obj) { if (!obj) { return parts.join('.'); } if (obj.property && obj.property.name) { parts.unshift(obj.property.name); } if (obj.object && obj.object.name) { parts.unshift(obj.object.name); } return buildName(obj.object); } return buildName(node.expression.left); } } catch (e) { console.log('Could not find document name', doc.file, doc.endingLine); } }
[ "function", "(", "doc", ")", "{", "if", "(", "doc", ".", "name", ")", "{", "return", "doc", ".", "name", ";", "}", "try", "{", "var", "node", "=", "doc", ".", "codeNode", ";", "if", "(", "node", ".", "declarations", "&&", "node", ".", "declarations", ".", "length", ")", "{", "return", "node", ".", "declarations", "[", "0", "]", ".", "id", ".", "name", ";", "}", "if", "(", "node", ".", "expression", ")", "{", "var", "parts", "=", "[", "]", ";", "function", "buildName", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "{", "return", "parts", ".", "join", "(", "'.'", ")", ";", "}", "if", "(", "obj", ".", "property", "&&", "obj", ".", "property", ".", "name", ")", "{", "parts", ".", "unshift", "(", "obj", ".", "property", ".", "name", ")", ";", "}", "if", "(", "obj", ".", "object", "&&", "obj", ".", "object", ".", "name", ")", "{", "parts", ".", "unshift", "(", "obj", ".", "object", ".", "name", ")", ";", "}", "return", "buildName", "(", "obj", ".", "object", ")", ";", "}", "return", "buildName", "(", "node", ".", "expression", ".", "left", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Could not find document name'", ",", "doc", ".", "file", ",", "doc", ".", "endingLine", ")", ";", "}", "}" ]
Find the name of the function.
[ "Find", "the", "name", "of", "the", "function", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/tag-fixer.js#L16-L60
train
angular/protractor
website/docgen/processors/tag-fixer.js
buildName
function buildName(obj) { if (!obj) { return parts.join('.'); } if (obj.property && obj.property.name) { parts.unshift(obj.property.name); } if (obj.object && obj.object.name) { parts.unshift(obj.object.name); } return buildName(obj.object); }
javascript
function buildName(obj) { if (!obj) { return parts.join('.'); } if (obj.property && obj.property.name) { parts.unshift(obj.property.name); } if (obj.object && obj.object.name) { parts.unshift(obj.object.name); } return buildName(obj.object); }
[ "function", "buildName", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "{", "return", "parts", ".", "join", "(", "'.'", ")", ";", "}", "if", "(", "obj", ".", "property", "&&", "obj", ".", "property", ".", "name", ")", "{", "parts", ".", "unshift", "(", "obj", ".", "property", ".", "name", ")", ";", "}", "if", "(", "obj", ".", "object", "&&", "obj", ".", "object", ".", "name", ")", "{", "parts", ".", "unshift", "(", "obj", ".", "object", ".", "name", ")", ";", "}", "return", "buildName", "(", "obj", ".", "object", ")", ";", "}" ]
Recursively create the function name by examining the object property. @param obj Parsed object. @return {string} The name of the function.
[ "Recursively", "create", "the", "function", "name", "by", "examining", "the", "object", "property", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/tag-fixer.js#L39-L53
train
angular/protractor
website/docgen/processors/tag-fixer.js
function(doc) { if (doc.params) { _.each(doc.params, function(param) { replaceNewLines(param, 'description'); }); } // Replace new lines in the return and params descriptions. var returns = doc.returns; if (returns) { replaceNewLines(returns, 'description'); } }
javascript
function(doc) { if (doc.params) { _.each(doc.params, function(param) { replaceNewLines(param, 'description'); }); } // Replace new lines in the return and params descriptions. var returns = doc.returns; if (returns) { replaceNewLines(returns, 'description'); } }
[ "function", "(", "doc", ")", "{", "if", "(", "doc", ".", "params", ")", "{", "_", ".", "each", "(", "doc", ".", "params", ",", "function", "(", "param", ")", "{", "replaceNewLines", "(", "param", ",", "'description'", ")", ";", "}", ")", ";", "}", "var", "returns", "=", "doc", ".", "returns", ";", "if", "(", "returns", ")", "{", "replaceNewLines", "(", "returns", ",", "'description'", ")", ";", "}", "}" ]
Remove the duplicate param annotations. Go through the params and the return annotations to replace the new lines and escape the types to prepare them for markdown rendering. @param {!Object} doc Document representing a function jsdoc.
[ "Remove", "the", "duplicate", "param", "annotations", ".", "Go", "through", "the", "params", "and", "the", "return", "annotations", "to", "replace", "the", "new", "lines", "and", "escape", "the", "types", "to", "prepare", "them", "for", "markdown", "rendering", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/website/docgen/processors/tag-fixer.js#L80-L92
train
angular/protractor
lib/clientsidescripts.js
function(callback) { if (window.angular) { var hooks = getNg1Hooks(rootSelector); if (!hooks){ callback(); // not an angular1 app } else{ if (hooks.$$testability) { hooks.$$testability.whenStable(callback); } else if (hooks.$injector) { hooks.$injector.get('$browser') .notifyWhenNoOutstandingRequests(callback); } else if (!rootSelector) { throw new Error( 'Could not automatically find injector on page: "' + window.location.toString() + '". Consider using config.rootEl'); } else { throw new Error( 'root element (' + rootSelector + ') has no injector.' + ' this may mean it is not inside ng-app.'); } } } else {callback();} // not an angular1 app }
javascript
function(callback) { if (window.angular) { var hooks = getNg1Hooks(rootSelector); if (!hooks){ callback(); // not an angular1 app } else{ if (hooks.$$testability) { hooks.$$testability.whenStable(callback); } else if (hooks.$injector) { hooks.$injector.get('$browser') .notifyWhenNoOutstandingRequests(callback); } else if (!rootSelector) { throw new Error( 'Could not automatically find injector on page: "' + window.location.toString() + '". Consider using config.rootEl'); } else { throw new Error( 'root element (' + rootSelector + ') has no injector.' + ' this may mean it is not inside ng-app.'); } } } else {callback();} // not an angular1 app }
[ "function", "(", "callback", ")", "{", "if", "(", "window", ".", "angular", ")", "{", "var", "hooks", "=", "getNg1Hooks", "(", "rootSelector", ")", ";", "if", "(", "!", "hooks", ")", "{", "callback", "(", ")", ";", "}", "else", "{", "if", "(", "hooks", ".", "$$testability", ")", "{", "hooks", ".", "$$testability", ".", "whenStable", "(", "callback", ")", ";", "}", "else", "if", "(", "hooks", ".", "$injector", ")", "{", "hooks", ".", "$injector", ".", "get", "(", "'$browser'", ")", ".", "notifyWhenNoOutstandingRequests", "(", "callback", ")", ";", "}", "else", "if", "(", "!", "rootSelector", ")", "{", "throw", "new", "Error", "(", "'Could not automatically find injector on page: \"'", "+", "window", ".", "location", ".", "toString", "(", ")", "+", "'\". Consider using config.rootEl'", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'root element ('", "+", "rootSelector", "+", "') has no injector.'", "+", "' this may mean it is not inside ng-app.'", ")", ";", "}", "}", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
Wait for angular1 testability first and run waitForAngular2 as a callback
[ "Wait", "for", "angular1", "testability", "first", "and", "run", "waitForAngular2", "as", "a", "callback" ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/lib/clientsidescripts.js#L143-L168
train
angular/protractor
lib/clientsidescripts.js
function() { if (window.getAngularTestability) { if (rootSelector) { var testability = null; var el = document.querySelector(rootSelector); try{ testability = window.getAngularTestability(el); } catch(e){} if (testability) { testability.whenStable(testCallback); return; } } // Didn't specify root element or testability could not be found // by rootSelector. This may happen in a hybrid app, which could have // more than one root. var testabilities = window.getAllAngularTestabilities(); var count = testabilities.length; // No angular2 testability, this happens when // going to a hybrid page and going back to a pure angular1 page if (count === 0) { testCallback(); return; } var decrement = function() { count--; if (count === 0) { testCallback(); } }; testabilities.forEach(function(testability) { testability.whenStable(decrement); }); } else {testCallback();} // not an angular2 app }
javascript
function() { if (window.getAngularTestability) { if (rootSelector) { var testability = null; var el = document.querySelector(rootSelector); try{ testability = window.getAngularTestability(el); } catch(e){} if (testability) { testability.whenStable(testCallback); return; } } // Didn't specify root element or testability could not be found // by rootSelector. This may happen in a hybrid app, which could have // more than one root. var testabilities = window.getAllAngularTestabilities(); var count = testabilities.length; // No angular2 testability, this happens when // going to a hybrid page and going back to a pure angular1 page if (count === 0) { testCallback(); return; } var decrement = function() { count--; if (count === 0) { testCallback(); } }; testabilities.forEach(function(testability) { testability.whenStable(decrement); }); } else {testCallback();} // not an angular2 app }
[ "function", "(", ")", "{", "if", "(", "window", ".", "getAngularTestability", ")", "{", "if", "(", "rootSelector", ")", "{", "var", "testability", "=", "null", ";", "var", "el", "=", "document", ".", "querySelector", "(", "rootSelector", ")", ";", "try", "{", "testability", "=", "window", ".", "getAngularTestability", "(", "el", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "if", "(", "testability", ")", "{", "testability", ".", "whenStable", "(", "testCallback", ")", ";", "return", ";", "}", "}", "var", "testabilities", "=", "window", ".", "getAllAngularTestabilities", "(", ")", ";", "var", "count", "=", "testabilities", ".", "length", ";", "if", "(", "count", "===", "0", ")", "{", "testCallback", "(", ")", ";", "return", ";", "}", "var", "decrement", "=", "function", "(", ")", "{", "count", "--", ";", "if", "(", "count", "===", "0", ")", "{", "testCallback", "(", ")", ";", "}", "}", ";", "testabilities", ".", "forEach", "(", "function", "(", "testability", ")", "{", "testability", ".", "whenStable", "(", "decrement", ")", ";", "}", ")", ";", "}", "else", "{", "testCallback", "(", ")", ";", "}", "}" ]
Wait for Angular2 testability and then run test callback
[ "Wait", "for", "Angular2", "testability", "and", "then", "run", "test", "callback" ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/lib/clientsidescripts.js#L171-L211
train
angular/protractor
lib/clientsidescripts.js
findRepeaterRows
function findRepeaterRows(repeater, exact, index, using) { using = using || document; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; var rows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } /* multiRows is an array of arrays, where each inner array contains one row of elements. */ var multiRows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { row.push(elem); } elem = elem.nextSibling; } multiRows.push(row); } } } var row = rows[index] || [], multiRow = multiRows[index] || []; return [].concat(row, multiRow); }
javascript
function findRepeaterRows(repeater, exact, index, using) { using = using || document; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; var rows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } /* multiRows is an array of arrays, where each inner array contains one row of elements. */ var multiRows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { row.push(elem); } elem = elem.nextSibling; } multiRows.push(row); } } } var row = rows[index] || [], multiRow = multiRows[index] || []; return [].concat(row, multiRow); }
[ "function", "findRepeaterRows", "(", "repeater", ",", "exact", ",", "index", ",", "using", ")", "{", "using", "=", "using", "||", "document", ";", "var", "prefixes", "=", "[", "'ng-'", ",", "'ng_'", ",", "'data-ng-'", ",", "'x-ng-'", ",", "'ng\\\\:'", "]", ";", "\\\\", "var", "rows", "=", "[", "]", ";", "for", "(", "var", "p", "=", "0", ";", "p", "<", "prefixes", ".", "length", ";", "++", "p", ")", "{", "var", "attr", "=", "prefixes", "[", "p", "]", "+", "'repeat'", ";", "var", "repeatElems", "=", "using", ".", "querySelectorAll", "(", "'['", "+", "attr", "+", "']'", ")", ";", "attr", "=", "attr", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "''", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "repeatElems", ".", "length", ";", "++", "i", ")", "{", "if", "(", "repeaterMatch", "(", "repeatElems", "[", "i", "]", ".", "getAttribute", "(", "attr", ")", ",", "repeater", ",", "exact", ")", ")", "{", "rows", ".", "push", "(", "repeatElems", "[", "i", "]", ")", ";", "}", "}", "}", "var", "multiRows", "=", "[", "]", ";", "for", "(", "var", "p", "=", "0", ";", "p", "<", "prefixes", ".", "length", ";", "++", "p", ")", "{", "var", "attr", "=", "prefixes", "[", "p", "]", "+", "'repeat-start'", ";", "var", "repeatElems", "=", "using", ".", "querySelectorAll", "(", "'['", "+", "attr", "+", "']'", ")", ";", "attr", "=", "attr", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "''", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "repeatElems", ".", "length", ";", "++", "i", ")", "{", "if", "(", "repeaterMatch", "(", "repeatElems", "[", "i", "]", ".", "getAttribute", "(", "attr", ")", ",", "repeater", ",", "exact", ")", ")", "{", "var", "elem", "=", "repeatElems", "[", "i", "]", ";", "var", "row", "=", "[", "]", ";", "while", "(", "elem", ".", "nodeType", "!=", "8", "||", "!", "repeaterMatch", "(", "elem", ".", "nodeValue", ",", "repeater", ")", ")", "{", "if", "(", "elem", ".", "nodeType", "==", "1", ")", "{", "row", ".", "push", "(", "elem", ")", ";", "}", "elem", "=", "elem", ".", "nextSibling", ";", "}", "multiRows", ".", "push", "(", "row", ")", ";", "}", "}", "}", "var", "row", "=", "rows", "[", "index", "]", "||", "[", "]", ",", "multiRow", "=", "multiRows", "[", "index", "]", "||", "[", "]", ";", "}" ]
Find an array of elements matching a row within an ng-repeat. Always returns an array of only one element for plain old ng-repeat. Returns an array of all the elements in one segment for ng-repeat-start. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {number} index The row index. @param {Element} using The scope of the search. @return {Array.<Element>} The row of the repeater, or an array of elements in the first row in the case of ng-repeat-start.
[ "Find", "an", "array", "of", "elements", "matching", "a", "row", "within", "an", "ng", "-", "repeat", ".", "Always", "returns", "an", "array", "of", "only", "one", "element", "for", "plain", "old", "ng", "-", "repeat", ".", "Returns", "an", "array", "of", "all", "the", "elements", "in", "one", "segment", "for", "ng", "-", "repeat", "-", "start", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/lib/clientsidescripts.js#L284-L323
train
angular/protractor
lib/clientsidescripts.js
findAllRepeaterRows
function findAllRepeaterRows(repeater, exact, using) { using = using || document; var rows = []; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { rows.push(elem); } elem = elem.nextSibling; } } } } return rows; }
javascript
function findAllRepeaterRows(repeater, exact, using) { using = using || document; var rows = []; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { rows.push(elem); } elem = elem.nextSibling; } } } } return rows; }
[ "function", "findAllRepeaterRows", "(", "repeater", ",", "exact", ",", "using", ")", "{", "using", "=", "using", "||", "document", ";", "var", "rows", "=", "[", "]", ";", "var", "prefixes", "=", "[", "'ng-'", ",", "'ng_'", ",", "'data-ng-'", ",", "'x-ng-'", ",", "'ng\\\\:'", "]", ";", "\\\\", "for", "(", "var", "p", "=", "0", ";", "p", "<", "prefixes", ".", "length", ";", "++", "p", ")", "{", "var", "attr", "=", "prefixes", "[", "p", "]", "+", "'repeat'", ";", "var", "repeatElems", "=", "using", ".", "querySelectorAll", "(", "'['", "+", "attr", "+", "']'", ")", ";", "attr", "=", "attr", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "''", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "repeatElems", ".", "length", ";", "++", "i", ")", "{", "if", "(", "repeaterMatch", "(", "repeatElems", "[", "i", "]", ".", "getAttribute", "(", "attr", ")", ",", "repeater", ",", "exact", ")", ")", "{", "rows", ".", "push", "(", "repeatElems", "[", "i", "]", ")", ";", "}", "}", "}", "for", "(", "var", "p", "=", "0", ";", "p", "<", "prefixes", ".", "length", ";", "++", "p", ")", "{", "var", "attr", "=", "prefixes", "[", "p", "]", "+", "'repeat-start'", ";", "var", "repeatElems", "=", "using", ".", "querySelectorAll", "(", "'['", "+", "attr", "+", "']'", ")", ";", "attr", "=", "attr", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "''", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "repeatElems", ".", "length", ";", "++", "i", ")", "{", "if", "(", "repeaterMatch", "(", "repeatElems", "[", "i", "]", ".", "getAttribute", "(", "attr", ")", ",", "repeater", ",", "exact", ")", ")", "{", "var", "elem", "=", "repeatElems", "[", "i", "]", ";", "while", "(", "elem", ".", "nodeType", "!=", "8", "||", "!", "repeaterMatch", "(", "elem", ".", "nodeValue", ",", "repeater", ")", ")", "{", "if", "(", "elem", ".", "nodeType", "==", "1", ")", "{", "rows", ".", "push", "(", "elem", ")", ";", "}", "elem", "=", "elem", ".", "nextSibling", ";", "}", "}", "}", "}", "}" ]
Find all rows of an ng-repeat. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {Element} using The scope of the search. @return {Array.<Element>} All rows of the repeater.
[ "Find", "all", "rows", "of", "an", "ng", "-", "repeat", "." ]
4f74a4ec753c97adfe955fe468a39286a0a55837
https://github.com/angular/protractor/blob/4f74a4ec753c97adfe955fe468a39286a0a55837/lib/clientsidescripts.js#L335-L368
train
getinsomnia/insomnia
packages/insomnia-prettify/src/json.js
_convertUnicode
function _convertUnicode(originalStr) { let m; let c; let cStr; let lastI = 0; // Matches \u#### but not \\u#### const unicodeRegex = /\\u[0-9a-fA-F]{4}/g; let convertedStr = ''; while ((m = unicodeRegex.exec(originalStr))) { // Don't convert if the backslash itself is escaped if (originalStr[m.index - 1] === '\\') { continue; } try { cStr = m[0].slice(2); // Trim off start c = String.fromCharCode(parseInt(cStr, 16)); if (c === '"') { // Escape it if it's double quotes c = `\\${c}`; } // + 1 to account for first matched (non-backslash) character convertedStr += originalStr.slice(lastI, m.index) + c; lastI = m.index + m[0].length; } catch (err) { // Some reason we couldn't convert a char. Should never actually happen console.warn('Failed to convert unicode char', m[0], err); } } // Finally, add the rest of the string to the end. convertedStr += originalStr.slice(lastI, originalStr.length); return convertedStr; }
javascript
function _convertUnicode(originalStr) { let m; let c; let cStr; let lastI = 0; // Matches \u#### but not \\u#### const unicodeRegex = /\\u[0-9a-fA-F]{4}/g; let convertedStr = ''; while ((m = unicodeRegex.exec(originalStr))) { // Don't convert if the backslash itself is escaped if (originalStr[m.index - 1] === '\\') { continue; } try { cStr = m[0].slice(2); // Trim off start c = String.fromCharCode(parseInt(cStr, 16)); if (c === '"') { // Escape it if it's double quotes c = `\\${c}`; } // + 1 to account for first matched (non-backslash) character convertedStr += originalStr.slice(lastI, m.index) + c; lastI = m.index + m[0].length; } catch (err) { // Some reason we couldn't convert a char. Should never actually happen console.warn('Failed to convert unicode char', m[0], err); } } // Finally, add the rest of the string to the end. convertedStr += originalStr.slice(lastI, originalStr.length); return convertedStr; }
[ "function", "_convertUnicode", "(", "originalStr", ")", "{", "let", "m", ";", "let", "c", ";", "let", "cStr", ";", "let", "lastI", "=", "0", ";", "const", "unicodeRegex", "=", "/", "\\\\u[0-9a-fA-F]{4}", "/", "g", ";", "let", "convertedStr", "=", "''", ";", "while", "(", "(", "m", "=", "unicodeRegex", ".", "exec", "(", "originalStr", ")", ")", ")", "{", "if", "(", "originalStr", "[", "m", ".", "index", "-", "1", "]", "===", "'\\\\'", ")", "\\\\", "{", "continue", ";", "}", "}", "try", "{", "cStr", "=", "m", "[", "0", "]", ".", "slice", "(", "2", ")", ";", "c", "=", "String", ".", "fromCharCode", "(", "parseInt", "(", "cStr", ",", "16", ")", ")", ";", "if", "(", "c", "===", "'\"'", ")", "{", "c", "=", "`", "\\\\", "${", "c", "}", "`", ";", "}", "convertedStr", "+=", "originalStr", ".", "slice", "(", "lastI", ",", "m", ".", "index", ")", "+", "c", ";", "lastI", "=", "m", ".", "index", "+", "m", "[", "0", "]", ".", "length", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "warn", "(", "'Failed to convert unicode char'", ",", "m", "[", "0", "]", ",", "err", ")", ";", "}", "convertedStr", "+=", "originalStr", ".", "slice", "(", "lastI", ",", "originalStr", ".", "length", ")", ";", "}" ]
Convert escaped unicode characters to real characters. Any JSON parser will do this by default. This is really fast too. Around 25ms for ~2MB of data with LOTS of unicode. @param originalStr @returns {string} @private
[ "Convert", "escaped", "unicode", "characters", "to", "real", "characters", ".", "Any", "JSON", "parser", "will", "do", "this", "by", "default", ".", "This", "is", "really", "fast", "too", ".", "Around", "25ms", "for", "~2MB", "of", "data", "with", "LOTS", "of", "unicode", "." ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-prettify/src/json.js#L172-L209
train
getinsomnia/insomnia
packages/insomnia-importers/src/importers/openapi3.js
parseEndpoints
function parseEndpoints(document) { const defaultParent = WORKSPACE_ID; const paths = Object.keys(document.paths); const endpointsSchemas = paths .map(path => { const schemasPerMethod = document.paths[path]; const methods = Object.keys(schemasPerMethod); return methods .filter(method => method !== 'parameters') .map(method => Object.assign({}, schemasPerMethod[method], { path, method })); }) .reduce((flat, arr) => flat.concat(arr), []); //flat single array const tags = document.tags || []; const folders = tags.map(tag => { return importFolderItem(tag, defaultParent); }); const folderLookup = {}; folders.forEach(folder => (folderLookup[folder.name] = folder._id)); const requests = []; endpointsSchemas.map(endpointSchema => { let { tags } = endpointSchema; if (!tags || tags.length == 0) tags = ['']; tags.forEach((tag, index) => { let id = endpointSchema.operationId ? `${endpointSchema.operationId}${index > 0 ? index : ''}` : `__REQUEST_${requestCount++}__`; let parentId = folderLookup[tag] || defaultParent; requests.push(importRequest(endpointSchema, id, parentId)); }); }); return [...folders, ...requests]; }
javascript
function parseEndpoints(document) { const defaultParent = WORKSPACE_ID; const paths = Object.keys(document.paths); const endpointsSchemas = paths .map(path => { const schemasPerMethod = document.paths[path]; const methods = Object.keys(schemasPerMethod); return methods .filter(method => method !== 'parameters') .map(method => Object.assign({}, schemasPerMethod[method], { path, method })); }) .reduce((flat, arr) => flat.concat(arr), []); //flat single array const tags = document.tags || []; const folders = tags.map(tag => { return importFolderItem(tag, defaultParent); }); const folderLookup = {}; folders.forEach(folder => (folderLookup[folder.name] = folder._id)); const requests = []; endpointsSchemas.map(endpointSchema => { let { tags } = endpointSchema; if (!tags || tags.length == 0) tags = ['']; tags.forEach((tag, index) => { let id = endpointSchema.operationId ? `${endpointSchema.operationId}${index > 0 ? index : ''}` : `__REQUEST_${requestCount++}__`; let parentId = folderLookup[tag] || defaultParent; requests.push(importRequest(endpointSchema, id, parentId)); }); }); return [...folders, ...requests]; }
[ "function", "parseEndpoints", "(", "document", ")", "{", "const", "defaultParent", "=", "WORKSPACE_ID", ";", "const", "paths", "=", "Object", ".", "keys", "(", "document", ".", "paths", ")", ";", "const", "endpointsSchemas", "=", "paths", ".", "map", "(", "path", "=>", "{", "const", "schemasPerMethod", "=", "document", ".", "paths", "[", "path", "]", ";", "const", "methods", "=", "Object", ".", "keys", "(", "schemasPerMethod", ")", ";", "return", "methods", ".", "filter", "(", "method", "=>", "method", "!==", "'parameters'", ")", ".", "map", "(", "method", "=>", "Object", ".", "assign", "(", "{", "}", ",", "schemasPerMethod", "[", "method", "]", ",", "{", "path", ",", "method", "}", ")", ")", ";", "}", ")", ".", "reduce", "(", "(", "flat", ",", "arr", ")", "=>", "flat", ".", "concat", "(", "arr", ")", ",", "[", "]", ")", ";", "const", "tags", "=", "document", ".", "tags", "||", "[", "]", ";", "const", "folders", "=", "tags", ".", "map", "(", "tag", "=>", "{", "return", "importFolderItem", "(", "tag", ",", "defaultParent", ")", ";", "}", ")", ";", "const", "folderLookup", "=", "{", "}", ";", "folders", ".", "forEach", "(", "folder", "=>", "(", "folderLookup", "[", "folder", ".", "name", "]", "=", "folder", ".", "_id", ")", ")", ";", "const", "requests", "=", "[", "]", ";", "endpointsSchemas", ".", "map", "(", "endpointSchema", "=>", "{", "let", "{", "tags", "}", "=", "endpointSchema", ";", "if", "(", "!", "tags", "||", "tags", ".", "length", "==", "0", ")", "tags", "=", "[", "''", "]", ";", "tags", ".", "forEach", "(", "(", "tag", ",", "index", ")", "=>", "{", "let", "id", "=", "endpointSchema", ".", "operationId", "?", "`", "${", "endpointSchema", ".", "operationId", "}", "${", "index", ">", "0", "?", "index", ":", "''", "}", "`", ":", "`", "${", "requestCount", "++", "}", "`", ";", "let", "parentId", "=", "folderLookup", "[", "tag", "]", "||", "defaultParent", ";", "requests", ".", "push", "(", "importRequest", "(", "endpointSchema", ",", "id", ",", "parentId", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "[", "...", "folders", ",", "...", "requests", "]", ";", "}" ]
Create request definitions based on openapi document. @param {Object} document - OpenAPI 3 valid object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oasObject) @returns {Object[]} array of insomnia endpoints definitions
[ "Create", "request", "definitions", "based", "on", "openapi", "document", "." ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-importers/src/importers/openapi3.js#L98-L134
train
getinsomnia/insomnia
packages/insomnia-importers/src/importers/openapi3.js
importRequest
function importRequest(endpointSchema, id, parentId) { const name = endpointSchema.summary || `${endpointSchema.method} ${endpointSchema.path}`; return { _type: 'request', _id: id, parentId: parentId, name, method: endpointSchema.method.toUpperCase(), url: '{{ base_url }}' + pathWithParamsAsVariables(endpointSchema.path), body: prepareBody(endpointSchema), headers: prepareHeaders(endpointSchema), parameters: prepareQueryParams(endpointSchema), }; }
javascript
function importRequest(endpointSchema, id, parentId) { const name = endpointSchema.summary || `${endpointSchema.method} ${endpointSchema.path}`; return { _type: 'request', _id: id, parentId: parentId, name, method: endpointSchema.method.toUpperCase(), url: '{{ base_url }}' + pathWithParamsAsVariables(endpointSchema.path), body: prepareBody(endpointSchema), headers: prepareHeaders(endpointSchema), parameters: prepareQueryParams(endpointSchema), }; }
[ "function", "importRequest", "(", "endpointSchema", ",", "id", ",", "parentId", ")", "{", "const", "name", "=", "endpointSchema", ".", "summary", "||", "`", "${", "endpointSchema", ".", "method", "}", "${", "endpointSchema", ".", "path", "}", "`", ";", "return", "{", "_type", ":", "'request'", ",", "_id", ":", "id", ",", "parentId", ":", "parentId", ",", "name", ",", "method", ":", "endpointSchema", ".", "method", ".", "toUpperCase", "(", ")", ",", "url", ":", "'{{ base_url }}'", "+", "pathWithParamsAsVariables", "(", "endpointSchema", ".", "path", ")", ",", "body", ":", "prepareBody", "(", "endpointSchema", ")", ",", "headers", ":", "prepareHeaders", "(", "endpointSchema", ")", ",", "parameters", ":", "prepareQueryParams", "(", "endpointSchema", ")", ",", "}", ";", "}" ]
Return Insomnia request @param {Object} endpointSchema - OpenAPI 3 endpoint schema @param {string} id - id to be given to current request @param {string} parentId - id of parent category @returns {Object}
[ "Return", "Insomnia", "request" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-importers/src/importers/openapi3.js#L163-L176
train
getinsomnia/insomnia
packages/insomnia-importers/src/importers/openapi3.js
prepareQueryParams
function prepareQueryParams(endpointSchema) { const isSendInQuery = p => p.in === 'query'; const parameters = endpointSchema.parameters || []; const queryParameters = parameters.filter(isSendInQuery); return convertParameters(queryParameters); }
javascript
function prepareQueryParams(endpointSchema) { const isSendInQuery = p => p.in === 'query'; const parameters = endpointSchema.parameters || []; const queryParameters = parameters.filter(isSendInQuery); return convertParameters(queryParameters); }
[ "function", "prepareQueryParams", "(", "endpointSchema", ")", "{", "const", "isSendInQuery", "=", "p", "=>", "p", ".", "in", "===", "'query'", ";", "const", "parameters", "=", "endpointSchema", ".", "parameters", "||", "[", "]", ";", "const", "queryParameters", "=", "parameters", ".", "filter", "(", "isSendInQuery", ")", ";", "return", "convertParameters", "(", "queryParameters", ")", ";", "}" ]
Imports insomnia definitions of query parameters. @param {Object} endpointSchema - OpenAPI 3 endpoint schema @returns {Object[]} array of parameters definitions
[ "Imports", "insomnia", "definitions", "of", "query", "parameters", "." ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-importers/src/importers/openapi3.js#L196-L201
train
getinsomnia/insomnia
packages/insomnia-importers/src/importers/openapi3.js
prepareHeaders
function prepareHeaders(endpointSchema) { const isSendInHeader = p => p.in === 'header'; const parameters = endpointSchema.parameters || []; const headerParameters = parameters.filter(isSendInHeader); return convertParameters(headerParameters); }
javascript
function prepareHeaders(endpointSchema) { const isSendInHeader = p => p.in === 'header'; const parameters = endpointSchema.parameters || []; const headerParameters = parameters.filter(isSendInHeader); return convertParameters(headerParameters); }
[ "function", "prepareHeaders", "(", "endpointSchema", ")", "{", "const", "isSendInHeader", "=", "p", "=>", "p", ".", "in", "===", "'header'", ";", "const", "parameters", "=", "endpointSchema", ".", "parameters", "||", "[", "]", ";", "const", "headerParameters", "=", "parameters", ".", "filter", "(", "isSendInHeader", ")", ";", "return", "convertParameters", "(", "headerParameters", ")", ";", "}" ]
Imports insomnia definitions of header parameters. @param {Object} endpointSchema - OpenAPI 3 endpoint schema @returns {Object[]} array of parameters definitions
[ "Imports", "insomnia", "definitions", "of", "header", "parameters", "." ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-importers/src/importers/openapi3.js#L209-L214
train
getinsomnia/insomnia
packages/insomnia-importers/src/importers/swagger2.js
convertParameters
function convertParameters(parameters) { return parameters.map(parameter => { const { required, name } = parameter; return { name, disabled: required !== true, value: `${generateParameterExample(parameter)}`, }; }); }
javascript
function convertParameters(parameters) { return parameters.map(parameter => { const { required, name } = parameter; return { name, disabled: required !== true, value: `${generateParameterExample(parameter)}`, }; }); }
[ "function", "convertParameters", "(", "parameters", ")", "{", "return", "parameters", ".", "map", "(", "parameter", "=>", "{", "const", "{", "required", ",", "name", "}", "=", "parameter", ";", "return", "{", "name", ",", "disabled", ":", "required", "!==", "true", ",", "value", ":", "`", "${", "generateParameterExample", "(", "parameter", ")", "}", "`", ",", "}", ";", "}", ")", ";", "}" ]
Converts swagger schema of parametes into insomnia one. @param {Object[]} parameters - array of swagger schemas of parameters @returns {Object[]} array of insomnia parameters definitions
[ "Converts", "swagger", "schema", "of", "parametes", "into", "insomnia", "one", "." ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-importers/src/importers/swagger2.js#L261-L270
train
getinsomnia/insomnia
packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js
replaceHintMatch
function replaceHintMatch(cm, self, data) { const cur = cm.getCursor(); const from = CodeMirror.Pos(cur.line, cur.ch - data.segment.length); const to = CodeMirror.Pos(cur.line, cur.ch); const prevStart = CodeMirror.Pos(from.line, from.ch - 10); const prevChars = cm.getRange(prevStart, from); const nextEnd = CodeMirror.Pos(to.line, to.ch + 10); const nextChars = cm.getRange(to, nextEnd); let prefix = ''; let suffix = ''; if (data.type === TYPE_VARIABLE && !prevChars.match(/{{[^}]*$/)) { prefix = '{{ '; // If no closer before } else if (data.type === TYPE_VARIABLE && prevChars.match(/{{$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && prevChars.match(/{%$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && !prevChars.match(/{%[^%]*$/)) { prefix = '{% '; // If no closer before } if (data.type === TYPE_VARIABLE && !nextChars.match(/^\s*}}/)) { suffix = ' }}'; // If no closer after } else if (data.type === TYPE_VARIABLE && nextChars.match(/^}}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^%}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^\s*}/)) { // Edge case because "%" doesn't auto-close tags so sometimes you end // up in the scenario of {% foo} suffix = ' %'; } else if (data.type === TYPE_TAG && !nextChars.match(/^\s*%}/)) { suffix = ' %}'; // If no closer after } cm.replaceRange(`${prefix}${data.text}${suffix}`, from, to); }
javascript
function replaceHintMatch(cm, self, data) { const cur = cm.getCursor(); const from = CodeMirror.Pos(cur.line, cur.ch - data.segment.length); const to = CodeMirror.Pos(cur.line, cur.ch); const prevStart = CodeMirror.Pos(from.line, from.ch - 10); const prevChars = cm.getRange(prevStart, from); const nextEnd = CodeMirror.Pos(to.line, to.ch + 10); const nextChars = cm.getRange(to, nextEnd); let prefix = ''; let suffix = ''; if (data.type === TYPE_VARIABLE && !prevChars.match(/{{[^}]*$/)) { prefix = '{{ '; // If no closer before } else if (data.type === TYPE_VARIABLE && prevChars.match(/{{$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && prevChars.match(/{%$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && !prevChars.match(/{%[^%]*$/)) { prefix = '{% '; // If no closer before } if (data.type === TYPE_VARIABLE && !nextChars.match(/^\s*}}/)) { suffix = ' }}'; // If no closer after } else if (data.type === TYPE_VARIABLE && nextChars.match(/^}}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^%}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^\s*}/)) { // Edge case because "%" doesn't auto-close tags so sometimes you end // up in the scenario of {% foo} suffix = ' %'; } else if (data.type === TYPE_TAG && !nextChars.match(/^\s*%}/)) { suffix = ' %}'; // If no closer after } cm.replaceRange(`${prefix}${data.text}${suffix}`, from, to); }
[ "function", "replaceHintMatch", "(", "cm", ",", "self", ",", "data", ")", "{", "const", "cur", "=", "cm", ".", "getCursor", "(", ")", ";", "const", "from", "=", "CodeMirror", ".", "Pos", "(", "cur", ".", "line", ",", "cur", ".", "ch", "-", "data", ".", "segment", ".", "length", ")", ";", "const", "to", "=", "CodeMirror", ".", "Pos", "(", "cur", ".", "line", ",", "cur", ".", "ch", ")", ";", "const", "prevStart", "=", "CodeMirror", ".", "Pos", "(", "from", ".", "line", ",", "from", ".", "ch", "-", "10", ")", ";", "const", "prevChars", "=", "cm", ".", "getRange", "(", "prevStart", ",", "from", ")", ";", "const", "nextEnd", "=", "CodeMirror", ".", "Pos", "(", "to", ".", "line", ",", "to", ".", "ch", "+", "10", ")", ";", "const", "nextChars", "=", "cm", ".", "getRange", "(", "to", ",", "nextEnd", ")", ";", "let", "prefix", "=", "''", ";", "let", "suffix", "=", "''", ";", "if", "(", "data", ".", "type", "===", "TYPE_VARIABLE", "&&", "!", "prevChars", ".", "match", "(", "/", "{{[^}]*$", "/", ")", ")", "{", "prefix", "=", "'{{ '", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_VARIABLE", "&&", "prevChars", ".", "match", "(", "/", "{{$", "/", ")", ")", "{", "prefix", "=", "' '", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_TAG", "&&", "prevChars", ".", "match", "(", "/", "{%$", "/", ")", ")", "{", "prefix", "=", "' '", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_TAG", "&&", "!", "prevChars", ".", "match", "(", "/", "{%[^%]*$", "/", ")", ")", "{", "prefix", "=", "'{% '", ";", "}", "if", "(", "data", ".", "type", "===", "TYPE_VARIABLE", "&&", "!", "nextChars", ".", "match", "(", "/", "^\\s*}}", "/", ")", ")", "{", "suffix", "=", "' }}'", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_VARIABLE", "&&", "nextChars", ".", "match", "(", "/", "^}}", "/", ")", ")", "{", "suffix", "=", "' '", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_TAG", "&&", "nextChars", ".", "match", "(", "/", "^%}", "/", ")", ")", "{", "suffix", "=", "' '", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_TAG", "&&", "nextChars", ".", "match", "(", "/", "^\\s*}", "/", ")", ")", "{", "suffix", "=", "' %'", ";", "}", "else", "if", "(", "data", ".", "type", "===", "TYPE_TAG", "&&", "!", "nextChars", ".", "match", "(", "/", "^\\s*%}", "/", ")", ")", "{", "suffix", "=", "' %}'", ";", "}", "cm", ".", "replaceRange", "(", "`", "${", "prefix", "}", "${", "data", ".", "text", "}", "${", "suffix", "}", "`", ",", "from", ",", "to", ")", ";", "}" ]
Replace the text in the editor when a hint is selected. This also makes sure there is whitespace surrounding it @param cm @param self @param data
[ "Replace", "the", "text", "in", "the", "editor", "when", "a", "hint", "is", "selected", ".", "This", "also", "makes", "sure", "there", "is", "whitespace", "surrounding", "it" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js#L298-L337
train
getinsomnia/insomnia
packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js
matchSegments
function matchSegments(listOfThings, segment, type, limit = -1) { if (!Array.isArray(listOfThings)) { console.warn('Autocomplete received items in non-list form', listOfThings); return []; } const matches = []; for (const t of listOfThings) { const name = typeof t === 'string' ? t : t.name; const value = typeof t === 'string' ? '' : t.value; const displayName = t.displayName || name; const defaultFill = typeof t === 'string' ? name : getDefaultFill(t.name, t.args); const matchSegment = segment.toLowerCase(); const matchName = displayName.toLowerCase(); // Throw away things that don't match if (!matchName.includes(matchSegment)) { continue; } matches.push({ // Custom Insomnia keys type, segment, comment: value, displayValue: value ? JSON.stringify(value) : '', score: name.length, // In case we want to sort by this // CodeMirror text: defaultFill, displayText: displayName, render: renderHintMatch, hint: replaceHintMatch, }); } if (limit >= 0) { return matches.slice(0, limit); } else { return matches; } }
javascript
function matchSegments(listOfThings, segment, type, limit = -1) { if (!Array.isArray(listOfThings)) { console.warn('Autocomplete received items in non-list form', listOfThings); return []; } const matches = []; for (const t of listOfThings) { const name = typeof t === 'string' ? t : t.name; const value = typeof t === 'string' ? '' : t.value; const displayName = t.displayName || name; const defaultFill = typeof t === 'string' ? name : getDefaultFill(t.name, t.args); const matchSegment = segment.toLowerCase(); const matchName = displayName.toLowerCase(); // Throw away things that don't match if (!matchName.includes(matchSegment)) { continue; } matches.push({ // Custom Insomnia keys type, segment, comment: value, displayValue: value ? JSON.stringify(value) : '', score: name.length, // In case we want to sort by this // CodeMirror text: defaultFill, displayText: displayName, render: renderHintMatch, hint: replaceHintMatch, }); } if (limit >= 0) { return matches.slice(0, limit); } else { return matches; } }
[ "function", "matchSegments", "(", "listOfThings", ",", "segment", ",", "type", ",", "limit", "=", "-", "1", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "listOfThings", ")", ")", "{", "console", ".", "warn", "(", "'Autocomplete received items in non-list form'", ",", "listOfThings", ")", ";", "return", "[", "]", ";", "}", "const", "matches", "=", "[", "]", ";", "for", "(", "const", "t", "of", "listOfThings", ")", "{", "const", "name", "=", "typeof", "t", "===", "'string'", "?", "t", ":", "t", ".", "name", ";", "const", "value", "=", "typeof", "t", "===", "'string'", "?", "''", ":", "t", ".", "value", ";", "const", "displayName", "=", "t", ".", "displayName", "||", "name", ";", "const", "defaultFill", "=", "typeof", "t", "===", "'string'", "?", "name", ":", "getDefaultFill", "(", "t", ".", "name", ",", "t", ".", "args", ")", ";", "const", "matchSegment", "=", "segment", ".", "toLowerCase", "(", ")", ";", "const", "matchName", "=", "displayName", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "matchName", ".", "includes", "(", "matchSegment", ")", ")", "{", "continue", ";", "}", "matches", ".", "push", "(", "{", "type", ",", "segment", ",", "comment", ":", "value", ",", "displayValue", ":", "value", "?", "JSON", ".", "stringify", "(", "value", ")", ":", "''", ",", "score", ":", "name", ".", "length", ",", "text", ":", "defaultFill", ",", "displayText", ":", "displayName", ",", "render", ":", "renderHintMatch", ",", "hint", ":", "replaceHintMatch", ",", "}", ")", ";", "}", "if", "(", "limit", ">=", "0", ")", "{", "return", "matches", ".", "slice", "(", "0", ",", "limit", ")", ";", "}", "else", "{", "return", "matches", ";", "}", "}" ]
Match against a list of things @param listOfThings - Can be list of strings or list of {name, value} @param segment - segment to match against @param type @param limit @returns {Array}
[ "Match", "against", "a", "list", "of", "things" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js#L347-L389
train
getinsomnia/insomnia
packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js
replaceWithSurround
function replaceWithSurround(text, find, prefix, suffix) { const escapedString = escapeRegex(find); const re = new RegExp(escapedString, 'gi'); return text.replace(re, matched => prefix + matched + suffix); }
javascript
function replaceWithSurround(text, find, prefix, suffix) { const escapedString = escapeRegex(find); const re = new RegExp(escapedString, 'gi'); return text.replace(re, matched => prefix + matched + suffix); }
[ "function", "replaceWithSurround", "(", "text", ",", "find", ",", "prefix", ",", "suffix", ")", "{", "const", "escapedString", "=", "escapeRegex", "(", "find", ")", ";", "const", "re", "=", "new", "RegExp", "(", "escapedString", ",", "'gi'", ")", ";", "return", "text", ".", "replace", "(", "re", ",", "matched", "=>", "prefix", "+", "matched", "+", "suffix", ")", ";", "}" ]
Replace all occurrences of string @param text @param find @param prefix @param suffix @returns string
[ "Replace", "all", "occurrences", "of", "string" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js#L399-L403
train
getinsomnia/insomnia
packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js
renderHintMatch
function renderHintMatch(li, self, data) { // Bold the matched text const { displayText, segment } = data; const markedName = replaceWithSurround(displayText, segment, '<strong>', '</strong>'); const { char, title } = ICONS[data.type]; const safeValue = escapeHTML(data.displayValue); li.className += ` fancy-hint type--${data.type}`; li.innerHTML = ` <label class="label" title="${title}">${char}</label> <div class="name">${markedName}</div> <div class="value" title=${safeValue}> ${safeValue} </div> `; }
javascript
function renderHintMatch(li, self, data) { // Bold the matched text const { displayText, segment } = data; const markedName = replaceWithSurround(displayText, segment, '<strong>', '</strong>'); const { char, title } = ICONS[data.type]; const safeValue = escapeHTML(data.displayValue); li.className += ` fancy-hint type--${data.type}`; li.innerHTML = ` <label class="label" title="${title}">${char}</label> <div class="name">${markedName}</div> <div class="value" title=${safeValue}> ${safeValue} </div> `; }
[ "function", "renderHintMatch", "(", "li", ",", "self", ",", "data", ")", "{", "const", "{", "displayText", ",", "segment", "}", "=", "data", ";", "const", "markedName", "=", "replaceWithSurround", "(", "displayText", ",", "segment", ",", "'<strong>'", ",", "'</strong>'", ")", ";", "const", "{", "char", ",", "title", "}", "=", "ICONS", "[", "data", ".", "type", "]", ";", "const", "safeValue", "=", "escapeHTML", "(", "data", ".", "displayValue", ")", ";", "li", ".", "className", "+=", "`", "${", "data", ".", "type", "}", "`", ";", "li", ".", "innerHTML", "=", "`", "${", "title", "}", "${", "char", "}", "${", "markedName", "}", "${", "safeValue", "}", "${", "safeValue", "}", "`", ";", "}" ]
Render the autocomplete list entry @param li @param self @param data
[ "Render", "the", "autocomplete", "list", "entry" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/ui/components/codemirror/extensions/autocomplete.js#L411-L427
train
getinsomnia/insomnia
packages/insomnia-app/app/sync-legacy/index.js
_getResourceGroupSymmetricKey
async function _getResourceGroupSymmetricKey(resourceGroupId) { let key = resourceGroupSymmetricKeysCache[resourceGroupId]; if (!key) { const resourceGroup = await fetchResourceGroup(resourceGroupId); const accountPrivateKey = await session.getPrivateKey(); const symmetricKeyStr = crypt.decryptRSAWithJWK( accountPrivateKey, resourceGroup.encSymmetricKey, ); key = JSON.parse(symmetricKeyStr); // Update cache resourceGroupSymmetricKeysCache[resourceGroupId] = key; } return key; }
javascript
async function _getResourceGroupSymmetricKey(resourceGroupId) { let key = resourceGroupSymmetricKeysCache[resourceGroupId]; if (!key) { const resourceGroup = await fetchResourceGroup(resourceGroupId); const accountPrivateKey = await session.getPrivateKey(); const symmetricKeyStr = crypt.decryptRSAWithJWK( accountPrivateKey, resourceGroup.encSymmetricKey, ); key = JSON.parse(symmetricKeyStr); // Update cache resourceGroupSymmetricKeysCache[resourceGroupId] = key; } return key; }
[ "async", "function", "_getResourceGroupSymmetricKey", "(", "resourceGroupId", ")", "{", "let", "key", "=", "resourceGroupSymmetricKeysCache", "[", "resourceGroupId", "]", ";", "if", "(", "!", "key", ")", "{", "const", "resourceGroup", "=", "await", "fetchResourceGroup", "(", "resourceGroupId", ")", ";", "const", "accountPrivateKey", "=", "await", "session", ".", "getPrivateKey", "(", ")", ";", "const", "symmetricKeyStr", "=", "crypt", ".", "decryptRSAWithJWK", "(", "accountPrivateKey", ",", "resourceGroup", ".", "encSymmetricKey", ",", ")", ";", "key", "=", "JSON", ".", "parse", "(", "symmetricKeyStr", ")", ";", "resourceGroupSymmetricKeysCache", "[", "resourceGroupId", "]", "=", "key", ";", "}", "return", "key", ";", "}" ]
Get a ResourceGroup's symmetric encryption key @param resourceGroupId @private
[ "Get", "a", "ResourceGroup", "s", "symmetric", "encryption", "key" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/sync-legacy/index.js#L669-L688
train
getinsomnia/insomnia
packages/insomnia-app/app/account/crypt.js
_pbkdf2Passphrase
async function _pbkdf2Passphrase(passphrase, salt) { if (window.crypto && window.crypto.subtle) { console.log('[crypt] Using native PBKDF2'); const k = await window.crypto.subtle.importKey( 'raw', Buffer.from(passphrase, 'utf8'), { name: 'PBKDF2' }, false, ['deriveBits'], ); const algo = { name: 'PBKDF2', salt: Buffer.from(salt, 'hex'), iterations: DEFAULT_PBKDF2_ITERATIONS, hash: 'SHA-256', }; const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8); return Buffer.from(derivedKeyRaw).toString('hex'); } else { console.log('[crypt] Using Forge PBKDF2'); const derivedKeyRaw = forge.pkcs5.pbkdf2( passphrase, forge.util.hexToBytes(salt), DEFAULT_PBKDF2_ITERATIONS, DEFAULT_BYTE_LENGTH, forge.md.sha256.create(), ); return forge.util.bytesToHex(derivedKeyRaw); } }
javascript
async function _pbkdf2Passphrase(passphrase, salt) { if (window.crypto && window.crypto.subtle) { console.log('[crypt] Using native PBKDF2'); const k = await window.crypto.subtle.importKey( 'raw', Buffer.from(passphrase, 'utf8'), { name: 'PBKDF2' }, false, ['deriveBits'], ); const algo = { name: 'PBKDF2', salt: Buffer.from(salt, 'hex'), iterations: DEFAULT_PBKDF2_ITERATIONS, hash: 'SHA-256', }; const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8); return Buffer.from(derivedKeyRaw).toString('hex'); } else { console.log('[crypt] Using Forge PBKDF2'); const derivedKeyRaw = forge.pkcs5.pbkdf2( passphrase, forge.util.hexToBytes(salt), DEFAULT_PBKDF2_ITERATIONS, DEFAULT_BYTE_LENGTH, forge.md.sha256.create(), ); return forge.util.bytesToHex(derivedKeyRaw); } }
[ "async", "function", "_pbkdf2Passphrase", "(", "passphrase", ",", "salt", ")", "{", "if", "(", "window", ".", "crypto", "&&", "window", ".", "crypto", ".", "subtle", ")", "{", "console", ".", "log", "(", "'[crypt] Using native PBKDF2'", ")", ";", "const", "k", "=", "await", "window", ".", "crypto", ".", "subtle", ".", "importKey", "(", "'raw'", ",", "Buffer", ".", "from", "(", "passphrase", ",", "'utf8'", ")", ",", "{", "name", ":", "'PBKDF2'", "}", ",", "false", ",", "[", "'deriveBits'", "]", ",", ")", ";", "const", "algo", "=", "{", "name", ":", "'PBKDF2'", ",", "salt", ":", "Buffer", ".", "from", "(", "salt", ",", "'hex'", ")", ",", "iterations", ":", "DEFAULT_PBKDF2_ITERATIONS", ",", "hash", ":", "'SHA-256'", ",", "}", ";", "const", "derivedKeyRaw", "=", "await", "window", ".", "crypto", ".", "subtle", ".", "deriveBits", "(", "algo", ",", "k", ",", "DEFAULT_BYTE_LENGTH", "*", "8", ")", ";", "return", "Buffer", ".", "from", "(", "derivedKeyRaw", ")", ".", "toString", "(", "'hex'", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'[crypt] Using Forge PBKDF2'", ")", ";", "const", "derivedKeyRaw", "=", "forge", ".", "pkcs5", ".", "pbkdf2", "(", "passphrase", ",", "forge", ".", "util", ".", "hexToBytes", "(", "salt", ")", ",", "DEFAULT_PBKDF2_ITERATIONS", ",", "DEFAULT_BYTE_LENGTH", ",", "forge", ".", "md", ".", "sha256", ".", "create", "(", ")", ",", ")", ";", "return", "forge", ".", "util", ".", "bytesToHex", "(", "derivedKeyRaw", ")", ";", "}", "}" ]
Derive key from password @param passphrase @param salt hex representation of salt
[ "Derive", "key", "from", "password" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/account/crypt.js#L346-L379
train
getinsomnia/insomnia
packages/insomnia-app/app/ui/redux/modules/index.js
getAllDocs
async function getAllDocs() { // Restore docs in parent->child->grandchild order const allDocs = [ ...(await models.settings.all()), ...(await models.workspace.all()), ...(await models.workspaceMeta.all()), ...(await models.environment.all()), ...(await models.cookieJar.all()), ...(await models.requestGroup.all()), ...(await models.requestGroupMeta.all()), ...(await models.request.all()), ...(await models.requestMeta.all()), ...(await models.response.all()), ...(await models.oAuth2Token.all()), ...(await models.clientCertificate.all()), ]; return allDocs; }
javascript
async function getAllDocs() { // Restore docs in parent->child->grandchild order const allDocs = [ ...(await models.settings.all()), ...(await models.workspace.all()), ...(await models.workspaceMeta.all()), ...(await models.environment.all()), ...(await models.cookieJar.all()), ...(await models.requestGroup.all()), ...(await models.requestGroupMeta.all()), ...(await models.request.all()), ...(await models.requestMeta.all()), ...(await models.response.all()), ...(await models.oAuth2Token.all()), ...(await models.clientCertificate.all()), ]; return allDocs; }
[ "async", "function", "getAllDocs", "(", ")", "{", "const", "allDocs", "=", "[", "...", "(", "await", "models", ".", "settings", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "workspace", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "workspaceMeta", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "environment", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "cookieJar", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "requestGroup", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "requestGroupMeta", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "request", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "requestMeta", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "response", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "oAuth2Token", ".", "all", "(", ")", ")", ",", "...", "(", "await", "models", ".", "clientCertificate", ".", "all", "(", ")", ")", ",", "]", ";", "return", "allDocs", ";", "}" ]
Async function to get all docs concurrently
[ "Async", "function", "to", "get", "all", "docs", "concurrently" ]
e24ce7f7b41246e700c4b9bdb6b34b6652ad589b
https://github.com/getinsomnia/insomnia/blob/e24ce7f7b41246e700c4b9bdb6b34b6652ad589b/packages/insomnia-app/app/ui/redux/modules/index.js#L48-L66
train
baianat/vee-validate
src/utils/vnode.js
addNativeNodeListener
function addNativeNodeListener (node, eventName, handler) { if (isNullOrUndefined(node.data.on)) { node.data.on = {}; } mergeVNodeListeners(node.data.on, eventName, handler); }
javascript
function addNativeNodeListener (node, eventName, handler) { if (isNullOrUndefined(node.data.on)) { node.data.on = {}; } mergeVNodeListeners(node.data.on, eventName, handler); }
[ "function", "addNativeNodeListener", "(", "node", ",", "eventName", ",", "handler", ")", "{", "if", "(", "isNullOrUndefined", "(", "node", ".", "data", ".", "on", ")", ")", "{", "node", ".", "data", ".", "on", "=", "{", "}", ";", "}", "mergeVNodeListeners", "(", "node", ".", "data", ".", "on", ",", "eventName", ",", "handler", ")", ";", "}" ]
Adds a listener to a native HTML vnode.
[ "Adds", "a", "listener", "to", "a", "native", "HTML", "vnode", "." ]
31a7022569a7ea36857016e0f6e68c6539b0c935
https://github.com/baianat/vee-validate/blob/31a7022569a7ea36857016e0f6e68c6539b0c935/src/utils/vnode.js#L79-L85
train
baianat/vee-validate
src/utils/vnode.js
addComponentNodeListener
function addComponentNodeListener (node, eventName, handler) { /* istanbul ignore next */ if (!node.componentOptions.listeners) { node.componentOptions.listeners = {}; } mergeVNodeListeners(node.componentOptions.listeners, eventName, handler); }
javascript
function addComponentNodeListener (node, eventName, handler) { /* istanbul ignore next */ if (!node.componentOptions.listeners) { node.componentOptions.listeners = {}; } mergeVNodeListeners(node.componentOptions.listeners, eventName, handler); }
[ "function", "addComponentNodeListener", "(", "node", ",", "eventName", ",", "handler", ")", "{", "if", "(", "!", "node", ".", "componentOptions", ".", "listeners", ")", "{", "node", ".", "componentOptions", ".", "listeners", "=", "{", "}", ";", "}", "mergeVNodeListeners", "(", "node", ".", "componentOptions", ".", "listeners", ",", "eventName", ",", "handler", ")", ";", "}" ]
Adds a listener to a Vue component vnode.
[ "Adds", "a", "listener", "to", "a", "Vue", "component", "vnode", "." ]
31a7022569a7ea36857016e0f6e68c6539b0c935
https://github.com/baianat/vee-validate/blob/31a7022569a7ea36857016e0f6e68c6539b0c935/src/utils/vnode.js#L88-L95
train
baianat/vee-validate
src/components/provider.js
shouldValidate
function shouldValidate (ctx, model) { // when an immediate/initial validation is needed and wasn't done before. if (!ctx._ignoreImmediate && ctx.immediate) { return true; } // when the value changes for whatever reason. if (ctx.value !== model.value) { return true; } // when it needs validation due to props/cross-fields changes. if (ctx._needsValidation) { return true; } // when the initial value is undefined and the field wasn't rendered yet. if (!ctx.initialized && model.value === undefined) { return true; } return false; }
javascript
function shouldValidate (ctx, model) { // when an immediate/initial validation is needed and wasn't done before. if (!ctx._ignoreImmediate && ctx.immediate) { return true; } // when the value changes for whatever reason. if (ctx.value !== model.value) { return true; } // when it needs validation due to props/cross-fields changes. if (ctx._needsValidation) { return true; } // when the initial value is undefined and the field wasn't rendered yet. if (!ctx.initialized && model.value === undefined) { return true; } return false; }
[ "function", "shouldValidate", "(", "ctx", ",", "model", ")", "{", "if", "(", "!", "ctx", ".", "_ignoreImmediate", "&&", "ctx", ".", "immediate", ")", "{", "return", "true", ";", "}", "if", "(", "ctx", ".", "value", "!==", "model", ".", "value", ")", "{", "return", "true", ";", "}", "if", "(", "ctx", ".", "_needsValidation", ")", "{", "return", "true", ";", "}", "if", "(", "!", "ctx", ".", "initialized", "&&", "model", ".", "value", "===", "undefined", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determines if a provider needs to run validation.
[ "Determines", "if", "a", "provider", "needs", "to", "run", "validation", "." ]
31a7022569a7ea36857016e0f6e68c6539b0c935
https://github.com/baianat/vee-validate/blob/31a7022569a7ea36857016e0f6e68c6539b0c935/src/components/provider.js#L41-L63
train
baianat/vee-validate
src/components/provider.js
addListeners
function addListeners (node) { const model = findModel(node); // cache the input eventName. this._inputEventName = this._inputEventName || getInputEventName(node, model); onRenderUpdate.call(this, model); const { onInput, onBlur, onValidate } = createCommonHandlers(this); addVNodeListener(node, this._inputEventName, onInput); addVNodeListener(node, 'blur', onBlur); // add the validation listeners. this.normalizedEvents.forEach(evt => { addVNodeListener(node, evt, onValidate); }); this.initialized = true; }
javascript
function addListeners (node) { const model = findModel(node); // cache the input eventName. this._inputEventName = this._inputEventName || getInputEventName(node, model); onRenderUpdate.call(this, model); const { onInput, onBlur, onValidate } = createCommonHandlers(this); addVNodeListener(node, this._inputEventName, onInput); addVNodeListener(node, 'blur', onBlur); // add the validation listeners. this.normalizedEvents.forEach(evt => { addVNodeListener(node, evt, onValidate); }); this.initialized = true; }
[ "function", "addListeners", "(", "node", ")", "{", "const", "model", "=", "findModel", "(", "node", ")", ";", "this", ".", "_inputEventName", "=", "this", ".", "_inputEventName", "||", "getInputEventName", "(", "node", ",", "model", ")", ";", "onRenderUpdate", ".", "call", "(", "this", ",", "model", ")", ";", "const", "{", "onInput", ",", "onBlur", ",", "onValidate", "}", "=", "createCommonHandlers", "(", "this", ")", ";", "addVNodeListener", "(", "node", ",", "this", ".", "_inputEventName", ",", "onInput", ")", ";", "addVNodeListener", "(", "node", ",", "'blur'", ",", "onBlur", ")", ";", "this", ".", "normalizedEvents", ".", "forEach", "(", "evt", "=>", "{", "addVNodeListener", "(", "node", ",", "evt", ",", "onValidate", ")", ";", "}", ")", ";", "this", ".", "initialized", "=", "true", ";", "}" ]
Adds all plugin listeners to the vnode.
[ "Adds", "all", "plugin", "listeners", "to", "the", "vnode", "." ]
31a7022569a7ea36857016e0f6e68c6539b0c935
https://github.com/baianat/vee-validate/blob/31a7022569a7ea36857016e0f6e68c6539b0c935/src/components/provider.js#L136-L153
train
firebase/firebaseui-web
javascript/utils/googleyolo.js
function() { // UI initialized, it is OK to cancel last operation. self.initialized_ = true; // retrieve is only called if auto sign-in is enabled. Otherwise, it will // get skipped. var retrieveCredential = Promise.resolve(null); if (!autoSignInDisabled) { retrieveCredential = self.googleyolo_.retrieve( /** @type {!SmartLockRequestOptions} */ (config)) .catch(function(error) { // For user cancellation or concurrent request pass down. // Otherwise suppress and run hint. if (error.type === firebaseui.auth.GoogleYolo.Error.USER_CANCELED || error.type === firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) { throw error; } // Ignore all other errors to give hint a chance to run next. return null; }); } // Check if a credential is already available (previously signed in with). return retrieveCredential .then(function(credential) { if (!credential) { // Auto sign-in not complete. // Show account selector. return self.googleyolo_.hint( /** @type {!SmartLockHintOptions} */ (config)); } // Credential already available from the retrieve call. Pass it // through. return credential; }) .catch(function(error) { // When user cancels the flow, reset the lastCancel promise and // resolve with false. if (error.type === firebaseui.auth.GoogleYolo.Error.USER_CANCELED) { self.lastCancel_ = Promise.resolve(); } else if (error.type === firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) { // Only one UI can be rendered at a time, cancel existing UI // and try again. self.cancel(); return self.show(config, autoSignInDisabled); } // Return null as no credential is available. return null; }); }
javascript
function() { // UI initialized, it is OK to cancel last operation. self.initialized_ = true; // retrieve is only called if auto sign-in is enabled. Otherwise, it will // get skipped. var retrieveCredential = Promise.resolve(null); if (!autoSignInDisabled) { retrieveCredential = self.googleyolo_.retrieve( /** @type {!SmartLockRequestOptions} */ (config)) .catch(function(error) { // For user cancellation or concurrent request pass down. // Otherwise suppress and run hint. if (error.type === firebaseui.auth.GoogleYolo.Error.USER_CANCELED || error.type === firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) { throw error; } // Ignore all other errors to give hint a chance to run next. return null; }); } // Check if a credential is already available (previously signed in with). return retrieveCredential .then(function(credential) { if (!credential) { // Auto sign-in not complete. // Show account selector. return self.googleyolo_.hint( /** @type {!SmartLockHintOptions} */ (config)); } // Credential already available from the retrieve call. Pass it // through. return credential; }) .catch(function(error) { // When user cancels the flow, reset the lastCancel promise and // resolve with false. if (error.type === firebaseui.auth.GoogleYolo.Error.USER_CANCELED) { self.lastCancel_ = Promise.resolve(); } else if (error.type === firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) { // Only one UI can be rendered at a time, cancel existing UI // and try again. self.cancel(); return self.show(config, autoSignInDisabled); } // Return null as no credential is available. return null; }); }
[ "function", "(", ")", "{", "self", ".", "initialized_", "=", "true", ";", "var", "retrieveCredential", "=", "Promise", ".", "resolve", "(", "null", ")", ";", "if", "(", "!", "autoSignInDisabled", ")", "{", "retrieveCredential", "=", "self", ".", "googleyolo_", ".", "retrieve", "(", "(", "config", ")", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", ".", "type", "===", "firebaseui", ".", "auth", ".", "GoogleYolo", ".", "Error", ".", "USER_CANCELED", "||", "error", ".", "type", "===", "firebaseui", ".", "auth", ".", "GoogleYolo", ".", "Error", ".", "CONCURRENT_REQUEST", ")", "{", "throw", "error", ";", "}", "return", "null", ";", "}", ")", ";", "}", "return", "retrieveCredential", ".", "then", "(", "function", "(", "credential", ")", "{", "if", "(", "!", "credential", ")", "{", "return", "self", ".", "googleyolo_", ".", "hint", "(", "(", "config", ")", ")", ";", "}", "return", "credential", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", ".", "type", "===", "firebaseui", ".", "auth", ".", "GoogleYolo", ".", "Error", ".", "USER_CANCELED", ")", "{", "self", ".", "lastCancel_", "=", "Promise", ".", "resolve", "(", ")", ";", "}", "else", "if", "(", "error", ".", "type", "===", "firebaseui", ".", "auth", ".", "GoogleYolo", ".", "Error", ".", "CONCURRENT_REQUEST", ")", "{", "self", ".", "cancel", "(", ")", ";", "return", "self", ".", "show", "(", "config", ",", "autoSignInDisabled", ")", ";", "}", "return", "null", ";", "}", ")", ";", "}" ]
One-Tap UI renderer.
[ "One", "-", "Tap", "UI", "renderer", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/utils/googleyolo.js#L131-L182
train
firebase/firebaseui-web
javascript/utils/acclient.js
function(resp, opt_error) { if (resp && resp['account'] && opt_onAccountSelected) { opt_onAccountSelected( firebaseui.auth.Account.fromPlainObject(resp['account'])); } else if (opt_onAddAccount) { // Check if accountchooser.com is available and pass to add account. var isUnavailable = firebaseui.auth.acClient.isUnavailable_(opt_error); // Either an error happened or user clicked the add account button. opt_onAddAccount(!isUnavailable); } }
javascript
function(resp, opt_error) { if (resp && resp['account'] && opt_onAccountSelected) { opt_onAccountSelected( firebaseui.auth.Account.fromPlainObject(resp['account'])); } else if (opt_onAddAccount) { // Check if accountchooser.com is available and pass to add account. var isUnavailable = firebaseui.auth.acClient.isUnavailable_(opt_error); // Either an error happened or user clicked the add account button. opt_onAddAccount(!isUnavailable); } }
[ "function", "(", "resp", ",", "opt_error", ")", "{", "if", "(", "resp", "&&", "resp", "[", "'account'", "]", "&&", "opt_onAccountSelected", ")", "{", "opt_onAccountSelected", "(", "firebaseui", ".", "auth", ".", "Account", ".", "fromPlainObject", "(", "resp", "[", "'account'", "]", ")", ")", ";", "}", "else", "if", "(", "opt_onAddAccount", ")", "{", "var", "isUnavailable", "=", "firebaseui", ".", "auth", ".", "acClient", ".", "isUnavailable_", "(", "opt_error", ")", ";", "opt_onAddAccount", "(", "!", "isUnavailable", ")", ";", "}", "}" ]
Save the add account callback for later use.
[ "Save", "the", "add", "account", "callback", "for", "later", "use", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/utils/acclient.js#L86-L96
train
firebase/firebaseui-web
protractor_spec.js
function(done, fail, tries) { // The default retrial policy. if (typeof tries === 'undefined') { tries = FLAKY_TEST_RETRIAL; } // executeScript runs the passed method in the "window" context of // the current test. JSUnit exposes hooks into the test's status through // the "G_testRunner" global object. browser.executeScript(function() { if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) { return { isFinished: true, isSuccess: window['G_testRunner']['isSuccess'](), report: window['G_testRunner']['getReport']() }; } else { return {'isFinished': false}; } }).then(function(status) { // Tests completed on the page but something failed. Retry a certain // number of times in case of flakiness. if (status && status.isFinished && !status.isSuccess && tries > 1) { // Try again in a few ms. setTimeout(waitForTest.bind(undefined, done, fail, tries - 1), 300); } else if (status && status.isFinished) { done(status); } else { // Try again in a few ms. setTimeout(waitForTest.bind(undefined, done, fail, tries), 300); } }, function(err) { // This can happen if the webdriver had an issue executing the script. fail(err); }); }
javascript
function(done, fail, tries) { // The default retrial policy. if (typeof tries === 'undefined') { tries = FLAKY_TEST_RETRIAL; } // executeScript runs the passed method in the "window" context of // the current test. JSUnit exposes hooks into the test's status through // the "G_testRunner" global object. browser.executeScript(function() { if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) { return { isFinished: true, isSuccess: window['G_testRunner']['isSuccess'](), report: window['G_testRunner']['getReport']() }; } else { return {'isFinished': false}; } }).then(function(status) { // Tests completed on the page but something failed. Retry a certain // number of times in case of flakiness. if (status && status.isFinished && !status.isSuccess && tries > 1) { // Try again in a few ms. setTimeout(waitForTest.bind(undefined, done, fail, tries - 1), 300); } else if (status && status.isFinished) { done(status); } else { // Try again in a few ms. setTimeout(waitForTest.bind(undefined, done, fail, tries), 300); } }, function(err) { // This can happen if the webdriver had an issue executing the script. fail(err); }); }
[ "function", "(", "done", ",", "fail", ",", "tries", ")", "{", "if", "(", "typeof", "tries", "===", "'undefined'", ")", "{", "tries", "=", "FLAKY_TEST_RETRIAL", ";", "}", "browser", ".", "executeScript", "(", "function", "(", ")", "{", "if", "(", "window", "[", "'G_testRunner'", "]", "&&", "window", "[", "'G_testRunner'", "]", "[", "'isFinished'", "]", "(", ")", ")", "{", "return", "{", "isFinished", ":", "true", ",", "isSuccess", ":", "window", "[", "'G_testRunner'", "]", "[", "'isSuccess'", "]", "(", ")", ",", "report", ":", "window", "[", "'G_testRunner'", "]", "[", "'getReport'", "]", "(", ")", "}", ";", "}", "else", "{", "return", "{", "'isFinished'", ":", "false", "}", ";", "}", "}", ")", ".", "then", "(", "function", "(", "status", ")", "{", "if", "(", "status", "&&", "status", ".", "isFinished", "&&", "!", "status", ".", "isSuccess", "&&", "tries", ">", "1", ")", "{", "setTimeout", "(", "waitForTest", ".", "bind", "(", "undefined", ",", "done", ",", "fail", ",", "tries", "-", "1", ")", ",", "300", ")", ";", "}", "else", "if", "(", "status", "&&", "status", ".", "isFinished", ")", "{", "done", "(", "status", ")", ";", "}", "else", "{", "setTimeout", "(", "waitForTest", ".", "bind", "(", "undefined", ",", "done", ",", "fail", ",", "tries", ")", ",", "300", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "fail", "(", "err", ")", ";", "}", ")", ";", "}" ]
Waits for current tests to be executed. @param {!Object} done The function called when the test is finished. @param {!Error} fail The function called when an unrecoverable error happened during the test. @param {?number=} tries The number of trials so far for the current test. This is used to retry flaky tests.
[ "Waits", "for", "current", "tests", "to", "be", "executed", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/protractor_spec.js#L32-L66
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function(isAvailable) { var app = getApp(); if (!app) { return; } firebaseui.auth.widget.handler.common.handleAcAddAccountResponse_( isAvailable, app, container, uiShownCallback); }
javascript
function(isAvailable) { var app = getApp(); if (!app) { return; } firebaseui.auth.widget.handler.common.handleAcAddAccountResponse_( isAvailable, app, container, uiShownCallback); }
[ "function", "(", "isAvailable", ")", "{", "var", "app", "=", "getApp", "(", ")", ";", "if", "(", "!", "app", ")", "{", "return", ";", "}", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "handleAcAddAccountResponse_", "(", "isAvailable", ",", "app", ",", "container", ",", "uiShownCallback", ")", ";", "}" ]
Handle adding an account.
[ "Handle", "adding", "an", "account", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L390-L397
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function(error) { // Ignore error if cancelled by the client. if (error['name'] && error['name'] == 'cancel') { return; } // Check if the error was due to an expired credential. // This may happen in the email mismatch case where the user waits more // than an hour and then proceeds to sign in with the expired credential. // Display the relevant error message in this case and return the user to // the sign-in start page. if (firebaseui.auth.widget.handler.common.isCredentialExpired(error)) { var container = component.getContainer(); // Dispose any existing component. component.dispose(); // Call widget sign-in start handler with the expired credential error. firebaseui.auth.widget.handler.common.handleSignInStart( app, container, undefined, firebaseui.auth.soy2.strings.errorExpiredCredential().toString()); } else { var errorMessage = (error && error['message']) || ''; if (error['code']) { // Firebase Auth error. // Errors thrown by anonymous upgrade should not be displayed in // info bar. if (error['code'] == 'auth/email-already-in-use' || error['code'] == 'auth/credential-already-in-use') { return; } errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); } // Show error message in the info bar. component.showInfoBar(errorMessage); } }
javascript
function(error) { // Ignore error if cancelled by the client. if (error['name'] && error['name'] == 'cancel') { return; } // Check if the error was due to an expired credential. // This may happen in the email mismatch case where the user waits more // than an hour and then proceeds to sign in with the expired credential. // Display the relevant error message in this case and return the user to // the sign-in start page. if (firebaseui.auth.widget.handler.common.isCredentialExpired(error)) { var container = component.getContainer(); // Dispose any existing component. component.dispose(); // Call widget sign-in start handler with the expired credential error. firebaseui.auth.widget.handler.common.handleSignInStart( app, container, undefined, firebaseui.auth.soy2.strings.errorExpiredCredential().toString()); } else { var errorMessage = (error && error['message']) || ''; if (error['code']) { // Firebase Auth error. // Errors thrown by anonymous upgrade should not be displayed in // info bar. if (error['code'] == 'auth/email-already-in-use' || error['code'] == 'auth/credential-already-in-use') { return; } errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); } // Show error message in the info bar. component.showInfoBar(errorMessage); } }
[ "function", "(", "error", ")", "{", "if", "(", "error", "[", "'name'", "]", "&&", "error", "[", "'name'", "]", "==", "'cancel'", ")", "{", "return", ";", "}", "if", "(", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "isCredentialExpired", "(", "error", ")", ")", "{", "var", "container", "=", "component", ".", "getContainer", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "handleSignInStart", "(", "app", ",", "container", ",", "undefined", ",", "firebaseui", ".", "auth", ".", "soy2", ".", "strings", ".", "errorExpiredCredential", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "var", "errorMessage", "=", "(", "error", "&&", "error", "[", "'message'", "]", ")", "||", "''", ";", "if", "(", "error", "[", "'code'", "]", ")", "{", "if", "(", "error", "[", "'code'", "]", "==", "'auth/email-already-in-use'", "||", "error", "[", "'code'", "]", "==", "'auth/credential-already-in-use'", ")", "{", "return", ";", "}", "errorMessage", "=", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "error", ")", ";", "}", "component", ".", "showInfoBar", "(", "errorMessage", ")", ";", "}", "}" ]
For any error, display in info bar message.
[ "For", "any", "error", "display", "in", "info", "bar", "message", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L562-L598
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function(error) { // Clear pending redirect status if redirect on Cordova fails. firebaseui.auth.storage.removePendingRedirectStatus(app.getAppId()); // Ignore error if cancelled by the client. if (error['name'] && error['name'] == 'cancel') { return; } switch (error['code']) { case 'auth/popup-blocked': // Popup blocked, switch to redirect flow as fallback. processRedirect(); break; case 'auth/popup-closed-by-user': case 'auth/cancelled-popup-request': // When popup is closed or when the user clicks another button, // do nothing. break; case 'auth/credential-already-in-use': // Do nothing when anonymous user is getting updated. // Developer should handle this in signInFailure callback. break; case 'auth/network-request-failed': case 'auth/too-many-requests': case 'auth/user-cancelled': // For no action errors like network error, just display in info // bar in current component. A second attempt could still work. component.showInfoBar( firebaseui.auth.widget.handler.common.getErrorMessage(error)); break; default: // Either linking required errors or errors that are // unrecoverable. component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.reject(error)); break; } }
javascript
function(error) { // Clear pending redirect status if redirect on Cordova fails. firebaseui.auth.storage.removePendingRedirectStatus(app.getAppId()); // Ignore error if cancelled by the client. if (error['name'] && error['name'] == 'cancel') { return; } switch (error['code']) { case 'auth/popup-blocked': // Popup blocked, switch to redirect flow as fallback. processRedirect(); break; case 'auth/popup-closed-by-user': case 'auth/cancelled-popup-request': // When popup is closed or when the user clicks another button, // do nothing. break; case 'auth/credential-already-in-use': // Do nothing when anonymous user is getting updated. // Developer should handle this in signInFailure callback. break; case 'auth/network-request-failed': case 'auth/too-many-requests': case 'auth/user-cancelled': // For no action errors like network error, just display in info // bar in current component. A second attempt could still work. component.showInfoBar( firebaseui.auth.widget.handler.common.getErrorMessage(error)); break; default: // Either linking required errors or errors that are // unrecoverable. component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.reject(error)); break; } }
[ "function", "(", "error", ")", "{", "firebaseui", ".", "auth", ".", "storage", ".", "removePendingRedirectStatus", "(", "app", ".", "getAppId", "(", ")", ")", ";", "if", "(", "error", "[", "'name'", "]", "&&", "error", "[", "'name'", "]", "==", "'cancel'", ")", "{", "return", ";", "}", "switch", "(", "error", "[", "'code'", "]", ")", "{", "case", "'auth/popup-blocked'", ":", "processRedirect", "(", ")", ";", "break", ";", "case", "'auth/popup-closed-by-user'", ":", "case", "'auth/cancelled-popup-request'", ":", "break", ";", "case", "'auth/credential-already-in-use'", ":", "break", ";", "case", "'auth/network-request-failed'", ":", "case", "'auth/too-many-requests'", ":", "case", "'auth/user-cancelled'", ":", "component", ".", "showInfoBar", "(", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "error", ")", ")", ";", "break", ";", "default", ":", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "CALLBACK", ",", "app", ",", "container", ",", "goog", ".", "Promise", ".", "reject", "(", "error", ")", ")", ";", "break", ";", "}", "}" ]
Error handler for signInWithPopup and getRedirectResult on Cordova.
[ "Error", "handler", "for", "signInWithPopup", "and", "getRedirectResult", "on", "Cordova", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L982-L1022
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function() { firebaseui.auth.storage.setPendingRedirectStatus(app.getAppId()); app.registerPending(component.executePromiseRequest( /** @type {function (): !goog.Promise} */ ( goog.bind(app.startSignInWithRedirect, app)), [provider], function() { // Only run below logic if the environment is potentially a Cordova // environment. This check is not required but will minimize the // need to change existing tests that assertSignInWithRedirect. if (firebaseui.auth.util.getScheme() !== 'file:') { return; } // This will resolve in a Cordova environment. Result should be // obtained from getRedirectResult and then treated like a // signInWithPopup operation. return app.registerPending(app.getRedirectResult() .then(function(result) { // Pass result in promise to callback handler. component.dispose(); // Removes pending redirect status if sign-in with redirect // resolves in Cordova environment. firebaseui.auth.storage.removePendingRedirectStatus( app.getAppId()); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.resolve(result)); }, signInResultErrorCallback)); }, providerSigninFailedCallback)); }
javascript
function() { firebaseui.auth.storage.setPendingRedirectStatus(app.getAppId()); app.registerPending(component.executePromiseRequest( /** @type {function (): !goog.Promise} */ ( goog.bind(app.startSignInWithRedirect, app)), [provider], function() { // Only run below logic if the environment is potentially a Cordova // environment. This check is not required but will minimize the // need to change existing tests that assertSignInWithRedirect. if (firebaseui.auth.util.getScheme() !== 'file:') { return; } // This will resolve in a Cordova environment. Result should be // obtained from getRedirectResult and then treated like a // signInWithPopup operation. return app.registerPending(app.getRedirectResult() .then(function(result) { // Pass result in promise to callback handler. component.dispose(); // Removes pending redirect status if sign-in with redirect // resolves in Cordova environment. firebaseui.auth.storage.removePendingRedirectStatus( app.getAppId()); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.resolve(result)); }, signInResultErrorCallback)); }, providerSigninFailedCallback)); }
[ "function", "(", ")", "{", "firebaseui", ".", "auth", ".", "storage", ".", "setPendingRedirectStatus", "(", "app", ".", "getAppId", "(", ")", ")", ";", "app", ".", "registerPending", "(", "component", ".", "executePromiseRequest", "(", "(", "goog", ".", "bind", "(", "app", ".", "startSignInWithRedirect", ",", "app", ")", ")", ",", "[", "provider", "]", ",", "function", "(", ")", "{", "if", "(", "firebaseui", ".", "auth", ".", "util", ".", "getScheme", "(", ")", "!==", "'file:'", ")", "{", "return", ";", "}", "return", "app", ".", "registerPending", "(", "app", ".", "getRedirectResult", "(", ")", ".", "then", "(", "function", "(", "result", ")", "{", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "storage", ".", "removePendingRedirectStatus", "(", "app", ".", "getAppId", "(", ")", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "CALLBACK", ",", "app", ",", "container", ",", "goog", ".", "Promise", ".", "resolve", "(", "result", ")", ")", ";", "}", ",", "signInResultErrorCallback", ")", ")", ";", "}", ",", "providerSigninFailedCallback", ")", ")", ";", "}" ]
Redirect processor.
[ "Redirect", "processor", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L1027-L1059
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function(firebaseCredential) { var status = false; var p = component.executePromiseRequest( /** @type {function (): !goog.Promise} */ ( goog.bind(app.startSignInWithCredential, app)), [firebaseCredential], function(result) { var container = component.getContainer(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.resolve(result)); status = true; }, function(error) { if (error['name'] && error['name'] == 'cancel') { return; } else if (error && error['code'] == 'auth/credential-already-in-use') { // Do nothing when anonymous user is getting updated. // Developer should handle this in signInFailure callback. return; } else if (error && error['code'] == 'auth/email-already-in-use' && error['email'] && error['credential']) { // Email already in use error should trigger account linking flow. // Pass error to callback handler to trigger that flow. var container = component.getContainer(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.reject(error)); return; } var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); // Show error message in the info bar. component.showInfoBar(errorMessage); }); app.registerPending(p); return p.then(function() { // Status needs to be returned. return status; }, function(error) { return false; }); }
javascript
function(firebaseCredential) { var status = false; var p = component.executePromiseRequest( /** @type {function (): !goog.Promise} */ ( goog.bind(app.startSignInWithCredential, app)), [firebaseCredential], function(result) { var container = component.getContainer(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.resolve(result)); status = true; }, function(error) { if (error['name'] && error['name'] == 'cancel') { return; } else if (error && error['code'] == 'auth/credential-already-in-use') { // Do nothing when anonymous user is getting updated. // Developer should handle this in signInFailure callback. return; } else if (error && error['code'] == 'auth/email-already-in-use' && error['email'] && error['credential']) { // Email already in use error should trigger account linking flow. // Pass error to callback handler to trigger that flow. var container = component.getContainer(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.CALLBACK, app, container, goog.Promise.reject(error)); return; } var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); // Show error message in the info bar. component.showInfoBar(errorMessage); }); app.registerPending(p); return p.then(function() { // Status needs to be returned. return status; }, function(error) { return false; }); }
[ "function", "(", "firebaseCredential", ")", "{", "var", "status", "=", "false", ";", "var", "p", "=", "component", ".", "executePromiseRequest", "(", "(", "goog", ".", "bind", "(", "app", ".", "startSignInWithCredential", ",", "app", ")", ")", ",", "[", "firebaseCredential", "]", ",", "function", "(", "result", ")", "{", "var", "container", "=", "component", ".", "getContainer", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "CALLBACK", ",", "app", ",", "container", ",", "goog", ".", "Promise", ".", "resolve", "(", "result", ")", ")", ";", "status", "=", "true", ";", "}", ",", "function", "(", "error", ")", "{", "if", "(", "error", "[", "'name'", "]", "&&", "error", "[", "'name'", "]", "==", "'cancel'", ")", "{", "return", ";", "}", "else", "if", "(", "error", "&&", "error", "[", "'code'", "]", "==", "'auth/credential-already-in-use'", ")", "{", "return", ";", "}", "else", "if", "(", "error", "&&", "error", "[", "'code'", "]", "==", "'auth/email-already-in-use'", "&&", "error", "[", "'email'", "]", "&&", "error", "[", "'credential'", "]", ")", "{", "var", "container", "=", "component", ".", "getContainer", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "CALLBACK", ",", "app", ",", "container", ",", "goog", ".", "Promise", ".", "reject", "(", "error", ")", ")", ";", "return", ";", "}", "var", "errorMessage", "=", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "error", ")", ";", "component", ".", "showInfoBar", "(", "errorMessage", ")", ";", "}", ")", ";", "app", ".", "registerPending", "(", "p", ")", ";", "return", "p", ".", "then", "(", "function", "(", ")", "{", "return", "status", ";", "}", ",", "function", "(", "error", ")", "{", "return", "false", ";", "}", ")", ";", "}" ]
Sign in with a Firebase Auth credential. @param {!firebase.auth.AuthCredential} firebaseCredential The Firebase Auth credential. @return {!goog.Promise<boolean>}
[ "Sign", "in", "with", "a", "Firebase", "Auth", "credential", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L1135-L1185
train
firebase/firebaseui-web
javascript/widgets/handler/common.js
function(providerId, opt_email) { // If popup flow enabled, this will fail and fallback to redirect. // TODO: Optimize to force redirect mode only. // For non-Google providers (not supported yet). This may end up signing the // user with a provider using different email. Even for Google, a user can // override the login_hint, but that should be fine as it is the user's // choice. firebaseui.auth.widget.handler.common.federatedSignIn( app, component, providerId, opt_email); return goog.Promise.resolve(true); }
javascript
function(providerId, opt_email) { // If popup flow enabled, this will fail and fallback to redirect. // TODO: Optimize to force redirect mode only. // For non-Google providers (not supported yet). This may end up signing the // user with a provider using different email. Even for Google, a user can // override the login_hint, but that should be fine as it is the user's // choice. firebaseui.auth.widget.handler.common.federatedSignIn( app, component, providerId, opt_email); return goog.Promise.resolve(true); }
[ "function", "(", "providerId", ",", "opt_email", ")", "{", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "federatedSignIn", "(", "app", ",", "component", ",", "providerId", ",", "opt_email", ")", ";", "return", "goog", ".", "Promise", ".", "resolve", "(", "true", ")", ";", "}" ]
Sign in with a provider ID. @param {string} providerId The Firebase Auth provider ID to sign-in with. @param {?string=} opt_email The optional email to sign-in with. @return {!goog.Promise<boolean>}
[ "Sign", "in", "with", "a", "provider", "ID", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/common.js#L1192-L1202
train
firebase/firebaseui-web
gulpfile.js
compile
function compile(srcs, out, args) { // Get the compiler arguments, using the defaults if not specified. const combinedArgs = Object.assign({}, COMPILER_DEFAULT_ARGS, args); return gulp .src(srcs) .pipe(closureCompiler({ compilerPath: COMPILER_PATH, fileName: path.basename(out), compilerFlags: combinedArgs })) .pipe(gulp.dest(path.dirname(out))); }
javascript
function compile(srcs, out, args) { // Get the compiler arguments, using the defaults if not specified. const combinedArgs = Object.assign({}, COMPILER_DEFAULT_ARGS, args); return gulp .src(srcs) .pipe(closureCompiler({ compilerPath: COMPILER_PATH, fileName: path.basename(out), compilerFlags: combinedArgs })) .pipe(gulp.dest(path.dirname(out))); }
[ "function", "compile", "(", "srcs", ",", "out", ",", "args", ")", "{", "const", "combinedArgs", "=", "Object", ".", "assign", "(", "{", "}", ",", "COMPILER_DEFAULT_ARGS", ",", "args", ")", ";", "return", "gulp", ".", "src", "(", "srcs", ")", ".", "pipe", "(", "closureCompiler", "(", "{", "compilerPath", ":", "COMPILER_PATH", ",", "fileName", ":", "path", ".", "basename", "(", "out", ")", ",", "compilerFlags", ":", "combinedArgs", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "path", ".", "dirname", "(", "out", ")", ")", ")", ";", "}" ]
Invokes Closure Compiler. @param {!Array<string>} srcs The JS sources to compile. @param {string} out The path to the output JS file. @param {!Object} args Additional arguments to Closure compiler. @return {*} A stream that finishes when compliation finishes.
[ "Invokes", "Closure", "Compiler", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/gulpfile.js#L124-L135
train
firebase/firebaseui-web
gulpfile.js
repeatTaskForAllLocales
function repeatTaskForAllLocales(taskName, dependencies, operation) { return ALL_LOCALES.map((locale) => { // Convert build-js-$ to build-js-fr, for example. const replaceTokens = (name) => name.replace(/\$/g, locale); const localeTaskName = replaceTokens(taskName); const localeDependencies = dependencies.map(replaceTokens); gulp.task(localeTaskName, gulp.series( gulp.parallel.apply(null, localeDependencies), () => operation(locale) )); return localeTaskName; }); }
javascript
function repeatTaskForAllLocales(taskName, dependencies, operation) { return ALL_LOCALES.map((locale) => { // Convert build-js-$ to build-js-fr, for example. const replaceTokens = (name) => name.replace(/\$/g, locale); const localeTaskName = replaceTokens(taskName); const localeDependencies = dependencies.map(replaceTokens); gulp.task(localeTaskName, gulp.series( gulp.parallel.apply(null, localeDependencies), () => operation(locale) )); return localeTaskName; }); }
[ "function", "repeatTaskForAllLocales", "(", "taskName", ",", "dependencies", ",", "operation", ")", "{", "return", "ALL_LOCALES", ".", "map", "(", "(", "locale", ")", "=>", "{", "const", "replaceTokens", "=", "(", "name", ")", "=>", "name", ".", "replace", "(", "/", "\\$", "/", "g", ",", "locale", ")", ";", "const", "localeTaskName", "=", "replaceTokens", "(", "taskName", ")", ";", "const", "localeDependencies", "=", "dependencies", ".", "map", "(", "replaceTokens", ")", ";", "gulp", ".", "task", "(", "localeTaskName", ",", "gulp", ".", "series", "(", "gulp", ".", "parallel", ".", "apply", "(", "null", ",", "localeDependencies", ")", ",", "(", ")", "=>", "operation", "(", "locale", ")", ")", ")", ";", "return", "localeTaskName", ";", "}", ")", ";", "}" ]
Repeats a gulp task for all locales. @param {string} taskName The gulp task name to generate. Any $ tokens will be replaced with the language code (e.g. build-$ becomes build-fr, build-es, etc.). @param {!Array<string>} dependencies The gulp tasks that each operation depends on. Any $ tokens will be replaced with the language code. @param {function()} operation The function to execute. @return {!Array<string>} The list of generated task names.
[ "Repeats", "a", "gulp", "task", "for", "all", "locales", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/gulpfile.js#L167-L179
train
firebase/firebaseui-web
gulpfile.js
buildFirebaseUiJs
function buildFirebaseUiJs(locale) { const flags = { closure_entry_point: 'firebaseui.auth.exports', define: `goog.LOCALE='${locale}'`, externs: [ 'node_modules/firebase/externs/firebase-app-externs.js', 'node_modules/firebase/externs/firebase-auth-externs.js', 'node_modules/firebase/externs/firebase-client-auth-externs.js' ], only_closure_dependencies: true, output_wrapper: OUTPUT_WRAPPER, // This is required to match XTB IDs to the JS/Soy messages. translations_project: 'FirebaseUI' }; if (locale !== DEFAULT_LOCALE) { flags.translations_file = `translations/${locale}.xtb`; } return compile([ 'node_modules/google-closure-templates/javascript/soyutils_usegoog.js', 'node_modules/google-closure-library/closure/goog/**/*.js', 'node_modules/google-closure-library/third_party/closure/goog/**/*.js', `${TMP_DIR}/**/*.js`, 'javascript/**/*.js' ], getTmpJsPath(locale), flags); }
javascript
function buildFirebaseUiJs(locale) { const flags = { closure_entry_point: 'firebaseui.auth.exports', define: `goog.LOCALE='${locale}'`, externs: [ 'node_modules/firebase/externs/firebase-app-externs.js', 'node_modules/firebase/externs/firebase-auth-externs.js', 'node_modules/firebase/externs/firebase-client-auth-externs.js' ], only_closure_dependencies: true, output_wrapper: OUTPUT_WRAPPER, // This is required to match XTB IDs to the JS/Soy messages. translations_project: 'FirebaseUI' }; if (locale !== DEFAULT_LOCALE) { flags.translations_file = `translations/${locale}.xtb`; } return compile([ 'node_modules/google-closure-templates/javascript/soyutils_usegoog.js', 'node_modules/google-closure-library/closure/goog/**/*.js', 'node_modules/google-closure-library/third_party/closure/goog/**/*.js', `${TMP_DIR}/**/*.js`, 'javascript/**/*.js' ], getTmpJsPath(locale), flags); }
[ "function", "buildFirebaseUiJs", "(", "locale", ")", "{", "const", "flags", "=", "{", "closure_entry_point", ":", "'firebaseui.auth.exports'", ",", "define", ":", "`", "${", "locale", "}", "`", ",", "externs", ":", "[", "'node_modules/firebase/externs/firebase-app-externs.js'", ",", "'node_modules/firebase/externs/firebase-auth-externs.js'", ",", "'node_modules/firebase/externs/firebase-client-auth-externs.js'", "]", ",", "only_closure_dependencies", ":", "true", ",", "output_wrapper", ":", "OUTPUT_WRAPPER", ",", "translations_project", ":", "'FirebaseUI'", "}", ";", "if", "(", "locale", "!==", "DEFAULT_LOCALE", ")", "{", "flags", ".", "translations_file", "=", "`", "${", "locale", "}", "`", ";", "}", "return", "compile", "(", "[", "'node_modules/google-closure-templates/javascript/soyutils_usegoog.js'", ",", "'node_modules/google-closure-library/closure/goog/**/*.js'", ",", "'node_modules/google-closure-library/third_party/closure/goog/**/*.js'", ",", "`", "${", "TMP_DIR", "}", "`", ",", "'javascript/**/*.js'", "]", ",", "getTmpJsPath", "(", "locale", ")", ",", "flags", ")", ";", "}" ]
Builds the core FirebaseUI binary in the given locale. @param {string} locale @return {*} A stream that finishes when compilation finishes.
[ "Builds", "the", "core", "FirebaseUI", "binary", "in", "the", "given", "locale", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/gulpfile.js#L186-L211
train
firebase/firebaseui-web
gulpfile.js
concatWithDeps
function concatWithDeps(locale, outBaseName, outputWrapper) { const localeForFileName = getLocaleForFileName(locale); // Get a list of the FirebaseUI JS and its dependencies. const srcs = JS_DEPS.concat([getTmpJsPath(locale)]); const outputPath = `${DEST_DIR}/${outBaseName}__${localeForFileName}.js`; return compile(srcs, outputPath, { compilation_level: 'WHITESPACE_ONLY', output_wrapper: outputWrapper }); }
javascript
function concatWithDeps(locale, outBaseName, outputWrapper) { const localeForFileName = getLocaleForFileName(locale); // Get a list of the FirebaseUI JS and its dependencies. const srcs = JS_DEPS.concat([getTmpJsPath(locale)]); const outputPath = `${DEST_DIR}/${outBaseName}__${localeForFileName}.js`; return compile(srcs, outputPath, { compilation_level: 'WHITESPACE_ONLY', output_wrapper: outputWrapper }); }
[ "function", "concatWithDeps", "(", "locale", ",", "outBaseName", ",", "outputWrapper", ")", "{", "const", "localeForFileName", "=", "getLocaleForFileName", "(", "locale", ")", ";", "const", "srcs", "=", "JS_DEPS", ".", "concat", "(", "[", "getTmpJsPath", "(", "locale", ")", "]", ")", ";", "const", "outputPath", "=", "`", "${", "DEST_DIR", "}", "${", "outBaseName", "}", "${", "localeForFileName", "}", "`", ";", "return", "compile", "(", "srcs", ",", "outputPath", ",", "{", "compilation_level", ":", "'WHITESPACE_ONLY'", ",", "output_wrapper", ":", "outputWrapper", "}", ")", ";", "}" ]
Concatenates the core FirebaseUI JS with its external dependencies, and cleans up comments and whitespace in the dependencies. @param {string} locale The desired FirebaseUI locale. @param {string} outBaseName The prefix of the output file name. @param {string} outputWrapper A wrapper with which to wrap the output JS. @return {*} A stream that ends when compilation finishes.
[ "Concatenates", "the", "core", "FirebaseUI", "JS", "with", "its", "external", "dependencies", "and", "cleans", "up", "comments", "and", "whitespace", "in", "the", "dependencies", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/gulpfile.js#L221-L230
train
firebase/firebaseui-web
gulpfile.js
buildCss
function buildCss(isRtl) { const mdlSrcs = gulp.src('stylesheet/mdl.scss') .pipe(sass.sync().on('error', sass.logError)) .pipe(cssInlineImages({ webRoot: 'node_modules/material-design-lite/src', })); const dialogPolyfillSrcs = gulp.src( 'node_modules/dialog-polyfill/dialog-polyfill.css'); let firebaseSrcs = gulp.src('stylesheet/*.css'); // Flip left/right, ltr/rtl for RTL languages. if (isRtl) { firebaseSrcs = firebaseSrcs.pipe(flip.gulp()); } const outFile = isRtl ? 'firebaseui-rtl.css' : 'firebaseui.css'; return streamqueue({objectMode: true}, mdlSrcs, dialogPolyfillSrcs, firebaseSrcs) .pipe(concatCSS(outFile)) .pipe(cleanCSS()) .pipe(gulp.dest(DEST_DIR)); }
javascript
function buildCss(isRtl) { const mdlSrcs = gulp.src('stylesheet/mdl.scss') .pipe(sass.sync().on('error', sass.logError)) .pipe(cssInlineImages({ webRoot: 'node_modules/material-design-lite/src', })); const dialogPolyfillSrcs = gulp.src( 'node_modules/dialog-polyfill/dialog-polyfill.css'); let firebaseSrcs = gulp.src('stylesheet/*.css'); // Flip left/right, ltr/rtl for RTL languages. if (isRtl) { firebaseSrcs = firebaseSrcs.pipe(flip.gulp()); } const outFile = isRtl ? 'firebaseui-rtl.css' : 'firebaseui.css'; return streamqueue({objectMode: true}, mdlSrcs, dialogPolyfillSrcs, firebaseSrcs) .pipe(concatCSS(outFile)) .pipe(cleanCSS()) .pipe(gulp.dest(DEST_DIR)); }
[ "function", "buildCss", "(", "isRtl", ")", "{", "const", "mdlSrcs", "=", "gulp", ".", "src", "(", "'stylesheet/mdl.scss'", ")", ".", "pipe", "(", "sass", ".", "sync", "(", ")", ".", "on", "(", "'error'", ",", "sass", ".", "logError", ")", ")", ".", "pipe", "(", "cssInlineImages", "(", "{", "webRoot", ":", "'node_modules/material-design-lite/src'", ",", "}", ")", ")", ";", "const", "dialogPolyfillSrcs", "=", "gulp", ".", "src", "(", "'node_modules/dialog-polyfill/dialog-polyfill.css'", ")", ";", "let", "firebaseSrcs", "=", "gulp", ".", "src", "(", "'stylesheet/*.css'", ")", ";", "if", "(", "isRtl", ")", "{", "firebaseSrcs", "=", "firebaseSrcs", ".", "pipe", "(", "flip", ".", "gulp", "(", ")", ")", ";", "}", "const", "outFile", "=", "isRtl", "?", "'firebaseui-rtl.css'", ":", "'firebaseui.css'", ";", "return", "streamqueue", "(", "{", "objectMode", ":", "true", "}", ",", "mdlSrcs", ",", "dialogPolyfillSrcs", ",", "firebaseSrcs", ")", ".", "pipe", "(", "concatCSS", "(", "outFile", ")", ")", ".", "pipe", "(", "cleanCSS", "(", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "DEST_DIR", ")", ")", ";", "}" ]
Builds the CSS for FirebaseUI. @param {boolean} isRtl Whether to build in right-to-left mode. @return {*} A stream that finishes when compilation finishes.
[ "Builds", "the", "CSS", "for", "FirebaseUI", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/gulpfile.js#L297-L318
train
firebase/firebaseui-web
soy/viewhelper.js
loadRecaptcha
function loadRecaptcha(container) { var root = goog.dom.getElement(container); var recaptchaContainer = goog.dom.getElementByClass('firebaseui-recaptcha-container', root); recaptchaContainer.style.display = 'block'; var img = goog.dom.createElement('img'); img.src = '../image/test/recaptcha-widget.png'; recaptchaContainer.appendChild(img); }
javascript
function loadRecaptcha(container) { var root = goog.dom.getElement(container); var recaptchaContainer = goog.dom.getElementByClass('firebaseui-recaptcha-container', root); recaptchaContainer.style.display = 'block'; var img = goog.dom.createElement('img'); img.src = '../image/test/recaptcha-widget.png'; recaptchaContainer.appendChild(img); }
[ "function", "loadRecaptcha", "(", "container", ")", "{", "var", "root", "=", "goog", ".", "dom", ".", "getElement", "(", "container", ")", ";", "var", "recaptchaContainer", "=", "goog", ".", "dom", ".", "getElementByClass", "(", "'firebaseui-recaptcha-container'", ",", "root", ")", ";", "recaptchaContainer", ".", "style", ".", "display", "=", "'block'", ";", "var", "img", "=", "goog", ".", "dom", ".", "createElement", "(", "'img'", ")", ";", "img", ".", "src", "=", "'../image/test/recaptcha-widget.png'", ";", "recaptchaContainer", ".", "appendChild", "(", "img", ")", ";", "}" ]
Simulates a reCAPTCHA being rendered for UI testing. This will just load a mock visible reCAPTCHA in the reCAPTCHA element. @param {Element} container The root container that holds the reCAPTCHA.
[ "Simulates", "a", "reCAPTCHA", "being", "rendered", "for", "UI", "testing", ".", "This", "will", "just", "load", "a", "mock", "visible", "reCAPTCHA", "in", "the", "reCAPTCHA", "element", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/soy/viewhelper.js#L59-L67
train
firebase/firebaseui-web
javascript/widgets/handler/emailnotreceived.js
function() { firebaseui.auth.widget.handler.common.sendEmailLinkForSignIn( app, component, email, onCancelClick, function(error) { // The email provided could be an invalid one or some other error // could occur. var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); component.showInfoBar(errorMessage); }, opt_pendingCredential); }
javascript
function() { firebaseui.auth.widget.handler.common.sendEmailLinkForSignIn( app, component, email, onCancelClick, function(error) { // The email provided could be an invalid one or some other error // could occur. var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); component.showInfoBar(errorMessage); }, opt_pendingCredential); }
[ "function", "(", ")", "{", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "sendEmailLinkForSignIn", "(", "app", ",", "component", ",", "email", ",", "onCancelClick", ",", "function", "(", "error", ")", "{", "var", "errorMessage", "=", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "error", ")", ";", "component", ".", "showInfoBar", "(", "errorMessage", ")", ";", "}", ",", "opt_pendingCredential", ")", ";", "}" ]
On resend link click.
[ "On", "resend", "link", "click", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/emailnotreceived.js#L44-L58
train
firebase/firebaseui-web
buildtools/country_data/get_directory_args.js
assertIsDirectory
function assertIsDirectory(path) { try { if (!fs.lstatSync(path).isDirectory()) { console.log('Path "' + path + '" is not a directory.'); process.exit(); } } catch (e) { console.log('Directory "' + path + '" could not be found.'); process.exit(); } }
javascript
function assertIsDirectory(path) { try { if (!fs.lstatSync(path).isDirectory()) { console.log('Path "' + path + '" is not a directory.'); process.exit(); } } catch (e) { console.log('Directory "' + path + '" could not be found.'); process.exit(); } }
[ "function", "assertIsDirectory", "(", "path", ")", "{", "try", "{", "if", "(", "!", "fs", ".", "lstatSync", "(", "path", ")", ".", "isDirectory", "(", ")", ")", "{", "console", ".", "log", "(", "'Path \"'", "+", "path", "+", "'\" is not a directory.'", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Directory \"'", "+", "path", "+", "'\" could not be found.'", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "}" ]
Asserts that the given path points to a directory and exits otherwise. @param {string} path
[ "Asserts", "that", "the", "given", "path", "points", "to", "a", "directory", "and", "exits", "otherwise", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/buildtools/country_data/get_directory_args.js#L26-L36
train
firebase/firebaseui-web
javascript/widgets/handler/passwordsignup.js
function() { var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(emailExistsError); firebaseui.auth.ui.element.setValid(component.getEmailElement(), false); firebaseui.auth.ui.element.show( component.getEmailErrorElement(), errorMessage); component.getEmailElement().focus(); }
javascript
function() { var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(emailExistsError); firebaseui.auth.ui.element.setValid(component.getEmailElement(), false); firebaseui.auth.ui.element.show( component.getEmailErrorElement(), errorMessage); component.getEmailElement().focus(); }
[ "function", "(", ")", "{", "var", "errorMessage", "=", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "emailExistsError", ")", ";", "firebaseui", ".", "auth", ".", "ui", ".", "element", ".", "setValid", "(", "component", ".", "getEmailElement", "(", ")", ",", "false", ")", ";", "firebaseui", ".", "auth", ".", "ui", ".", "element", ".", "show", "(", "component", ".", "getEmailErrorElement", "(", ")", ",", "errorMessage", ")", ";", "component", ".", "getEmailElement", "(", ")", ".", "focus", "(", ")", ";", "}" ]
If a provider already exists, just display the error and focus the email element.
[ "If", "a", "provider", "already", "exists", "just", "display", "the", "error", "and", "focus", "the", "email", "element", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/passwordsignup.js#L192-L199
train
firebase/firebaseui-web
javascript/widgets/handler/phonesigninstart.js
function(phoneAuthResult) { // Display the dialog that the code was sent. var container = component.getContainer(); component.showProgressDialog( firebaseui.auth.ui.element.progressDialog.State.DONE, firebaseui.auth.soy2.strings.dialogCodeSent().toString()); // Keep the dialog long enough to be seen before redirecting to code // entry page. var codeVerificationTimer = setTimeout(function() { component.dismissDialog(); // Handle sign in with phone number code verification. component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_FINISH, app, container, phoneNumberValue, firebaseui.auth.widget.handler.RESEND_DELAY_SECONDS, phoneAuthResult); }, firebaseui.auth.widget.handler.SENDING_SUCCESS_DIALOG_DELAY); // On reset, clear timeout. app.registerPending(function() { // Dismiss dialog if still visible. if (component) { component.dismissDialog(); } clearTimeout(codeVerificationTimer); }); }
javascript
function(phoneAuthResult) { // Display the dialog that the code was sent. var container = component.getContainer(); component.showProgressDialog( firebaseui.auth.ui.element.progressDialog.State.DONE, firebaseui.auth.soy2.strings.dialogCodeSent().toString()); // Keep the dialog long enough to be seen before redirecting to code // entry page. var codeVerificationTimer = setTimeout(function() { component.dismissDialog(); // Handle sign in with phone number code verification. component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_FINISH, app, container, phoneNumberValue, firebaseui.auth.widget.handler.RESEND_DELAY_SECONDS, phoneAuthResult); }, firebaseui.auth.widget.handler.SENDING_SUCCESS_DIALOG_DELAY); // On reset, clear timeout. app.registerPending(function() { // Dismiss dialog if still visible. if (component) { component.dismissDialog(); } clearTimeout(codeVerificationTimer); }); }
[ "function", "(", "phoneAuthResult", ")", "{", "var", "container", "=", "component", ".", "getContainer", "(", ")", ";", "component", ".", "showProgressDialog", "(", "firebaseui", ".", "auth", ".", "ui", ".", "element", ".", "progressDialog", ".", "State", ".", "DONE", ",", "firebaseui", ".", "auth", ".", "soy2", ".", "strings", ".", "dialogCodeSent", "(", ")", ".", "toString", "(", ")", ")", ";", "var", "codeVerificationTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "PHONE_SIGN_IN_FINISH", ",", "app", ",", "container", ",", "phoneNumberValue", ",", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "RESEND_DELAY_SECONDS", ",", "phoneAuthResult", ")", ";", "}", ",", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "SENDING_SUCCESS_DIALOG_DELAY", ")", ";", "app", ".", "registerPending", "(", "function", "(", ")", "{", "if", "(", "component", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "}", "clearTimeout", "(", "codeVerificationTimer", ")", ";", "}", ")", ";", "}" ]
On success a phone Auth result is returned.
[ "On", "success", "a", "phone", "Auth", "result", "is", "returned", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/phonesigninstart.js#L269-L297
train
firebase/firebaseui-web
demo/public/app.js
getUiConfig
function getUiConfig() { return { 'callbacks': { // Called when the user has been successfully signed in. 'signInSuccessWithAuthResult': function(authResult, redirectUrl) { if (authResult.user) { handleSignedInUser(authResult.user); } if (authResult.additionalUserInfo) { document.getElementById('is-new-user').textContent = authResult.additionalUserInfo.isNewUser ? 'New User' : 'Existing User'; } // Do not redirect. return false; } }, // Opens IDP Providers sign-in flow in a popup. 'signInFlow': 'popup', 'signInOptions': [ // TODO(developer): Remove the providers you don't need for your app. { provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID, // Required to enable this provider in One-Tap Sign-up. authMethod: 'https://accounts.google.com', // Required to enable ID token credentials for this provider. clientId: CLIENT_ID }, { provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID, scopes :[ 'public_profile', 'email', 'user_likes', 'user_friends' ] }, firebase.auth.TwitterAuthProvider.PROVIDER_ID, firebase.auth.GithubAuthProvider.PROVIDER_ID, { provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, // Whether the display name should be displayed in Sign Up page. requireDisplayName: true, signInMethod: getEmailSignInMethod() }, { provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID, recaptchaParameters: { size: getRecaptchaMode() } }, { provider: 'microsoft.com', providerName: 'Microsoft', buttonColor: '#2F2F2F', iconUrl: 'https://docs.microsoft.com/en-us/azure/active-directory/develop/media/howto-add-branding-in-azure-ad-apps/ms-symbollockup_mssymbol_19.png', loginHintKey: 'login_hint' }, firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID ], // Terms of service url. 'tosUrl': 'https://www.google.com', // Privacy policy url. 'privacyPolicyUrl': 'https://www.google.com', 'credentialHelper': CLIENT_ID && CLIENT_ID != 'YOUR_OAUTH_CLIENT_ID' ? firebaseui.auth.CredentialHelper.GOOGLE_YOLO : firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM }; }
javascript
function getUiConfig() { return { 'callbacks': { // Called when the user has been successfully signed in. 'signInSuccessWithAuthResult': function(authResult, redirectUrl) { if (authResult.user) { handleSignedInUser(authResult.user); } if (authResult.additionalUserInfo) { document.getElementById('is-new-user').textContent = authResult.additionalUserInfo.isNewUser ? 'New User' : 'Existing User'; } // Do not redirect. return false; } }, // Opens IDP Providers sign-in flow in a popup. 'signInFlow': 'popup', 'signInOptions': [ // TODO(developer): Remove the providers you don't need for your app. { provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID, // Required to enable this provider in One-Tap Sign-up. authMethod: 'https://accounts.google.com', // Required to enable ID token credentials for this provider. clientId: CLIENT_ID }, { provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID, scopes :[ 'public_profile', 'email', 'user_likes', 'user_friends' ] }, firebase.auth.TwitterAuthProvider.PROVIDER_ID, firebase.auth.GithubAuthProvider.PROVIDER_ID, { provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, // Whether the display name should be displayed in Sign Up page. requireDisplayName: true, signInMethod: getEmailSignInMethod() }, { provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID, recaptchaParameters: { size: getRecaptchaMode() } }, { provider: 'microsoft.com', providerName: 'Microsoft', buttonColor: '#2F2F2F', iconUrl: 'https://docs.microsoft.com/en-us/azure/active-directory/develop/media/howto-add-branding-in-azure-ad-apps/ms-symbollockup_mssymbol_19.png', loginHintKey: 'login_hint' }, firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID ], // Terms of service url. 'tosUrl': 'https://www.google.com', // Privacy policy url. 'privacyPolicyUrl': 'https://www.google.com', 'credentialHelper': CLIENT_ID && CLIENT_ID != 'YOUR_OAUTH_CLIENT_ID' ? firebaseui.auth.CredentialHelper.GOOGLE_YOLO : firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM }; }
[ "function", "getUiConfig", "(", ")", "{", "return", "{", "'callbacks'", ":", "{", "'signInSuccessWithAuthResult'", ":", "function", "(", "authResult", ",", "redirectUrl", ")", "{", "if", "(", "authResult", ".", "user", ")", "{", "handleSignedInUser", "(", "authResult", ".", "user", ")", ";", "}", "if", "(", "authResult", ".", "additionalUserInfo", ")", "{", "document", ".", "getElementById", "(", "'is-new-user'", ")", ".", "textContent", "=", "authResult", ".", "additionalUserInfo", ".", "isNewUser", "?", "'New User'", ":", "'Existing User'", ";", "}", "return", "false", ";", "}", "}", ",", "'signInFlow'", ":", "'popup'", ",", "'signInOptions'", ":", "[", "{", "provider", ":", "firebase", ".", "auth", ".", "GoogleAuthProvider", ".", "PROVIDER_ID", ",", "authMethod", ":", "'https://accounts.google.com'", ",", "clientId", ":", "CLIENT_ID", "}", ",", "{", "provider", ":", "firebase", ".", "auth", ".", "FacebookAuthProvider", ".", "PROVIDER_ID", ",", "scopes", ":", "[", "'public_profile'", ",", "'email'", ",", "'user_likes'", ",", "'user_friends'", "]", "}", ",", "firebase", ".", "auth", ".", "TwitterAuthProvider", ".", "PROVIDER_ID", ",", "firebase", ".", "auth", ".", "GithubAuthProvider", ".", "PROVIDER_ID", ",", "{", "provider", ":", "firebase", ".", "auth", ".", "EmailAuthProvider", ".", "PROVIDER_ID", ",", "requireDisplayName", ":", "true", ",", "signInMethod", ":", "getEmailSignInMethod", "(", ")", "}", ",", "{", "provider", ":", "firebase", ".", "auth", ".", "PhoneAuthProvider", ".", "PROVIDER_ID", ",", "recaptchaParameters", ":", "{", "size", ":", "getRecaptchaMode", "(", ")", "}", "}", ",", "{", "provider", ":", "'microsoft.com'", ",", "providerName", ":", "'Microsoft'", ",", "buttonColor", ":", "'#2F2F2F'", ",", "iconUrl", ":", "'https://docs.microsoft.com/en-us/azure/active-directory/develop/media/howto-add-branding-in-azure-ad-apps/ms-symbollockup_mssymbol_19.png'", ",", "loginHintKey", ":", "'login_hint'", "}", ",", "firebaseui", ".", "auth", ".", "AnonymousAuthProvider", ".", "PROVIDER_ID", "]", ",", "'tosUrl'", ":", "'https://www.google.com'", ",", "'privacyPolicyUrl'", ":", "'https://www.google.com'", ",", "'credentialHelper'", ":", "CLIENT_ID", "&&", "CLIENT_ID", "!=", "'YOUR_OAUTH_CLIENT_ID'", "?", "firebaseui", ".", "auth", ".", "CredentialHelper", ".", "GOOGLE_YOLO", ":", "firebaseui", ".", "auth", ".", "CredentialHelper", ".", "ACCOUNT_CHOOSER_COM", "}", ";", "}" ]
FirebaseUI initialization to be used in a Single Page application context. @return {!Object} The FirebaseUI config.
[ "FirebaseUI", "initialization", "to", "be", "used", "in", "a", "Single", "Page", "application", "context", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L22-L90
train
firebase/firebaseui-web
demo/public/app.js
function(authResult, redirectUrl) { if (authResult.user) { handleSignedInUser(authResult.user); } if (authResult.additionalUserInfo) { document.getElementById('is-new-user').textContent = authResult.additionalUserInfo.isNewUser ? 'New User' : 'Existing User'; } // Do not redirect. return false; }
javascript
function(authResult, redirectUrl) { if (authResult.user) { handleSignedInUser(authResult.user); } if (authResult.additionalUserInfo) { document.getElementById('is-new-user').textContent = authResult.additionalUserInfo.isNewUser ? 'New User' : 'Existing User'; } // Do not redirect. return false; }
[ "function", "(", "authResult", ",", "redirectUrl", ")", "{", "if", "(", "authResult", ".", "user", ")", "{", "handleSignedInUser", "(", "authResult", ".", "user", ")", ";", "}", "if", "(", "authResult", ".", "additionalUserInfo", ")", "{", "document", ".", "getElementById", "(", "'is-new-user'", ")", ".", "textContent", "=", "authResult", ".", "additionalUserInfo", ".", "isNewUser", "?", "'New User'", ":", "'Existing User'", ";", "}", "return", "false", ";", "}" ]
Called when the user has been successfully signed in.
[ "Called", "when", "the", "user", "has", "been", "successfully", "signed", "in", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L26-L37
train
firebase/firebaseui-web
demo/public/app.js
function(user) { document.getElementById('user-signed-in').style.display = 'block'; document.getElementById('user-signed-out').style.display = 'none'; document.getElementById('name').textContent = user.displayName; document.getElementById('email').textContent = user.email; document.getElementById('phone').textContent = user.phoneNumber; if (user.photoURL){ var photoURL = user.photoURL; // Append size to the photo URL for Google hosted images to avoid requesting // the image with its original resolution (using more bandwidth than needed) // when it is going to be presented in smaller size. if ((photoURL.indexOf('googleusercontent.com') != -1) || (photoURL.indexOf('ggpht.com') != -1)) { photoURL = photoURL + '?sz=' + document.getElementById('photo').clientHeight; } document.getElementById('photo').src = photoURL; document.getElementById('photo').style.display = 'block'; } else { document.getElementById('photo').style.display = 'none'; } }
javascript
function(user) { document.getElementById('user-signed-in').style.display = 'block'; document.getElementById('user-signed-out').style.display = 'none'; document.getElementById('name').textContent = user.displayName; document.getElementById('email').textContent = user.email; document.getElementById('phone').textContent = user.phoneNumber; if (user.photoURL){ var photoURL = user.photoURL; // Append size to the photo URL for Google hosted images to avoid requesting // the image with its original resolution (using more bandwidth than needed) // when it is going to be presented in smaller size. if ((photoURL.indexOf('googleusercontent.com') != -1) || (photoURL.indexOf('ggpht.com') != -1)) { photoURL = photoURL + '?sz=' + document.getElementById('photo').clientHeight; } document.getElementById('photo').src = photoURL; document.getElementById('photo').style.display = 'block'; } else { document.getElementById('photo').style.display = 'none'; } }
[ "function", "(", "user", ")", "{", "document", ".", "getElementById", "(", "'user-signed-in'", ")", ".", "style", ".", "display", "=", "'block'", ";", "document", ".", "getElementById", "(", "'user-signed-out'", ")", ".", "style", ".", "display", "=", "'none'", ";", "document", ".", "getElementById", "(", "'name'", ")", ".", "textContent", "=", "user", ".", "displayName", ";", "document", ".", "getElementById", "(", "'email'", ")", ".", "textContent", "=", "user", ".", "email", ";", "document", ".", "getElementById", "(", "'phone'", ")", ".", "textContent", "=", "user", ".", "phoneNumber", ";", "if", "(", "user", ".", "photoURL", ")", "{", "var", "photoURL", "=", "user", ".", "photoURL", ";", "if", "(", "(", "photoURL", ".", "indexOf", "(", "'googleusercontent.com'", ")", "!=", "-", "1", ")", "||", "(", "photoURL", ".", "indexOf", "(", "'ggpht.com'", ")", "!=", "-", "1", ")", ")", "{", "photoURL", "=", "photoURL", "+", "'?sz='", "+", "document", ".", "getElementById", "(", "'photo'", ")", ".", "clientHeight", ";", "}", "document", ".", "getElementById", "(", "'photo'", ")", ".", "src", "=", "photoURL", ";", "document", ".", "getElementById", "(", "'photo'", ")", ".", "style", ".", "display", "=", "'block'", ";", "}", "else", "{", "document", ".", "getElementById", "(", "'photo'", ")", ".", "style", ".", "display", "=", "'none'", ";", "}", "}" ]
Displays the UI for a signed in user. @param {!firebase.User} user
[ "Displays", "the", "UI", "for", "a", "signed", "in", "user", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L127-L148
train
firebase/firebaseui-web
demo/public/app.js
function() { document.getElementById('user-signed-in').style.display = 'none'; document.getElementById('user-signed-out').style.display = 'block'; ui.start('#firebaseui-container', getUiConfig()); }
javascript
function() { document.getElementById('user-signed-in').style.display = 'none'; document.getElementById('user-signed-out').style.display = 'block'; ui.start('#firebaseui-container', getUiConfig()); }
[ "function", "(", ")", "{", "document", ".", "getElementById", "(", "'user-signed-in'", ")", ".", "style", ".", "display", "=", "'none'", ";", "document", ".", "getElementById", "(", "'user-signed-out'", ")", ".", "style", ".", "display", "=", "'block'", ";", "ui", ".", "start", "(", "'#firebaseui-container'", ",", "getUiConfig", "(", ")", ")", ";", "}" ]
Displays the UI for a signed out user.
[ "Displays", "the", "UI", "for", "a", "signed", "out", "user", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L154-L158
train
firebase/firebaseui-web
demo/public/app.js
function() { firebase.auth().currentUser.delete().catch(function(error) { if (error.code == 'auth/requires-recent-login') { // The user's credential is too old. She needs to sign in again. firebase.auth().signOut().then(function() { // The timeout allows the message to be displayed after the UI has // changed to the signed out state. setTimeout(function() { alert('Please sign in again to delete your account.'); }, 1); }); } }); }
javascript
function() { firebase.auth().currentUser.delete().catch(function(error) { if (error.code == 'auth/requires-recent-login') { // The user's credential is too old. She needs to sign in again. firebase.auth().signOut().then(function() { // The timeout allows the message to be displayed after the UI has // changed to the signed out state. setTimeout(function() { alert('Please sign in again to delete your account.'); }, 1); }); } }); }
[ "function", "(", ")", "{", "firebase", ".", "auth", "(", ")", ".", "currentUser", ".", "delete", "(", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", ".", "code", "==", "'auth/requires-recent-login'", ")", "{", "firebase", ".", "auth", "(", ")", ".", "signOut", "(", ")", ".", "then", "(", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "alert", "(", "'Please sign in again to delete your account.'", ")", ";", "}", ",", "1", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Deletes the user's account.
[ "Deletes", "the", "user", "s", "account", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L171-L184
train
firebase/firebaseui-web
demo/public/app.js
handleConfigChange
function handleConfigChange() { var newRecaptchaValue = document.querySelector( 'input[name="recaptcha"]:checked').value; var newEmailSignInMethodValue = document.querySelector( 'input[name="emailSignInMethod"]:checked').value; location.replace( location.pathname + '#recaptcha=' + newRecaptchaValue + '&emailSignInMethod=' + newEmailSignInMethodValue); // Reset the inline widget so the config changes are reflected. ui.reset(); ui.start('#firebaseui-container', getUiConfig()); }
javascript
function handleConfigChange() { var newRecaptchaValue = document.querySelector( 'input[name="recaptcha"]:checked').value; var newEmailSignInMethodValue = document.querySelector( 'input[name="emailSignInMethod"]:checked').value; location.replace( location.pathname + '#recaptcha=' + newRecaptchaValue + '&emailSignInMethod=' + newEmailSignInMethodValue); // Reset the inline widget so the config changes are reflected. ui.reset(); ui.start('#firebaseui-container', getUiConfig()); }
[ "function", "handleConfigChange", "(", ")", "{", "var", "newRecaptchaValue", "=", "document", ".", "querySelector", "(", "'input[name=\"recaptcha\"]:checked'", ")", ".", "value", ";", "var", "newEmailSignInMethodValue", "=", "document", ".", "querySelector", "(", "'input[name=\"emailSignInMethod\"]:checked'", ")", ".", "value", ";", "location", ".", "replace", "(", "location", ".", "pathname", "+", "'#recaptcha='", "+", "newRecaptchaValue", "+", "'&emailSignInMethod='", "+", "newEmailSignInMethodValue", ")", ";", "ui", ".", "reset", "(", ")", ";", "ui", ".", "start", "(", "'#firebaseui-container'", ",", "getUiConfig", "(", ")", ")", ";", "}" ]
Handles when the user changes the reCAPTCHA or email signInMethod config.
[ "Handles", "when", "the", "user", "changes", "the", "reCAPTCHA", "or", "email", "signInMethod", "config", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L190-L202
train
firebase/firebaseui-web
demo/public/app.js
function() { document.getElementById('sign-in-with-redirect').addEventListener( 'click', signInWithRedirect); document.getElementById('sign-in-with-popup').addEventListener( 'click', signInWithPopup); document.getElementById('sign-out').addEventListener('click', function() { firebase.auth().signOut(); }); document.getElementById('delete-account').addEventListener( 'click', function() { deleteAccount(); }); document.getElementById('recaptcha-normal').addEventListener( 'change', handleConfigChange); document.getElementById('recaptcha-invisible').addEventListener( 'change', handleConfigChange); // Check the selected reCAPTCHA mode. document.querySelector( 'input[name="recaptcha"][value="' + getRecaptchaMode() + '"]') .checked = true; document.getElementById('email-signInMethod-password').addEventListener( 'change', handleConfigChange); document.getElementById('email-signInMethod-emailLink').addEventListener( 'change', handleConfigChange); // Check the selected email signInMethod mode. document.querySelector( 'input[name="emailSignInMethod"][value="' + getEmailSignInMethod() + '"]') .checked = true; }
javascript
function() { document.getElementById('sign-in-with-redirect').addEventListener( 'click', signInWithRedirect); document.getElementById('sign-in-with-popup').addEventListener( 'click', signInWithPopup); document.getElementById('sign-out').addEventListener('click', function() { firebase.auth().signOut(); }); document.getElementById('delete-account').addEventListener( 'click', function() { deleteAccount(); }); document.getElementById('recaptcha-normal').addEventListener( 'change', handleConfigChange); document.getElementById('recaptcha-invisible').addEventListener( 'change', handleConfigChange); // Check the selected reCAPTCHA mode. document.querySelector( 'input[name="recaptcha"][value="' + getRecaptchaMode() + '"]') .checked = true; document.getElementById('email-signInMethod-password').addEventListener( 'change', handleConfigChange); document.getElementById('email-signInMethod-emailLink').addEventListener( 'change', handleConfigChange); // Check the selected email signInMethod mode. document.querySelector( 'input[name="emailSignInMethod"][value="' + getEmailSignInMethod() + '"]') .checked = true; }
[ "function", "(", ")", "{", "document", ".", "getElementById", "(", "'sign-in-with-redirect'", ")", ".", "addEventListener", "(", "'click'", ",", "signInWithRedirect", ")", ";", "document", ".", "getElementById", "(", "'sign-in-with-popup'", ")", ".", "addEventListener", "(", "'click'", ",", "signInWithPopup", ")", ";", "document", ".", "getElementById", "(", "'sign-out'", ")", ".", "addEventListener", "(", "'click'", ",", "function", "(", ")", "{", "firebase", ".", "auth", "(", ")", ".", "signOut", "(", ")", ";", "}", ")", ";", "document", ".", "getElementById", "(", "'delete-account'", ")", ".", "addEventListener", "(", "'click'", ",", "function", "(", ")", "{", "deleteAccount", "(", ")", ";", "}", ")", ";", "document", ".", "getElementById", "(", "'recaptcha-normal'", ")", ".", "addEventListener", "(", "'change'", ",", "handleConfigChange", ")", ";", "document", ".", "getElementById", "(", "'recaptcha-invisible'", ")", ".", "addEventListener", "(", "'change'", ",", "handleConfigChange", ")", ";", "document", ".", "querySelector", "(", "'input[name=\"recaptcha\"][value=\"'", "+", "getRecaptchaMode", "(", ")", "+", "'\"]'", ")", ".", "checked", "=", "true", ";", "document", ".", "getElementById", "(", "'email-signInMethod-password'", ")", ".", "addEventListener", "(", "'change'", ",", "handleConfigChange", ")", ";", "document", ".", "getElementById", "(", "'email-signInMethod-emailLink'", ")", ".", "addEventListener", "(", "'change'", ",", "handleConfigChange", ")", ";", "document", ".", "querySelector", "(", "'input[name=\"emailSignInMethod\"][value=\"'", "+", "getEmailSignInMethod", "(", ")", "+", "'\"]'", ")", ".", "checked", "=", "true", ";", "}" ]
Initializes the app.
[ "Initializes", "the", "app", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/demo/public/app.js#L208-L238
train
firebase/firebaseui-web
javascript/widgets/handler/emaillinkconfirmation.js
function() { var email = component.checkAndGetEmail(); if (!email) { component.getEmailElement().focus(); return; } component.dispose(); onContinue(app, container, email, link); }
javascript
function() { var email = component.checkAndGetEmail(); if (!email) { component.getEmailElement().focus(); return; } component.dispose(); onContinue(app, container, email, link); }
[ "function", "(", ")", "{", "var", "email", "=", "component", ".", "checkAndGetEmail", "(", ")", ";", "if", "(", "!", "email", ")", "{", "component", ".", "getEmailElement", "(", ")", ".", "focus", "(", ")", ";", "return", ";", "}", "component", ".", "dispose", "(", ")", ";", "onContinue", "(", "app", ",", "container", ",", "email", ",", "link", ")", ";", "}" ]
On email enter.
[ "On", "email", "enter", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/emaillinkconfirmation.js#L46-L54
train
firebase/firebaseui-web
javascript/widgets/handler/phonesigninfinish.js
function() { component.dispose(); // Render previous phone sign in start page. firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app, container, phoneNumberValue); }
javascript
function() { component.dispose(); // Render previous phone sign in start page. firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app, container, phoneNumberValue); }
[ "function", "(", ")", "{", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "PHONE_SIGN_IN_START", ",", "app", ",", "container", ",", "phoneNumberValue", ")", ";", "}" ]
On change phone number click.
[ "On", "change", "phone", "number", "click", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/phonesigninfinish.js#L56-L62
train
firebase/firebaseui-web
javascript/widgets/handler/phonesigninfinish.js
function(userCredential) { component.dismissDialog(); // Show code verified dialog. component.showProgressDialog( firebaseui.auth.ui.element.progressDialog.State.DONE, firebaseui.auth.soy2.strings.dialogCodeVerified().toString()); // Keep on display for long enough to be seen. var codeVerifiedTimer = setTimeout(function() { // Dismiss dialog and dispose of component before completing sign-in. component.dismissDialog(); component.dispose(); var authResult = /** @type {!firebaseui.auth.AuthResult} */ ({ // User already signed on external instance. 'user': app.getExternalAuth().currentUser, // Phone Auth operations do not return a credential. 'credential': null, 'operationType': userCredential['operationType'], 'additionalUserInfo': userCredential['additionalUserInfo'] }); firebaseui.auth.widget.handler.common.setLoggedInWithAuthResult( app, component, authResult, true); }, firebaseui.auth.widget.handler.CODE_SUCCESS_DIALOG_DELAY); // On reset, clear timeout. app.registerPending(function() { // Dismiss dialog if still visible. if (component) { component.dismissDialog(); } clearTimeout(codeVerifiedTimer); }); }
javascript
function(userCredential) { component.dismissDialog(); // Show code verified dialog. component.showProgressDialog( firebaseui.auth.ui.element.progressDialog.State.DONE, firebaseui.auth.soy2.strings.dialogCodeVerified().toString()); // Keep on display for long enough to be seen. var codeVerifiedTimer = setTimeout(function() { // Dismiss dialog and dispose of component before completing sign-in. component.dismissDialog(); component.dispose(); var authResult = /** @type {!firebaseui.auth.AuthResult} */ ({ // User already signed on external instance. 'user': app.getExternalAuth().currentUser, // Phone Auth operations do not return a credential. 'credential': null, 'operationType': userCredential['operationType'], 'additionalUserInfo': userCredential['additionalUserInfo'] }); firebaseui.auth.widget.handler.common.setLoggedInWithAuthResult( app, component, authResult, true); }, firebaseui.auth.widget.handler.CODE_SUCCESS_DIALOG_DELAY); // On reset, clear timeout. app.registerPending(function() { // Dismiss dialog if still visible. if (component) { component.dismissDialog(); } clearTimeout(codeVerifiedTimer); }); }
[ "function", "(", "userCredential", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "component", ".", "showProgressDialog", "(", "firebaseui", ".", "auth", ".", "ui", ".", "element", ".", "progressDialog", ".", "State", ".", "DONE", ",", "firebaseui", ".", "auth", ".", "soy2", ".", "strings", ".", "dialogCodeVerified", "(", ")", ".", "toString", "(", ")", ")", ";", "var", "codeVerifiedTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "var", "authResult", "=", "(", "{", "'user'", ":", "app", ".", "getExternalAuth", "(", ")", ".", "currentUser", ",", "'credential'", ":", "null", ",", "'operationType'", ":", "userCredential", "[", "'operationType'", "]", ",", "'additionalUserInfo'", ":", "userCredential", "[", "'additionalUserInfo'", "]", "}", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "setLoggedInWithAuthResult", "(", "app", ",", "component", ",", "authResult", ",", "true", ")", ";", "}", ",", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "CODE_SUCCESS_DIALOG_DELAY", ")", ";", "app", ".", "registerPending", "(", "function", "(", ")", "{", "if", "(", "component", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "}", "clearTimeout", "(", "codeVerifiedTimer", ")", ";", "}", ")", ";", "}" ]
On success a user credential is returned.
[ "On", "success", "a", "user", "credential", "is", "returned", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/phonesigninfinish.js#L141-L171
train
firebase/firebaseui-web
javascript/widgets/handler/phonesigninfinish.js
function(error) { if (error['name'] && error['name'] == 'cancel') { // Close dialog. component.dismissDialog(); return; } // Get error message. var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); // Some errors are recoverable while others require resending the code. switch (error['code']) { case 'auth/credential-already-in-use': // Do nothing when anonymous user is getting upgraded. // Developer should handle this in signInFailure callback. component.dismissDialog(); break; case 'auth/code-expired': // Expired code requires sending another request. // Render previous phone sign in start page and display error in // the info bar. var container = component.getContainer(); // Close dialog. component.dismissDialog(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app, container, phoneNumberValue, errorMessage); break; case 'auth/missing-verification-code': case 'auth/invalid-verification-code': // Close dialog. component.dismissDialog(); // As these errors are related to the code provided, it is better // to display inline. showInvalidCode(errorMessage); break; default: // Close dialog. component.dismissDialog(); // Stay on the same page for all other errors and display error in // info bar. component.showInfoBar(errorMessage); break; } }
javascript
function(error) { if (error['name'] && error['name'] == 'cancel') { // Close dialog. component.dismissDialog(); return; } // Get error message. var errorMessage = firebaseui.auth.widget.handler.common.getErrorMessage(error); // Some errors are recoverable while others require resending the code. switch (error['code']) { case 'auth/credential-already-in-use': // Do nothing when anonymous user is getting upgraded. // Developer should handle this in signInFailure callback. component.dismissDialog(); break; case 'auth/code-expired': // Expired code requires sending another request. // Render previous phone sign in start page and display error in // the info bar. var container = component.getContainer(); // Close dialog. component.dismissDialog(); component.dispose(); firebaseui.auth.widget.handler.handle( firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app, container, phoneNumberValue, errorMessage); break; case 'auth/missing-verification-code': case 'auth/invalid-verification-code': // Close dialog. component.dismissDialog(); // As these errors are related to the code provided, it is better // to display inline. showInvalidCode(errorMessage); break; default: // Close dialog. component.dismissDialog(); // Stay on the same page for all other errors and display error in // info bar. component.showInfoBar(errorMessage); break; } }
[ "function", "(", "error", ")", "{", "if", "(", "error", "[", "'name'", "]", "&&", "error", "[", "'name'", "]", "==", "'cancel'", ")", "{", "component", ".", "dismissDialog", "(", ")", ";", "return", ";", "}", "var", "errorMessage", "=", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "common", ".", "getErrorMessage", "(", "error", ")", ";", "switch", "(", "error", "[", "'code'", "]", ")", "{", "case", "'auth/credential-already-in-use'", ":", "component", ".", "dismissDialog", "(", ")", ";", "break", ";", "case", "'auth/code-expired'", ":", "var", "container", "=", "component", ".", "getContainer", "(", ")", ";", "component", ".", "dismissDialog", "(", ")", ";", "component", ".", "dispose", "(", ")", ";", "firebaseui", ".", "auth", ".", "widget", ".", "handler", ".", "handle", "(", "firebaseui", ".", "auth", ".", "widget", ".", "HandlerName", ".", "PHONE_SIGN_IN_START", ",", "app", ",", "container", ",", "phoneNumberValue", ",", "errorMessage", ")", ";", "break", ";", "case", "'auth/missing-verification-code'", ":", "case", "'auth/invalid-verification-code'", ":", "component", ".", "dismissDialog", "(", ")", ";", "showInvalidCode", "(", "errorMessage", ")", ";", "break", ";", "default", ":", "component", ".", "dismissDialog", "(", ")", ";", "component", ".", "showInfoBar", "(", "errorMessage", ")", ";", "break", ";", "}", "}" ]
On code verification failure.
[ "On", "code", "verification", "failure", "." ]
c10aa51e38aeb38dc63baa22b48cd6690c2be087
https://github.com/firebase/firebaseui-web/blob/c10aa51e38aeb38dc63baa22b48cd6690c2be087/javascript/widgets/handler/phonesigninfinish.js#L173-L217
train
immerjs/immer
src/es5.js
markChangesSweep
function markChangesSweep(drafts) { // The natural order of drafts in the `scope` array is based on when they // were accessed. By processing drafts in reverse natural order, we have a // better chance of processing leaf nodes first. When a leaf node is known to // have changed, we can avoid any traversal of its ancestor nodes. for (let i = drafts.length - 1; i >= 0; i--) { const state = drafts[i][DRAFT_STATE] if (!state.modified) { if (Array.isArray(state.base)) { if (hasArrayChanges(state)) markChanged(state) } else if (hasObjectChanges(state)) markChanged(state) } } }
javascript
function markChangesSweep(drafts) { // The natural order of drafts in the `scope` array is based on when they // were accessed. By processing drafts in reverse natural order, we have a // better chance of processing leaf nodes first. When a leaf node is known to // have changed, we can avoid any traversal of its ancestor nodes. for (let i = drafts.length - 1; i >= 0; i--) { const state = drafts[i][DRAFT_STATE] if (!state.modified) { if (Array.isArray(state.base)) { if (hasArrayChanges(state)) markChanged(state) } else if (hasObjectChanges(state)) markChanged(state) } } }
[ "function", "markChangesSweep", "(", "drafts", ")", "{", "for", "(", "let", "i", "=", "drafts", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "const", "state", "=", "drafts", "[", "i", "]", "[", "DRAFT_STATE", "]", "if", "(", "!", "state", ".", "modified", ")", "{", "if", "(", "Array", ".", "isArray", "(", "state", ".", "base", ")", ")", "{", "if", "(", "hasArrayChanges", "(", "state", ")", ")", "markChanged", "(", "state", ")", "}", "else", "if", "(", "hasObjectChanges", "(", "state", ")", ")", "markChanged", "(", "state", ")", "}", "}", "}" ]
This looks expensive, but only proxies are visited, and only objects without known changes are scanned.
[ "This", "looks", "expensive", "but", "only", "proxies", "are", "visited", "and", "only", "objects", "without", "known", "changes", "are", "scanned", "." ]
4443cace6c23d14536955ce5b2aec92c8c76cacc
https://github.com/immerjs/immer/blob/4443cace6c23d14536955ce5b2aec92c8c76cacc/src/es5.js#L156-L169
train
postcss/autoprefixer
lib/prefixer.js
clone
function clone (obj, parent) { let cloned = new obj.constructor() for (let i of Object.keys(obj || {})) { let value = obj[i] if (i === 'parent' && typeof value === 'object') { if (parent) { cloned[i] = parent } } else if (i === 'source' || i === null) { cloned[i] = value } else if (value instanceof Array) { cloned[i] = value.map(x => clone(x, cloned)) } else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') { if (typeof value === 'object' && value !== null) { value = clone(value, cloned) } cloned[i] = value } } return cloned }
javascript
function clone (obj, parent) { let cloned = new obj.constructor() for (let i of Object.keys(obj || {})) { let value = obj[i] if (i === 'parent' && typeof value === 'object') { if (parent) { cloned[i] = parent } } else if (i === 'source' || i === null) { cloned[i] = value } else if (value instanceof Array) { cloned[i] = value.map(x => clone(x, cloned)) } else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') { if (typeof value === 'object' && value !== null) { value = clone(value, cloned) } cloned[i] = value } } return cloned }
[ "function", "clone", "(", "obj", ",", "parent", ")", "{", "let", "cloned", "=", "new", "obj", ".", "constructor", "(", ")", "for", "(", "let", "i", "of", "Object", ".", "keys", "(", "obj", "||", "{", "}", ")", ")", "{", "let", "value", "=", "obj", "[", "i", "]", "if", "(", "i", "===", "'parent'", "&&", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "parent", ")", "{", "cloned", "[", "i", "]", "=", "parent", "}", "}", "else", "if", "(", "i", "===", "'source'", "||", "i", "===", "null", ")", "{", "cloned", "[", "i", "]", "=", "value", "}", "else", "if", "(", "value", "instanceof", "Array", ")", "{", "cloned", "[", "i", "]", "=", "value", ".", "map", "(", "x", "=>", "clone", "(", "x", ",", "cloned", ")", ")", "}", "else", "if", "(", "i", "!==", "'_autoprefixerPrefix'", "&&", "i", "!==", "'_autoprefixerValues'", ")", "{", "if", "(", "typeof", "value", "===", "'object'", "&&", "value", "!==", "null", ")", "{", "value", "=", "clone", "(", "value", ",", "cloned", ")", "}", "cloned", "[", "i", "]", "=", "value", "}", "}", "return", "cloned", "}" ]
Recursively clone objects
[ "Recursively", "clone", "objects" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/prefixer.js#L9-L31
train
postcss/autoprefixer
data/prefixes.js
f
function f (data, opts, callback) { data = unpack(data) if (!callback) { [callback, opts] = [opts, {}] } let match = opts.match || /\sx($|\s)/ let need = [] for (let browser in data.stats) { let versions = data.stats[browser] for (let version in versions) { let support = versions[version] if (support.match(match)) { need.push(browser + ' ' + version) } } } callback(need.sort(browsersSort)) }
javascript
function f (data, opts, callback) { data = unpack(data) if (!callback) { [callback, opts] = [opts, {}] } let match = opts.match || /\sx($|\s)/ let need = [] for (let browser in data.stats) { let versions = data.stats[browser] for (let version in versions) { let support = versions[version] if (support.match(match)) { need.push(browser + ' ' + version) } } } callback(need.sort(browsersSort)) }
[ "function", "f", "(", "data", ",", "opts", ",", "callback", ")", "{", "data", "=", "unpack", "(", "data", ")", "if", "(", "!", "callback", ")", "{", "[", "callback", ",", "opts", "]", "=", "[", "opts", ",", "{", "}", "]", "}", "let", "match", "=", "opts", ".", "match", "||", "/", "\\sx($|\\s)", "/", "let", "need", "=", "[", "]", "for", "(", "let", "browser", "in", "data", ".", "stats", ")", "{", "let", "versions", "=", "data", ".", "stats", "[", "browser", "]", "for", "(", "let", "version", "in", "versions", ")", "{", "let", "support", "=", "versions", "[", "version", "]", "if", "(", "support", ".", "match", "(", "match", ")", ")", "{", "need", ".", "push", "(", "browser", "+", "' '", "+", "version", ")", "}", "}", "}", "callback", "(", "need", ".", "sort", "(", "browsersSort", ")", ")", "}" ]
Convert Can I Use data
[ "Convert", "Can", "I", "Use", "data" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/data/prefixes.js#L18-L39
train
postcss/autoprefixer
lib/hacks/grid-utils.js
getMSDecls
function getMSDecls (area, addRowSpan = false, addColumnSpan = false) { return [].concat( { prop: '-ms-grid-row', value: String(area.row.start) }, (area.row.span > 1 || addRowSpan) ? { prop: '-ms-grid-row-span', value: String(area.row.span) } : [], { prop: '-ms-grid-column', value: String(area.column.start) }, (area.column.span > 1 || addColumnSpan) ? { prop: '-ms-grid-column-span', value: String(area.column.span) } : [] ) }
javascript
function getMSDecls (area, addRowSpan = false, addColumnSpan = false) { return [].concat( { prop: '-ms-grid-row', value: String(area.row.start) }, (area.row.span > 1 || addRowSpan) ? { prop: '-ms-grid-row-span', value: String(area.row.span) } : [], { prop: '-ms-grid-column', value: String(area.column.start) }, (area.column.span > 1 || addColumnSpan) ? { prop: '-ms-grid-column-span', value: String(area.column.span) } : [] ) }
[ "function", "getMSDecls", "(", "area", ",", "addRowSpan", "=", "false", ",", "addColumnSpan", "=", "false", ")", "{", "return", "[", "]", ".", "concat", "(", "{", "prop", ":", "'-ms-grid-row'", ",", "value", ":", "String", "(", "area", ".", "row", ".", "start", ")", "}", ",", "(", "area", ".", "row", ".", "span", ">", "1", "||", "addRowSpan", ")", "?", "{", "prop", ":", "'-ms-grid-row-span'", ",", "value", ":", "String", "(", "area", ".", "row", ".", "span", ")", "}", ":", "[", "]", ",", "{", "prop", ":", "'-ms-grid-column'", ",", "value", ":", "String", "(", "area", ".", "column", ".", "start", ")", "}", ",", "(", "area", ".", "column", ".", "span", ">", "1", "||", "addColumnSpan", ")", "?", "{", "prop", ":", "'-ms-grid-column-span'", ",", "value", ":", "String", "(", "area", ".", "column", ".", "span", ")", "}", ":", "[", "]", ")", "}" ]
Insert parsed grid areas Get an array of -ms- prefixed props and values @param {Object} [area] area object with column and row data @param {Boolean} [addRowSpan] should we add grid-column-row value? @param {Boolean} [addColumnSpan] should we add grid-column-span value? @return {Array<Object>}
[ "Insert", "parsed", "grid", "areas", "Get", "an", "array", "of", "-", "ms", "-", "prefixed", "props", "and", "values" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L276-L295
train
postcss/autoprefixer
lib/hacks/grid-utils.js
changeDuplicateAreaSelectors
function changeDuplicateAreaSelectors (ruleSelectors, templateSelectors) { ruleSelectors = ruleSelectors.map(selector => { let selectorBySpace = list.space(selector) let selectorByComma = list.comma(selector) if (selectorBySpace.length > selectorByComma.length) { selector = selectorBySpace.slice(-1).join('') } return selector }) return ruleSelectors.map(ruleSelector => { let newSelector = templateSelectors.map((tplSelector, index) => { let space = index === 0 ? '' : ' ' return `${ space }${ tplSelector } > ${ ruleSelector }` }) return newSelector }) }
javascript
function changeDuplicateAreaSelectors (ruleSelectors, templateSelectors) { ruleSelectors = ruleSelectors.map(selector => { let selectorBySpace = list.space(selector) let selectorByComma = list.comma(selector) if (selectorBySpace.length > selectorByComma.length) { selector = selectorBySpace.slice(-1).join('') } return selector }) return ruleSelectors.map(ruleSelector => { let newSelector = templateSelectors.map((tplSelector, index) => { let space = index === 0 ? '' : ' ' return `${ space }${ tplSelector } > ${ ruleSelector }` }) return newSelector }) }
[ "function", "changeDuplicateAreaSelectors", "(", "ruleSelectors", ",", "templateSelectors", ")", "{", "ruleSelectors", "=", "ruleSelectors", ".", "map", "(", "selector", "=>", "{", "let", "selectorBySpace", "=", "list", ".", "space", "(", "selector", ")", "let", "selectorByComma", "=", "list", ".", "comma", "(", "selector", ")", "if", "(", "selectorBySpace", ".", "length", ">", "selectorByComma", ".", "length", ")", "{", "selector", "=", "selectorBySpace", ".", "slice", "(", "-", "1", ")", ".", "join", "(", "''", ")", "}", "return", "selector", "}", ")", "return", "ruleSelectors", ".", "map", "(", "ruleSelector", "=>", "{", "let", "newSelector", "=", "templateSelectors", ".", "map", "(", "(", "tplSelector", ",", "index", ")", "=>", "{", "let", "space", "=", "index", "===", "0", "?", "''", ":", "' '", "return", "`", "${", "space", "}", "${", "tplSelector", "}", "${", "ruleSelector", "}", "`", "}", ")", "return", "newSelector", "}", ")", "}" ]
change selectors for rules with duplicate grid-areas. @param {Array<Rule>} rules @param {Array<String>} templateSelectors @return {Array<Rule>} rules with changed selectors
[ "change", "selectors", "for", "rules", "with", "duplicate", "grid", "-", "areas", "." ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L313-L332
train
postcss/autoprefixer
lib/hacks/grid-utils.js
selectorsEqual
function selectorsEqual (ruleA, ruleB) { return ruleA.selectors.some(sel => { return ruleB.selectors.some(s => s === sel) }) }
javascript
function selectorsEqual (ruleA, ruleB) { return ruleA.selectors.some(sel => { return ruleB.selectors.some(s => s === sel) }) }
[ "function", "selectorsEqual", "(", "ruleA", ",", "ruleB", ")", "{", "return", "ruleA", ".", "selectors", ".", "some", "(", "sel", "=>", "{", "return", "ruleB", ".", "selectors", ".", "some", "(", "s", "=>", "s", "===", "sel", ")", "}", ")", "}" ]
check if selector of rules are equal @param {Rule} ruleA @param {Rule} ruleB @return {Boolean}
[ "check", "if", "selector", "of", "rules", "are", "equal" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L340-L344
train
postcss/autoprefixer
lib/hacks/grid-utils.js
warnMissedAreas
function warnMissedAreas (areas, decl, result) { let missed = Object.keys(areas) decl.root().walkDecls('grid-area', gridArea => { missed = missed.filter(e => e !== gridArea.value) }) if (missed.length > 0) { decl.warn(result, 'Can not find grid areas: ' + missed.join(', ')) } return undefined }
javascript
function warnMissedAreas (areas, decl, result) { let missed = Object.keys(areas) decl.root().walkDecls('grid-area', gridArea => { missed = missed.filter(e => e !== gridArea.value) }) if (missed.length > 0) { decl.warn(result, 'Can not find grid areas: ' + missed.join(', ')) } return undefined }
[ "function", "warnMissedAreas", "(", "areas", ",", "decl", ",", "result", ")", "{", "let", "missed", "=", "Object", ".", "keys", "(", "areas", ")", "decl", ".", "root", "(", ")", ".", "walkDecls", "(", "'grid-area'", ",", "gridArea", "=>", "{", "missed", "=", "missed", ".", "filter", "(", "e", "=>", "e", "!==", "gridArea", ".", "value", ")", "}", ")", "if", "(", "missed", ".", "length", ">", "0", ")", "{", "decl", ".", "warn", "(", "result", ",", "'Can not find grid areas: '", "+", "missed", ".", "join", "(", "', '", ")", ")", "}", "return", "undefined", "}" ]
Warn user if grid area identifiers are not found @param {Object} areas @param {Declaration} decl @param {Result} result @return {void}
[ "Warn", "user", "if", "grid", "area", "identifiers", "are", "not", "found" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L653-L665
train
postcss/autoprefixer
lib/hacks/grid-utils.js
shouldInheritGap
function shouldInheritGap (selA, selB) { let result // get arrays of selector split in 3-deep array let splitSelectorArrA = splitSelector(selA) let splitSelectorArrB = splitSelector(selB) if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) { // abort if selectorA has lower descendant specificity then selectorB // (e.g '.grid' and '.hello .world .grid') return false } else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) { // if selectorA has higher descendant specificity then selectorB // (e.g '.foo .bar .grid' and '.grid') let idx = splitSelectorArrA[0].reduce((res, [item], index) => { let firstSelectorPart = splitSelectorArrB[0][0][0] if (item === firstSelectorPart) { return index } return false }, false) if (idx) { result = splitSelectorArrB[0].every((arr, index) => { return arr.every((part, innerIndex) => // because selectorA has more space elements, we need to slice // selectorA array by 'idx' number to compare them splitSelectorArrA[0].slice(idx)[index][innerIndex] === part) }) } } else { // if selectorA has the same descendant specificity as selectorB // this condition covers cases such as: '.grid.foo.bar' and '.grid' result = splitSelectorArrB.some(byCommaArr => { return byCommaArr.every((bySpaceArr, index) => { return bySpaceArr.every( (part, innerIndex) => splitSelectorArrA[0][index][innerIndex] === part ) }) }) } return result }
javascript
function shouldInheritGap (selA, selB) { let result // get arrays of selector split in 3-deep array let splitSelectorArrA = splitSelector(selA) let splitSelectorArrB = splitSelector(selB) if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) { // abort if selectorA has lower descendant specificity then selectorB // (e.g '.grid' and '.hello .world .grid') return false } else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) { // if selectorA has higher descendant specificity then selectorB // (e.g '.foo .bar .grid' and '.grid') let idx = splitSelectorArrA[0].reduce((res, [item], index) => { let firstSelectorPart = splitSelectorArrB[0][0][0] if (item === firstSelectorPart) { return index } return false }, false) if (idx) { result = splitSelectorArrB[0].every((arr, index) => { return arr.every((part, innerIndex) => // because selectorA has more space elements, we need to slice // selectorA array by 'idx' number to compare them splitSelectorArrA[0].slice(idx)[index][innerIndex] === part) }) } } else { // if selectorA has the same descendant specificity as selectorB // this condition covers cases such as: '.grid.foo.bar' and '.grid' result = splitSelectorArrB.some(byCommaArr => { return byCommaArr.every((bySpaceArr, index) => { return bySpaceArr.every( (part, innerIndex) => splitSelectorArrA[0][index][innerIndex] === part ) }) }) } return result }
[ "function", "shouldInheritGap", "(", "selA", ",", "selB", ")", "{", "let", "result", "let", "splitSelectorArrA", "=", "splitSelector", "(", "selA", ")", "let", "splitSelectorArrB", "=", "splitSelector", "(", "selB", ")", "if", "(", "splitSelectorArrA", "[", "0", "]", ".", "length", "<", "splitSelectorArrB", "[", "0", "]", ".", "length", ")", "{", "return", "false", "}", "else", "if", "(", "splitSelectorArrA", "[", "0", "]", ".", "length", ">", "splitSelectorArrB", "[", "0", "]", ".", "length", ")", "{", "let", "idx", "=", "splitSelectorArrA", "[", "0", "]", ".", "reduce", "(", "(", "res", ",", "[", "item", "]", ",", "index", ")", "=>", "{", "let", "firstSelectorPart", "=", "splitSelectorArrB", "[", "0", "]", "[", "0", "]", "[", "0", "]", "if", "(", "item", "===", "firstSelectorPart", ")", "{", "return", "index", "}", "return", "false", "}", ",", "false", ")", "if", "(", "idx", ")", "{", "result", "=", "splitSelectorArrB", "[", "0", "]", ".", "every", "(", "(", "arr", ",", "index", ")", "=>", "{", "return", "arr", ".", "every", "(", "(", "part", ",", "innerIndex", ")", "=>", "splitSelectorArrA", "[", "0", "]", ".", "slice", "(", "idx", ")", "[", "index", "]", "[", "innerIndex", "]", "===", "part", ")", "}", ")", "}", "}", "else", "{", "result", "=", "splitSelectorArrB", ".", "some", "(", "byCommaArr", "=>", "{", "return", "byCommaArr", ".", "every", "(", "(", "bySpaceArr", ",", "index", ")", "=>", "{", "return", "bySpaceArr", ".", "every", "(", "(", "part", ",", "innerIndex", ")", "=>", "splitSelectorArrA", "[", "0", "]", "[", "index", "]", "[", "innerIndex", "]", "===", "part", ")", "}", ")", "}", ")", "}", "return", "result", "}" ]
Compare the selectors and decide if we need to inherit gap from compared selector or not. @type {String} selA @type {String} selB @return {Boolean}
[ "Compare", "the", "selectors", "and", "decide", "if", "we", "need", "to", "inherit", "gap", "from", "compared", "selector", "or", "not", "." ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L819-L863
train
postcss/autoprefixer
lib/hacks/grid-utils.js
inheritGridGap
function inheritGridGap (decl, gap) { let rule = decl.parent let mediaRule = getParentMedia(rule) let root = rule.root() // get an array of selector split in 3-deep array let splitSelectorArr = splitSelector(rule.selector) // abort if the rule already has gaps if (Object.keys(gap).length > 0) { return false } // e.g ['min-width'] let [prop] = parseMediaParams(mediaRule.params) let lastBySpace = splitSelectorArr[0] // get escaped value from the selector // if we have '.grid-2.foo.bar' selector, will be '\.grid\-2' let escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0]) let regexp = new RegExp(`(${ escaped }$)|(${ escaped }[,.])`) // find the closest rule with the same selector let closestRuleGap root.walkRules(regexp, r => { let gridGap // abort if are checking the same rule if (rule.toString() === r.toString()) { return false } // find grid-gap values r.walkDecls('grid-gap', d => (gridGap = getGridGap(d))) // skip rule without gaps if (!gridGap || Object.keys(gridGap).length === 0) { return true } // skip rules that should not be inherited from if (!shouldInheritGap(rule.selector, r.selector)) { return true } let media = getParentMedia(r) if (media) { // if we are inside media, we need to check that media props match // e.g ('min-width' === 'min-width') let propToCompare = parseMediaParams(media.params)[0] if (propToCompare === prop) { closestRuleGap = gridGap return true } } else { closestRuleGap = gridGap return true } return undefined }) // if we find the closest gap object if (closestRuleGap && Object.keys(closestRuleGap).length > 0) { return closestRuleGap } return false }
javascript
function inheritGridGap (decl, gap) { let rule = decl.parent let mediaRule = getParentMedia(rule) let root = rule.root() // get an array of selector split in 3-deep array let splitSelectorArr = splitSelector(rule.selector) // abort if the rule already has gaps if (Object.keys(gap).length > 0) { return false } // e.g ['min-width'] let [prop] = parseMediaParams(mediaRule.params) let lastBySpace = splitSelectorArr[0] // get escaped value from the selector // if we have '.grid-2.foo.bar' selector, will be '\.grid\-2' let escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0]) let regexp = new RegExp(`(${ escaped }$)|(${ escaped }[,.])`) // find the closest rule with the same selector let closestRuleGap root.walkRules(regexp, r => { let gridGap // abort if are checking the same rule if (rule.toString() === r.toString()) { return false } // find grid-gap values r.walkDecls('grid-gap', d => (gridGap = getGridGap(d))) // skip rule without gaps if (!gridGap || Object.keys(gridGap).length === 0) { return true } // skip rules that should not be inherited from if (!shouldInheritGap(rule.selector, r.selector)) { return true } let media = getParentMedia(r) if (media) { // if we are inside media, we need to check that media props match // e.g ('min-width' === 'min-width') let propToCompare = parseMediaParams(media.params)[0] if (propToCompare === prop) { closestRuleGap = gridGap return true } } else { closestRuleGap = gridGap return true } return undefined }) // if we find the closest gap object if (closestRuleGap && Object.keys(closestRuleGap).length > 0) { return closestRuleGap } return false }
[ "function", "inheritGridGap", "(", "decl", ",", "gap", ")", "{", "let", "rule", "=", "decl", ".", "parent", "let", "mediaRule", "=", "getParentMedia", "(", "rule", ")", "let", "root", "=", "rule", ".", "root", "(", ")", "let", "splitSelectorArr", "=", "splitSelector", "(", "rule", ".", "selector", ")", "if", "(", "Object", ".", "keys", "(", "gap", ")", ".", "length", ">", "0", ")", "{", "return", "false", "}", "let", "[", "prop", "]", "=", "parseMediaParams", "(", "mediaRule", ".", "params", ")", "let", "lastBySpace", "=", "splitSelectorArr", "[", "0", "]", "let", "escaped", "=", "escapeRegexp", "(", "lastBySpace", "[", "lastBySpace", ".", "length", "-", "1", "]", "[", "0", "]", ")", "let", "regexp", "=", "new", "RegExp", "(", "`", "${", "escaped", "}", "${", "escaped", "}", "`", ")", "let", "closestRuleGap", "root", ".", "walkRules", "(", "regexp", ",", "r", "=>", "{", "let", "gridGap", "if", "(", "rule", ".", "toString", "(", ")", "===", "r", ".", "toString", "(", ")", ")", "{", "return", "false", "}", "r", ".", "walkDecls", "(", "'grid-gap'", ",", "d", "=>", "(", "gridGap", "=", "getGridGap", "(", "d", ")", ")", ")", "if", "(", "!", "gridGap", "||", "Object", ".", "keys", "(", "gridGap", ")", ".", "length", "===", "0", ")", "{", "return", "true", "}", "if", "(", "!", "shouldInheritGap", "(", "rule", ".", "selector", ",", "r", ".", "selector", ")", ")", "{", "return", "true", "}", "let", "media", "=", "getParentMedia", "(", "r", ")", "if", "(", "media", ")", "{", "let", "propToCompare", "=", "parseMediaParams", "(", "media", ".", "params", ")", "[", "0", "]", "if", "(", "propToCompare", "===", "prop", ")", "{", "closestRuleGap", "=", "gridGap", "return", "true", "}", "}", "else", "{", "closestRuleGap", "=", "gridGap", "return", "true", "}", "return", "undefined", "}", ")", "if", "(", "closestRuleGap", "&&", "Object", ".", "keys", "(", "closestRuleGap", ")", ".", "length", ">", "0", ")", "{", "return", "closestRuleGap", "}", "return", "false", "}" ]
inherit grid gap values from the closest rule above with the same selector @param {Declaration} decl @param {Object} gap gap values @return {Object | Boolean} return gap values or false (if not found)
[ "inherit", "grid", "gap", "values", "from", "the", "closest", "rule", "above", "with", "the", "same", "selector" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L871-L940
train
postcss/autoprefixer
lib/hacks/grid-utils.js
autoplaceGridItems
function autoplaceGridItems (decl, result, gap, autoflowValue = 'row') { let { parent } = decl let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows') let rows = normalizeRowColumn(rowDecl.value) let columns = normalizeRowColumn(decl.value) // Build array of area names with dummy values. If we have 3 columns and // 2 rows, filledRows will be equal to ['1 2 3', '4 5 6'] let filledRows = rows.map((_, rowIndex) => { return Array.from({ length: columns.length }, (v, k) => k + (rowIndex * columns.length) + 1).join(' ') }) let areas = parseGridAreas({ rows: filledRows, gap }) let keys = Object.keys(areas) let items = keys.map(i => areas[i]) // Change the order of cells if grid-auto-flow value is 'column' if (autoflowValue.includes('column')) { items = items.sort((a, b) => a.column.start - b.column.start) } // Insert new rules items.reverse().forEach((item, index) => { let { column, row } = item let nodeSelector = parent.selectors.map(sel => sel + ` > *:nth-child(${ keys.length - index })`).join(', ') // create new rule let node = parent.clone().removeAll() // change rule selector node.selector = nodeSelector // insert prefixed row/column values node.append({ prop: '-ms-grid-row', value: row.start }) node.append({ prop: '-ms-grid-column', value: column.start }) // insert rule parent.after(node) }) return undefined }
javascript
function autoplaceGridItems (decl, result, gap, autoflowValue = 'row') { let { parent } = decl let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows') let rows = normalizeRowColumn(rowDecl.value) let columns = normalizeRowColumn(decl.value) // Build array of area names with dummy values. If we have 3 columns and // 2 rows, filledRows will be equal to ['1 2 3', '4 5 6'] let filledRows = rows.map((_, rowIndex) => { return Array.from({ length: columns.length }, (v, k) => k + (rowIndex * columns.length) + 1).join(' ') }) let areas = parseGridAreas({ rows: filledRows, gap }) let keys = Object.keys(areas) let items = keys.map(i => areas[i]) // Change the order of cells if grid-auto-flow value is 'column' if (autoflowValue.includes('column')) { items = items.sort((a, b) => a.column.start - b.column.start) } // Insert new rules items.reverse().forEach((item, index) => { let { column, row } = item let nodeSelector = parent.selectors.map(sel => sel + ` > *:nth-child(${ keys.length - index })`).join(', ') // create new rule let node = parent.clone().removeAll() // change rule selector node.selector = nodeSelector // insert prefixed row/column values node.append({ prop: '-ms-grid-row', value: row.start }) node.append({ prop: '-ms-grid-column', value: column.start }) // insert rule parent.after(node) }) return undefined }
[ "function", "autoplaceGridItems", "(", "decl", ",", "result", ",", "gap", ",", "autoflowValue", "=", "'row'", ")", "{", "let", "{", "parent", "}", "=", "decl", "let", "rowDecl", "=", "parent", ".", "nodes", ".", "find", "(", "i", "=>", "i", ".", "prop", "===", "'grid-template-rows'", ")", "let", "rows", "=", "normalizeRowColumn", "(", "rowDecl", ".", "value", ")", "let", "columns", "=", "normalizeRowColumn", "(", "decl", ".", "value", ")", "let", "filledRows", "=", "rows", ".", "map", "(", "(", "_", ",", "rowIndex", ")", "=>", "{", "return", "Array", ".", "from", "(", "{", "length", ":", "columns", ".", "length", "}", ",", "(", "v", ",", "k", ")", "=>", "k", "+", "(", "rowIndex", "*", "columns", ".", "length", ")", "+", "1", ")", ".", "join", "(", "' '", ")", "}", ")", "let", "areas", "=", "parseGridAreas", "(", "{", "rows", ":", "filledRows", ",", "gap", "}", ")", "let", "keys", "=", "Object", ".", "keys", "(", "areas", ")", "let", "items", "=", "keys", ".", "map", "(", "i", "=>", "areas", "[", "i", "]", ")", "if", "(", "autoflowValue", ".", "includes", "(", "'column'", ")", ")", "{", "items", "=", "items", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "column", ".", "start", "-", "b", ".", "column", ".", "start", ")", "}", "items", ".", "reverse", "(", ")", ".", "forEach", "(", "(", "item", ",", "index", ")", "=>", "{", "let", "{", "column", ",", "row", "}", "=", "item", "let", "nodeSelector", "=", "parent", ".", "selectors", ".", "map", "(", "sel", "=>", "sel", "+", "`", "${", "keys", ".", "length", "-", "index", "}", "`", ")", ".", "join", "(", "', '", ")", "let", "node", "=", "parent", ".", "clone", "(", ")", ".", "removeAll", "(", ")", "node", ".", "selector", "=", "nodeSelector", "node", ".", "append", "(", "{", "prop", ":", "'-ms-grid-row'", ",", "value", ":", "row", ".", "start", "}", ")", "node", ".", "append", "(", "{", "prop", ":", "'-ms-grid-column'", ",", "value", ":", "column", ".", "start", "}", ")", "parent", ".", "after", "(", "node", ")", "}", ")", "return", "undefined", "}" ]
Autoplace grid items @param {Declaration} decl @param {Result} result @param {Object} gap gap values @param {String} autoflowValue grid-auto-flow value @return {void} @see https://github.com/postcss/autoprefixer/issues/1148
[ "Autoplace", "grid", "items" ]
24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32
https://github.com/postcss/autoprefixer/blob/24b28b6dbdc34a5e5800986e76f48cbaf9bbbc32/lib/hacks/grid-utils.js#L1014-L1058
train
showdownjs/showdown
dist/showdown.js
substitutePreCodeTags
function substitutePreCodeTags (doc) { var pres = doc.querySelectorAll('pre'), presPH = []; for (var i = 0; i < pres.length; ++i) { if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') { var content = pres[i].firstChild.innerHTML.trim(), language = pres[i].firstChild.getAttribute('data-language') || ''; // if data-language attribute is not defined, then we look for class language-* if (language === '') { var classes = pres[i].firstChild.className.split(' '); for (var c = 0; c < classes.length; ++c) { var matches = classes[c].match(/^language-(.+)$/); if (matches !== null) { language = matches[1]; break; } } } // unescape html entities in content content = showdown.helper.unescapeHTMLEntities(content); presPH.push(content); pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>'; } else { presPH.push(pres[i].innerHTML); pres[i].innerHTML = ''; pres[i].setAttribute('prenum', i.toString()); } } return presPH; }
javascript
function substitutePreCodeTags (doc) { var pres = doc.querySelectorAll('pre'), presPH = []; for (var i = 0; i < pres.length; ++i) { if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') { var content = pres[i].firstChild.innerHTML.trim(), language = pres[i].firstChild.getAttribute('data-language') || ''; // if data-language attribute is not defined, then we look for class language-* if (language === '') { var classes = pres[i].firstChild.className.split(' '); for (var c = 0; c < classes.length; ++c) { var matches = classes[c].match(/^language-(.+)$/); if (matches !== null) { language = matches[1]; break; } } } // unescape html entities in content content = showdown.helper.unescapeHTMLEntities(content); presPH.push(content); pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>'; } else { presPH.push(pres[i].innerHTML); pres[i].innerHTML = ''; pres[i].setAttribute('prenum', i.toString()); } } return presPH; }
[ "function", "substitutePreCodeTags", "(", "doc", ")", "{", "var", "pres", "=", "doc", ".", "querySelectorAll", "(", "'pre'", ")", ",", "presPH", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pres", ".", "length", ";", "++", "i", ")", "{", "if", "(", "pres", "[", "i", "]", ".", "childElementCount", "===", "1", "&&", "pres", "[", "i", "]", ".", "firstChild", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "'code'", ")", "{", "var", "content", "=", "pres", "[", "i", "]", ".", "firstChild", ".", "innerHTML", ".", "trim", "(", ")", ",", "language", "=", "pres", "[", "i", "]", ".", "firstChild", ".", "getAttribute", "(", "'data-language'", ")", "||", "''", ";", "if", "(", "language", "===", "''", ")", "{", "var", "classes", "=", "pres", "[", "i", "]", ".", "firstChild", ".", "className", ".", "split", "(", "' '", ")", ";", "for", "(", "var", "c", "=", "0", ";", "c", "<", "classes", ".", "length", ";", "++", "c", ")", "{", "var", "matches", "=", "classes", "[", "c", "]", ".", "match", "(", "/", "^language-(.+)$", "/", ")", ";", "if", "(", "matches", "!==", "null", ")", "{", "language", "=", "matches", "[", "1", "]", ";", "break", ";", "}", "}", "}", "content", "=", "showdown", ".", "helper", ".", "unescapeHTMLEntities", "(", "content", ")", ";", "presPH", ".", "push", "(", "content", ")", ";", "pres", "[", "i", "]", ".", "outerHTML", "=", "'<precode language=\"'", "+", "language", "+", "'\" precodenum=\"'", "+", "i", ".", "toString", "(", ")", "+", "'\"></precode>'", ";", "}", "else", "{", "presPH", ".", "push", "(", "pres", "[", "i", "]", ".", "innerHTML", ")", ";", "pres", "[", "i", "]", ".", "innerHTML", "=", "''", ";", "pres", "[", "i", "]", ".", "setAttribute", "(", "'prenum'", ",", "i", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "presPH", ";", "}" ]
find all pre tags and replace contents with placeholder we need this so that we can remove all indentation from html to ease up parsing
[ "find", "all", "pre", "tags", "and", "replace", "contents", "with", "placeholder", "we", "need", "this", "so", "that", "we", "can", "remove", "all", "indentation", "from", "html", "to", "ease", "up", "parsing" ]
33bba54535d6fcdde5c82d2ec4d7a3bd951b5bb9
https://github.com/showdownjs/showdown/blob/33bba54535d6fcdde5c82d2ec4d7a3bd951b5bb9/dist/showdown.js#L5249-L5284
train
firebase/firebase-js-sdk
packages/auth/demo/public/web-worker.js
function() { return new Promise(function(resolve, reject) { firebase.auth().onAuthStateChanged(function(user) { if (user) { user.getIdToken().then(function(idToken) { resolve(idToken); }, function(error) { resolve(null); }); } else { resolve(null); } }); }).catch(function(error) { console.log(error); }); }
javascript
function() { return new Promise(function(resolve, reject) { firebase.auth().onAuthStateChanged(function(user) { if (user) { user.getIdToken().then(function(idToken) { resolve(idToken); }, function(error) { resolve(null); }); } else { resolve(null); } }); }).catch(function(error) { console.log(error); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "firebase", ".", "auth", "(", ")", ".", "onAuthStateChanged", "(", "function", "(", "user", ")", "{", "if", "(", "user", ")", "{", "user", ".", "getIdToken", "(", ")", ".", "then", "(", "function", "(", "idToken", ")", "{", "resolve", "(", "idToken", ")", ";", "}", ",", "function", "(", "error", ")", "{", "resolve", "(", "null", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "null", ")", ";", "}", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "console", ".", "log", "(", "error", ")", ";", "}", ")", ";", "}" ]
Returns a promise that resolves with an ID token if available. @return {!Promise<?string>} The promise that resolves with an ID token if available. Otherwise, the promise resolves with null.
[ "Returns", "a", "promise", "that", "resolves", "with", "an", "ID", "token", "if", "available", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/web-worker.js#L36-L52
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
runTypedoc
function runTypedoc() { const typeSource = apiType === 'node' ? tempNodeSourcePath : sourceFile; const command = `${repoPath}/node_modules/.bin/typedoc ${typeSource} \ --out ${docPath} \ --readme ${tempHomePath} \ --options ${__dirname}/typedoc.js \ --theme ${__dirname}/theme`; console.log('Running command:\n', command); return exec(command); }
javascript
function runTypedoc() { const typeSource = apiType === 'node' ? tempNodeSourcePath : sourceFile; const command = `${repoPath}/node_modules/.bin/typedoc ${typeSource} \ --out ${docPath} \ --readme ${tempHomePath} \ --options ${__dirname}/typedoc.js \ --theme ${__dirname}/theme`; console.log('Running command:\n', command); return exec(command); }
[ "function", "runTypedoc", "(", ")", "{", "const", "typeSource", "=", "apiType", "===", "'node'", "?", "tempNodeSourcePath", ":", "sourceFile", ";", "const", "command", "=", "`", "${", "repoPath", "}", "${", "typeSource", "}", "\\", "${", "docPath", "}", "\\", "${", "tempHomePath", "}", "\\", "${", "__dirname", "}", "\\", "${", "__dirname", "}", "`", ";", "console", ".", "log", "(", "'Running command:\\n'", ",", "\\n", ")", ";", "command", "}" ]
Runs Typedoc command. Additional config options come from ./typedoc.js
[ "Runs", "Typedoc", "command", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L62-L72
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
moveFilesToRoot
function moveFilesToRoot(subdir) { return exec(`mv ${docPath}/${subdir}/* ${docPath}`) .then(() => { exec(`rmdir ${docPath}/${subdir}`); }) .catch(e => console.error(e)); }
javascript
function moveFilesToRoot(subdir) { return exec(`mv ${docPath}/${subdir}/* ${docPath}`) .then(() => { exec(`rmdir ${docPath}/${subdir}`); }) .catch(e => console.error(e)); }
[ "function", "moveFilesToRoot", "(", "subdir", ")", "{", "return", "exec", "(", "`", "${", "docPath", "}", "${", "subdir", "}", "${", "docPath", "}", "`", ")", ".", "then", "(", "(", ")", "=>", "{", "exec", "(", "`", "${", "docPath", "}", "${", "subdir", "}", "`", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "console", ".", "error", "(", "e", ")", ")", ";", "}" ]
Moves files from subdir to root. @param {string} subdir Subdir to move files out of.
[ "Moves", "files", "from", "subdir", "to", "root", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L78-L84
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
fixLinks
function fixLinks(file) { return fs.readFile(file, 'utf8').then(data => { const flattenedLinks = data .replace(/\.\.\//g, '') .replace(/(modules|interfaces|classes)\//g, ''); let caseFixedLinks = flattenedLinks; for (const lower in lowerToUpperLookup) { const re = new RegExp(lower, 'g'); caseFixedLinks = caseFixedLinks.replace(re, lowerToUpperLookup[lower]); } return fs.writeFile(file, caseFixedLinks); }); }
javascript
function fixLinks(file) { return fs.readFile(file, 'utf8').then(data => { const flattenedLinks = data .replace(/\.\.\//g, '') .replace(/(modules|interfaces|classes)\//g, ''); let caseFixedLinks = flattenedLinks; for (const lower in lowerToUpperLookup) { const re = new RegExp(lower, 'g'); caseFixedLinks = caseFixedLinks.replace(re, lowerToUpperLookup[lower]); } return fs.writeFile(file, caseFixedLinks); }); }
[ "function", "fixLinks", "(", "file", ")", "{", "return", "fs", ".", "readFile", "(", "file", ",", "'utf8'", ")", ".", "then", "(", "data", "=>", "{", "const", "flattenedLinks", "=", "data", ".", "replace", "(", "/", "\\.\\.\\/", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "(modules|interfaces|classes)\\/", "/", "g", ",", "''", ")", ";", "let", "caseFixedLinks", "=", "flattenedLinks", ";", "for", "(", "const", "lower", "in", "lowerToUpperLookup", ")", "{", "const", "re", "=", "new", "RegExp", "(", "lower", ",", "'g'", ")", ";", "caseFixedLinks", "=", "caseFixedLinks", ".", "replace", "(", "re", ",", "lowerToUpperLookup", "[", "lower", "]", ")", ";", "}", "return", "fs", ".", "writeFile", "(", "file", ",", "caseFixedLinks", ")", ";", "}", ")", ";", "}" ]
Reformat links to match flat structure. @param {string} file File to fix links in.
[ "Reformat", "links", "to", "match", "flat", "structure", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L90-L102
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
generateTempHomeMdFile
function generateTempHomeMdFile(tocRaw, homeRaw) { const { toc } = yaml.safeLoad(tocRaw); let tocPageLines = [homeRaw, '# API Reference']; toc.forEach(group => { tocPageLines.push(`\n## [${group.title}](${stripPath(group.path)}.html)`); group.section.forEach(item => { tocPageLines.push(`- [${item.title}](${stripPath(item.path)}.html)`); }); }); return fs.writeFile(tempHomePath, tocPageLines.join('\n')); }
javascript
function generateTempHomeMdFile(tocRaw, homeRaw) { const { toc } = yaml.safeLoad(tocRaw); let tocPageLines = [homeRaw, '# API Reference']; toc.forEach(group => { tocPageLines.push(`\n## [${group.title}](${stripPath(group.path)}.html)`); group.section.forEach(item => { tocPageLines.push(`- [${item.title}](${stripPath(item.path)}.html)`); }); }); return fs.writeFile(tempHomePath, tocPageLines.join('\n')); }
[ "function", "generateTempHomeMdFile", "(", "tocRaw", ",", "homeRaw", ")", "{", "const", "{", "toc", "}", "=", "yaml", ".", "safeLoad", "(", "tocRaw", ")", ";", "let", "tocPageLines", "=", "[", "homeRaw", ",", "'# API Reference'", "]", ";", "toc", ".", "forEach", "(", "group", "=>", "{", "tocPageLines", ".", "push", "(", "`", "\\n", "${", "group", ".", "title", "}", "${", "stripPath", "(", "group", ".", "path", ")", "}", "`", ")", ";", "group", ".", "section", ".", "forEach", "(", "item", "=>", "{", "tocPageLines", ".", "push", "(", "`", "${", "item", ".", "title", "}", "${", "stripPath", "(", "item", ".", "path", ")", "}", "`", ")", ";", "}", ")", ";", "}", ")", ";", "return", "fs", ".", "writeFile", "(", "tempHomePath", ",", "tocPageLines", ".", "join", "(", "'\\n'", ")", ")", ";", "}" ]
Generates temporary markdown file that will be sourced by Typedoc to create index.html. @param {string} tocRaw @param {string} homeRaw
[ "Generates", "temporary", "markdown", "file", "that", "will", "be", "sourced", "by", "Typedoc", "to", "create", "index", ".", "html", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L113-L123
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
checkForMissingFilesAndFixFilenameCase
function checkForMissingFilesAndFixFilenameCase() { // Get filenames from toc.yaml. const filenames = tocText .split('\n') .filter(line => line.includes('path:')) .map(line => line.split(devsitePath)[1]); // Logs warning to console if a file from TOC is not found. const fileCheckPromises = filenames.map(filename => { // Warns if file does not exist, fixes filename case if it does. // Preferred filename for devsite should be capitalized and taken from // toc.yaml. const tocFilePath = `${docPath}/${filename}.html`; // Generated filename from Typedoc will be lowercase. const generatedFilePath = `${docPath}/${filename.toLowerCase()}.html`; return fs.exists(generatedFilePath).then(exists => { if (exists) { // Store in a lookup table for link fixing. lowerToUpperLookup[ `${filename.toLowerCase()}.html` ] = `${filename}.html`; return fs.rename(generatedFilePath, tocFilePath); } else { console.warn( `Missing file: ${filename}.html requested ` + `in toc.yaml but not found in ${docPath}` ); } }); }); return Promise.all(fileCheckPromises).then(() => filenames); }
javascript
function checkForMissingFilesAndFixFilenameCase() { // Get filenames from toc.yaml. const filenames = tocText .split('\n') .filter(line => line.includes('path:')) .map(line => line.split(devsitePath)[1]); // Logs warning to console if a file from TOC is not found. const fileCheckPromises = filenames.map(filename => { // Warns if file does not exist, fixes filename case if it does. // Preferred filename for devsite should be capitalized and taken from // toc.yaml. const tocFilePath = `${docPath}/${filename}.html`; // Generated filename from Typedoc will be lowercase. const generatedFilePath = `${docPath}/${filename.toLowerCase()}.html`; return fs.exists(generatedFilePath).then(exists => { if (exists) { // Store in a lookup table for link fixing. lowerToUpperLookup[ `${filename.toLowerCase()}.html` ] = `${filename}.html`; return fs.rename(generatedFilePath, tocFilePath); } else { console.warn( `Missing file: ${filename}.html requested ` + `in toc.yaml but not found in ${docPath}` ); } }); }); return Promise.all(fileCheckPromises).then(() => filenames); }
[ "function", "checkForMissingFilesAndFixFilenameCase", "(", ")", "{", "const", "filenames", "=", "tocText", ".", "split", "(", "'\\n'", ")", ".", "\\n", "filter", ".", "(", "line", "=>", "line", ".", "includes", "(", "'path:'", ")", ")", "map", ";", "(", "line", "=>", "line", ".", "split", "(", "devsitePath", ")", "[", "1", "]", ")", "const", "fileCheckPromises", "=", "filenames", ".", "map", "(", "filename", "=>", "{", "const", "tocFilePath", "=", "`", "${", "docPath", "}", "${", "filename", "}", "`", ";", "const", "generatedFilePath", "=", "`", "${", "docPath", "}", "${", "filename", ".", "toLowerCase", "(", ")", "}", "`", ";", "return", "fs", ".", "exists", "(", "generatedFilePath", ")", ".", "then", "(", "exists", "=>", "{", "if", "(", "exists", ")", "{", "lowerToUpperLookup", "[", "`", "${", "filename", ".", "toLowerCase", "(", ")", "}", "`", "]", "=", "`", "${", "filename", "}", "`", ";", "return", "fs", ".", "rename", "(", "generatedFilePath", ",", "tocFilePath", ")", ";", "}", "else", "{", "console", ".", "warn", "(", "`", "${", "filename", "}", "`", "+", "`", "${", "docPath", "}", "`", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Checks to see if any files listed in toc.yaml were not generated. If files exist, fixes filename case to match toc.yaml version.
[ "Checks", "to", "see", "if", "any", "files", "listed", "in", "toc", ".", "yaml", "were", "not", "generated", ".", "If", "files", "exist", "fixes", "filename", "case", "to", "match", "toc", ".", "yaml", "version", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L135-L165
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
writeGeneratedFileList
function writeGeneratedFileList(htmlFiles) { const fileList = htmlFiles.map(filename => { return { title: filename, path: `${devsitePath}${filename}` }; }); const generatedTocYAML = yaml.safeDump({ toc: fileList }); return fs .writeFile(`${docPath}/_toc_autogenerated.yaml`, generatedTocYAML) .then(() => htmlFiles); }
javascript
function writeGeneratedFileList(htmlFiles) { const fileList = htmlFiles.map(filename => { return { title: filename, path: `${devsitePath}${filename}` }; }); const generatedTocYAML = yaml.safeDump({ toc: fileList }); return fs .writeFile(`${docPath}/_toc_autogenerated.yaml`, generatedTocYAML) .then(() => htmlFiles); }
[ "function", "writeGeneratedFileList", "(", "htmlFiles", ")", "{", "const", "fileList", "=", "htmlFiles", ".", "map", "(", "filename", "=>", "{", "return", "{", "title", ":", "filename", ",", "path", ":", "`", "${", "devsitePath", "}", "${", "filename", "}", "`", "}", ";", "}", ")", ";", "const", "generatedTocYAML", "=", "yaml", ".", "safeDump", "(", "{", "toc", ":", "fileList", "}", ")", ";", "return", "fs", ".", "writeFile", "(", "`", "${", "docPath", "}", "`", ",", "generatedTocYAML", ")", ".", "then", "(", "(", ")", "=>", "htmlFiles", ")", ";", "}" ]
Writes a _toc_autogenerated.yaml as a record of all files that were autogenerated. Helpful to tech writers. @param {Array} htmlFiles List of html files found in generated dir.
[ "Writes", "a", "_toc_autogenerated", ".", "yaml", "as", "a", "record", "of", "all", "files", "that", "were", "autogenerated", ".", "Helpful", "to", "tech", "writers", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L218-L229
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
fixAllLinks
function fixAllLinks(htmlFiles) { const writePromises = []; htmlFiles.forEach(file => { // Update links in each html file to match flattened file structure. writePromises.push(fixLinks(`${docPath}/${file}.html`)); }); return Promise.all(writePromises); }
javascript
function fixAllLinks(htmlFiles) { const writePromises = []; htmlFiles.forEach(file => { // Update links in each html file to match flattened file structure. writePromises.push(fixLinks(`${docPath}/${file}.html`)); }); return Promise.all(writePromises); }
[ "function", "fixAllLinks", "(", "htmlFiles", ")", "{", "const", "writePromises", "=", "[", "]", ";", "htmlFiles", ".", "forEach", "(", "file", "=>", "{", "writePromises", ".", "push", "(", "fixLinks", "(", "`", "${", "docPath", "}", "${", "file", "}", "`", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "writePromises", ")", ";", "}" ]
Fix all links in generated files to other generated files to point to top level of generated docs dir. @param {Array} htmlFiles List of html files found in generated dir.
[ "Fix", "all", "links", "in", "generated", "files", "to", "other", "generated", "files", "to", "point", "to", "top", "level", "of", "generated", "docs", "dir", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L237-L244
train
firebase/firebase-js-sdk
scripts/docgen/generate-docs.js
generateNodeSource
async function generateNodeSource() { const sourceText = await fs.readFile(sourceFile, 'utf8'); // Parse index.d.ts. A dummy filename is required but it doesn't create a // file. let typescriptSourceFile = typescript.createSourceFile( 'temp.d.ts', sourceText, typescript.ScriptTarget.ES2015, /*setParentNodes */ false ); /** * Typescript transformer function. Removes nodes tagged with @webonly. */ const removeWebOnlyNodes = context => rootNode => { function visit(node) { if ( node.jsDoc && node.jsDoc.some( item => item.tags && item.tags.some(tag => tag.tagName.escapedText === 'webonly') ) ) { return null; } return typescript.visitEachChild(node, visit, context); } return typescript.visitNode(rootNode, visit); }; // Use above transformer on source AST to remove nodes tagged with @webonly. const result = typescript.transform(typescriptSourceFile, [ removeWebOnlyNodes ]); // Convert transformed AST to text and write to file. const printer = typescript.createPrinter(); return fs.writeFile( tempNodeSourcePath, printer.printFile(result.transformed[0]) ); }
javascript
async function generateNodeSource() { const sourceText = await fs.readFile(sourceFile, 'utf8'); // Parse index.d.ts. A dummy filename is required but it doesn't create a // file. let typescriptSourceFile = typescript.createSourceFile( 'temp.d.ts', sourceText, typescript.ScriptTarget.ES2015, /*setParentNodes */ false ); /** * Typescript transformer function. Removes nodes tagged with @webonly. */ const removeWebOnlyNodes = context => rootNode => { function visit(node) { if ( node.jsDoc && node.jsDoc.some( item => item.tags && item.tags.some(tag => tag.tagName.escapedText === 'webonly') ) ) { return null; } return typescript.visitEachChild(node, visit, context); } return typescript.visitNode(rootNode, visit); }; // Use above transformer on source AST to remove nodes tagged with @webonly. const result = typescript.transform(typescriptSourceFile, [ removeWebOnlyNodes ]); // Convert transformed AST to text and write to file. const printer = typescript.createPrinter(); return fs.writeFile( tempNodeSourcePath, printer.printFile(result.transformed[0]) ); }
[ "async", "function", "generateNodeSource", "(", ")", "{", "const", "sourceText", "=", "await", "fs", ".", "readFile", "(", "sourceFile", ",", "'utf8'", ")", ";", "let", "typescriptSourceFile", "=", "typescript", ".", "createSourceFile", "(", "'temp.d.ts'", ",", "sourceText", ",", "typescript", ".", "ScriptTarget", ".", "ES2015", ",", "false", ")", ";", "const", "removeWebOnlyNodes", "=", "context", "=>", "rootNode", "=>", "{", "function", "visit", "(", "node", ")", "{", "if", "(", "node", ".", "jsDoc", "&&", "node", ".", "jsDoc", ".", "some", "(", "item", "=>", "item", ".", "tags", "&&", "item", ".", "tags", ".", "some", "(", "tag", "=>", "tag", ".", "tagName", ".", "escapedText", "===", "'webonly'", ")", ")", ")", "{", "return", "null", ";", "}", "return", "typescript", ".", "visitEachChild", "(", "node", ",", "visit", ",", "context", ")", ";", "}", "return", "typescript", ".", "visitNode", "(", "rootNode", ",", "visit", ")", ";", "}", ";", "const", "result", "=", "typescript", ".", "transform", "(", "typescriptSourceFile", ",", "[", "removeWebOnlyNodes", "]", ")", ";", "const", "printer", "=", "typescript", ".", "createPrinter", "(", ")", ";", "return", "fs", ".", "writeFile", "(", "tempNodeSourcePath", ",", "printer", ".", "printFile", "(", "result", ".", "transformed", "[", "0", "]", ")", ")", ";", "}" ]
Generate an temporary abridged version of index.d.ts used to create Node docs.
[ "Generate", "an", "temporary", "abridged", "version", "of", "index", ".", "d", ".", "ts", "used", "to", "create", "Node", "docs", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/scripts/docgen/generate-docs.js#L250-L293
train
firebase/firebase-js-sdk
packages/auth/src/cordovahandler.js
function() { // Remove current resume listener. if (onResume) { doc.removeEventListener('resume', onResume, false); } // Remove visibility change listener. if (onVisibilityChange) { doc.removeEventListener('visibilitychange', onVisibilityChange, false); } // Cancel onClose promise if not already cancelled. if (onClose) { onClose.cancel(); } // Remove Auth event callback. if (authEventCallback) { self.removeAuthEventListener(authEventCallback); } // Clear any pending redirect now that it is completed. self.pendingRedirect_ = null; }
javascript
function() { // Remove current resume listener. if (onResume) { doc.removeEventListener('resume', onResume, false); } // Remove visibility change listener. if (onVisibilityChange) { doc.removeEventListener('visibilitychange', onVisibilityChange, false); } // Cancel onClose promise if not already cancelled. if (onClose) { onClose.cancel(); } // Remove Auth event callback. if (authEventCallback) { self.removeAuthEventListener(authEventCallback); } // Clear any pending redirect now that it is completed. self.pendingRedirect_ = null; }
[ "function", "(", ")", "{", "if", "(", "onResume", ")", "{", "doc", ".", "removeEventListener", "(", "'resume'", ",", "onResume", ",", "false", ")", ";", "}", "if", "(", "onVisibilityChange", ")", "{", "doc", ".", "removeEventListener", "(", "'visibilitychange'", ",", "onVisibilityChange", ",", "false", ")", ";", "}", "if", "(", "onClose", ")", "{", "onClose", ".", "cancel", "(", ")", ";", "}", "if", "(", "authEventCallback", ")", "{", "self", ".", "removeAuthEventListener", "(", "authEventCallback", ")", ";", "}", "self", ".", "pendingRedirect_", "=", "null", ";", "}" ]
When the processRedirect promise completes, clean up any remaining temporary listeners and timers.
[ "When", "the", "processRedirect", "promise", "completes", "clean", "up", "any", "remaining", "temporary", "listeners", "and", "timers", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/cordovahandler.js#L359-L378
train
firebase/firebase-js-sdk
packages/auth/src/cordovahandler.js
function(eventData) { initialResolve = true; // Cancel no event timer. if (noEventTimer) { noEventTimer.cancel(); } // Incoming link detected. // Check for any stored partial event. self.getPartialStoredEvent_().then(function(event) { // Initialize to an unknown event. var authEvent = noEvent; // Confirm OAuth response included. if (event && eventData && eventData['url']) { // Construct complete event. Default to unknown event if none found. authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) || noEvent; } // Dispatch Auth event. self.dispatchEvent_(authEvent); }); }
javascript
function(eventData) { initialResolve = true; // Cancel no event timer. if (noEventTimer) { noEventTimer.cancel(); } // Incoming link detected. // Check for any stored partial event. self.getPartialStoredEvent_().then(function(event) { // Initialize to an unknown event. var authEvent = noEvent; // Confirm OAuth response included. if (event && eventData && eventData['url']) { // Construct complete event. Default to unknown event if none found. authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) || noEvent; } // Dispatch Auth event. self.dispatchEvent_(authEvent); }); }
[ "function", "(", "eventData", ")", "{", "initialResolve", "=", "true", ";", "if", "(", "noEventTimer", ")", "{", "noEventTimer", ".", "cancel", "(", ")", ";", "}", "self", ".", "getPartialStoredEvent_", "(", ")", ".", "then", "(", "function", "(", "event", ")", "{", "var", "authEvent", "=", "noEvent", ";", "if", "(", "event", "&&", "eventData", "&&", "eventData", "[", "'url'", "]", ")", "{", "authEvent", "=", "self", ".", "extractAuthEventFromUrl_", "(", "event", ",", "eventData", "[", "'url'", "]", ")", "||", "noEvent", ";", "}", "self", ".", "dispatchEvent_", "(", "authEvent", ")", ";", "}", ")", ";", "}" ]
No event name needed, subscribe to all incoming universal links.
[ "No", "event", "name", "needed", "subscribe", "to", "all", "incoming", "universal", "links", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/cordovahandler.js#L753-L773
train
firebase/firebase-js-sdk
packages/auth/src/authuser.js
function() { // Get time until expiration minus the refresh offset. var waitInterval = self.stsTokenManager_.getExpirationTime() - goog.now() - fireauth.TokenRefreshTime.OFFSET_DURATION; // Set to zero if wait interval is negative. return waitInterval > 0 ? waitInterval : 0; }
javascript
function() { // Get time until expiration minus the refresh offset. var waitInterval = self.stsTokenManager_.getExpirationTime() - goog.now() - fireauth.TokenRefreshTime.OFFSET_DURATION; // Set to zero if wait interval is negative. return waitInterval > 0 ? waitInterval : 0; }
[ "function", "(", ")", "{", "var", "waitInterval", "=", "self", ".", "stsTokenManager_", ".", "getExpirationTime", "(", ")", "-", "goog", ".", "now", "(", ")", "-", "fireauth", ".", "TokenRefreshTime", ".", "OFFSET_DURATION", ";", "return", "waitInterval", ">", "0", "?", "waitInterval", ":", "0", ";", "}" ]
Return next time to run with offset applied.
[ "Return", "next", "time", "to", "run", "with", "offset", "applied", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/authuser.js#L474-L481
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
logAtLevel_
function logAtLevel_(message, level) { if (message != null) { var messageDiv = $('<div></div>'); messageDiv.addClass(level); if (typeof message === 'object') { messageDiv.text(JSON.stringify(message, null, ' ')); } else { messageDiv.text(message); } $('.logs').append(messageDiv); } console[level](message); }
javascript
function logAtLevel_(message, level) { if (message != null) { var messageDiv = $('<div></div>'); messageDiv.addClass(level); if (typeof message === 'object') { messageDiv.text(JSON.stringify(message, null, ' ')); } else { messageDiv.text(message); } $('.logs').append(messageDiv); } console[level](message); }
[ "function", "logAtLevel_", "(", "message", ",", "level", ")", "{", "if", "(", "message", "!=", "null", ")", "{", "var", "messageDiv", "=", "$", "(", "'<div></div>'", ")", ";", "messageDiv", ".", "addClass", "(", "level", ")", ";", "if", "(", "typeof", "message", "===", "'object'", ")", "{", "messageDiv", ".", "text", "(", "JSON", ".", "stringify", "(", "message", ",", "null", ",", "' '", ")", ")", ";", "}", "else", "{", "messageDiv", ".", "text", "(", "message", ")", ";", "}", "$", "(", "'.logs'", ")", ".", "append", "(", "messageDiv", ")", ";", "}", "console", "[", "level", "]", "(", "message", ")", ";", "}" ]
Logs the message in the console and on the log window in the app using the level given. @param {?Object} message Object or message to log. @param {string} level The level of log (log, error, debug). @private
[ "Logs", "the", "message", "in", "the", "console", "and", "on", "the", "log", "window", "in", "the", "app", "using", "the", "level", "given", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L56-L68
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
alertMessage_
function alertMessage_(message, cssClass) { var alertBox = $('<div></div>') .addClass(cssClass) .css('display', 'none') .text(message); $('#alert-messages').prepend(alertBox); alertBox.fadeIn({ complete: function() { setTimeout(function() { alertBox.slideUp(); }, 3000); } }); }
javascript
function alertMessage_(message, cssClass) { var alertBox = $('<div></div>') .addClass(cssClass) .css('display', 'none') .text(message); $('#alert-messages').prepend(alertBox); alertBox.fadeIn({ complete: function() { setTimeout(function() { alertBox.slideUp(); }, 3000); } }); }
[ "function", "alertMessage_", "(", "message", ",", "cssClass", ")", "{", "var", "alertBox", "=", "$", "(", "'<div></div>'", ")", ".", "addClass", "(", "cssClass", ")", ".", "css", "(", "'display'", ",", "'none'", ")", ".", "text", "(", "message", ")", ";", "$", "(", "'#alert-messages'", ")", ".", "prepend", "(", "alertBox", ")", ";", "alertBox", ".", "fadeIn", "(", "{", "complete", ":", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "alertBox", ".", "slideUp", "(", ")", ";", "}", ",", "3000", ")", ";", "}", "}", ")", ";", "}" ]
Displays for a few seconds a box with a specific message and then fades it out. @param {string} message Small message to display. @param {string} cssClass The class(s) to give the alert box. @private
[ "Displays", "for", "a", "few", "seconds", "a", "box", "with", "a", "specific", "message", "and", "then", "fades", "it", "out", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L94-L107
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
refreshUserData
function refreshUserData() { if (activeUser()) { var user = activeUser(); $('.profile').show(); $('body').addClass('user-info-displayed'); $('div.profile-email,span.profile-email').text(user.email || 'No Email'); $('div.profile-phone,span.profile-phone') .text(user.phoneNumber || 'No Phone'); $('div.profile-uid,span.profile-uid').text(user.uid); $('div.profile-name,span.profile-name').text(user.displayName || 'No Name'); $('input.profile-name').val(user.displayName); $('input.photo-url').val(user.photoURL); if (user.photoURL != null) { var photoURL = user.photoURL; // Append size to the photo URL for Google hosted images to avoid requesting // the image with its original resolution (using more bandwidth than needed) // when it is going to be presented in smaller size. if ((photoURL.indexOf('googleusercontent.com') != -1) || (photoURL.indexOf('ggpht.com') != -1)) { photoURL = photoURL + '?sz=' + $('img.profile-image').height(); } $('img.profile-image').attr('src', photoURL).show(); } else { $('img.profile-image').hide(); } $('.profile-email-verified').toggle(user.emailVerified); $('.profile-email-not-verified').toggle(!user.emailVerified); $('.profile-anonymous').toggle(user.isAnonymous); // Display/Hide providers icons. $('.profile-providers').empty(); if (user['providerData'] && user['providerData'].length) { var providersCount = user['providerData'].length; for (var i = 0; i < providersCount; i++) { addProviderIcon(user['providerData'][i]['providerId']); } } // Change color. if (user == auth.currentUser) { $('#user-info').removeClass('last-user'); $('#user-info').addClass('current-user'); } else { $('#user-info').removeClass('current-user'); $('#user-info').addClass('last-user'); } } else { $('.profile').slideUp(); $('body').removeClass('user-info-displayed'); $('input.profile-data').val(''); } }
javascript
function refreshUserData() { if (activeUser()) { var user = activeUser(); $('.profile').show(); $('body').addClass('user-info-displayed'); $('div.profile-email,span.profile-email').text(user.email || 'No Email'); $('div.profile-phone,span.profile-phone') .text(user.phoneNumber || 'No Phone'); $('div.profile-uid,span.profile-uid').text(user.uid); $('div.profile-name,span.profile-name').text(user.displayName || 'No Name'); $('input.profile-name').val(user.displayName); $('input.photo-url').val(user.photoURL); if (user.photoURL != null) { var photoURL = user.photoURL; // Append size to the photo URL for Google hosted images to avoid requesting // the image with its original resolution (using more bandwidth than needed) // when it is going to be presented in smaller size. if ((photoURL.indexOf('googleusercontent.com') != -1) || (photoURL.indexOf('ggpht.com') != -1)) { photoURL = photoURL + '?sz=' + $('img.profile-image').height(); } $('img.profile-image').attr('src', photoURL).show(); } else { $('img.profile-image').hide(); } $('.profile-email-verified').toggle(user.emailVerified); $('.profile-email-not-verified').toggle(!user.emailVerified); $('.profile-anonymous').toggle(user.isAnonymous); // Display/Hide providers icons. $('.profile-providers').empty(); if (user['providerData'] && user['providerData'].length) { var providersCount = user['providerData'].length; for (var i = 0; i < providersCount; i++) { addProviderIcon(user['providerData'][i]['providerId']); } } // Change color. if (user == auth.currentUser) { $('#user-info').removeClass('last-user'); $('#user-info').addClass('current-user'); } else { $('#user-info').removeClass('current-user'); $('#user-info').addClass('last-user'); } } else { $('.profile').slideUp(); $('body').removeClass('user-info-displayed'); $('input.profile-data').val(''); } }
[ "function", "refreshUserData", "(", ")", "{", "if", "(", "activeUser", "(", ")", ")", "{", "var", "user", "=", "activeUser", "(", ")", ";", "$", "(", "'.profile'", ")", ".", "show", "(", ")", ";", "$", "(", "'body'", ")", ".", "addClass", "(", "'user-info-displayed'", ")", ";", "$", "(", "'div.profile-email,span.profile-email'", ")", ".", "text", "(", "user", ".", "email", "||", "'No Email'", ")", ";", "$", "(", "'div.profile-phone,span.profile-phone'", ")", ".", "text", "(", "user", ".", "phoneNumber", "||", "'No Phone'", ")", ";", "$", "(", "'div.profile-uid,span.profile-uid'", ")", ".", "text", "(", "user", ".", "uid", ")", ";", "$", "(", "'div.profile-name,span.profile-name'", ")", ".", "text", "(", "user", ".", "displayName", "||", "'No Name'", ")", ";", "$", "(", "'input.profile-name'", ")", ".", "val", "(", "user", ".", "displayName", ")", ";", "$", "(", "'input.photo-url'", ")", ".", "val", "(", "user", ".", "photoURL", ")", ";", "if", "(", "user", ".", "photoURL", "!=", "null", ")", "{", "var", "photoURL", "=", "user", ".", "photoURL", ";", "if", "(", "(", "photoURL", ".", "indexOf", "(", "'googleusercontent.com'", ")", "!=", "-", "1", ")", "||", "(", "photoURL", ".", "indexOf", "(", "'ggpht.com'", ")", "!=", "-", "1", ")", ")", "{", "photoURL", "=", "photoURL", "+", "'?sz='", "+", "$", "(", "'img.profile-image'", ")", ".", "height", "(", ")", ";", "}", "$", "(", "'img.profile-image'", ")", ".", "attr", "(", "'src'", ",", "photoURL", ")", ".", "show", "(", ")", ";", "}", "else", "{", "$", "(", "'img.profile-image'", ")", ".", "hide", "(", ")", ";", "}", "$", "(", "'.profile-email-verified'", ")", ".", "toggle", "(", "user", ".", "emailVerified", ")", ";", "$", "(", "'.profile-email-not-verified'", ")", ".", "toggle", "(", "!", "user", ".", "emailVerified", ")", ";", "$", "(", "'.profile-anonymous'", ")", ".", "toggle", "(", "user", ".", "isAnonymous", ")", ";", "$", "(", "'.profile-providers'", ")", ".", "empty", "(", ")", ";", "if", "(", "user", "[", "'providerData'", "]", "&&", "user", "[", "'providerData'", "]", ".", "length", ")", "{", "var", "providersCount", "=", "user", "[", "'providerData'", "]", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "providersCount", ";", "i", "++", ")", "{", "addProviderIcon", "(", "user", "[", "'providerData'", "]", "[", "i", "]", "[", "'providerId'", "]", ")", ";", "}", "}", "if", "(", "user", "==", "auth", ".", "currentUser", ")", "{", "$", "(", "'#user-info'", ")", ".", "removeClass", "(", "'last-user'", ")", ";", "$", "(", "'#user-info'", ")", ".", "addClass", "(", "'current-user'", ")", ";", "}", "else", "{", "$", "(", "'#user-info'", ")", ".", "removeClass", "(", "'current-user'", ")", ";", "$", "(", "'#user-info'", ")", ".", "addClass", "(", "'last-user'", ")", ";", "}", "}", "else", "{", "$", "(", "'.profile'", ")", ".", "slideUp", "(", ")", ";", "$", "(", "'body'", ")", ".", "removeClass", "(", "'user-info-displayed'", ")", ";", "$", "(", "'input.profile-data'", ")", ".", "val", "(", "''", ")", ";", "}", "}" ]
Refreshes the current user data in the UI, displaying a user info box if a user is signed in, or removing it.
[ "Refreshes", "the", "current", "user", "data", "in", "the", "UI", "displaying", "a", "user", "info", "box", "if", "a", "user", "is", "signed", "in", "or", "removing", "it", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L146-L195
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
addProviderIcon
function addProviderIcon(providerId) { var pElt = $('<i>').addClass('fa ' + providersIcons[providerId]) .attr('title', providerId) .data({ 'toggle': 'tooltip', 'placement': 'bottom' }); $('.profile-providers').append(pElt); pElt.tooltip(); }
javascript
function addProviderIcon(providerId) { var pElt = $('<i>').addClass('fa ' + providersIcons[providerId]) .attr('title', providerId) .data({ 'toggle': 'tooltip', 'placement': 'bottom' }); $('.profile-providers').append(pElt); pElt.tooltip(); }
[ "function", "addProviderIcon", "(", "providerId", ")", "{", "var", "pElt", "=", "$", "(", "'<i>'", ")", ".", "addClass", "(", "'fa '", "+", "providersIcons", "[", "providerId", "]", ")", ".", "attr", "(", "'title'", ",", "providerId", ")", ".", "data", "(", "{", "'toggle'", ":", "'tooltip'", ",", "'placement'", ":", "'bottom'", "}", ")", ";", "$", "(", "'.profile-providers'", ")", ".", "append", "(", "pElt", ")", ";", "pElt", ".", "tooltip", "(", ")", ";", "}" ]
Add a provider icon to the profile info. @param {string} providerId The providerId of the provider.
[ "Add", "a", "provider", "icon", "to", "the", "profile", "info", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L219-L228
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSetLanguageCode
function onSetLanguageCode() { var languageCode = $('#language-code').val() || null; try { auth.languageCode = languageCode; alertSuccess('Language code changed to "' + languageCode + '".'); } catch (error) { alertError('Error: ' + error.code); } }
javascript
function onSetLanguageCode() { var languageCode = $('#language-code').val() || null; try { auth.languageCode = languageCode; alertSuccess('Language code changed to "' + languageCode + '".'); } catch (error) { alertError('Error: ' + error.code); } }
[ "function", "onSetLanguageCode", "(", ")", "{", "var", "languageCode", "=", "$", "(", "'#language-code'", ")", ".", "val", "(", ")", "||", "null", ";", "try", "{", "auth", ".", "languageCode", "=", "languageCode", ";", "alertSuccess", "(", "'Language code changed to \"'", "+", "languageCode", "+", "'\".'", ")", ";", "}", "catch", "(", "error", ")", "{", "alertError", "(", "'Error: '", "+", "error", ".", "code", ")", ";", "}", "}" ]
Saves the new language code provided in the language code input field.
[ "Saves", "the", "new", "language", "code", "provided", "in", "the", "language", "code", "input", "field", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L265-L273
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSetPersistence
function onSetPersistence() { var type = $('#persistence-type').val(); try { auth.setPersistence(type).then(function() { log('Persistence state change to "' + type + '".'); alertSuccess('Persistence state change to "' + type + '".'); }, function(error) { alertError('Error: ' + error.code); }); } catch (error) { alertError('Error: ' + error.code); } }
javascript
function onSetPersistence() { var type = $('#persistence-type').val(); try { auth.setPersistence(type).then(function() { log('Persistence state change to "' + type + '".'); alertSuccess('Persistence state change to "' + type + '".'); }, function(error) { alertError('Error: ' + error.code); }); } catch (error) { alertError('Error: ' + error.code); } }
[ "function", "onSetPersistence", "(", ")", "{", "var", "type", "=", "$", "(", "'#persistence-type'", ")", ".", "val", "(", ")", ";", "try", "{", "auth", ".", "setPersistence", "(", "type", ")", ".", "then", "(", "function", "(", ")", "{", "log", "(", "'Persistence state change to \"'", "+", "type", "+", "'\".'", ")", ";", "alertSuccess", "(", "'Persistence state change to \"'", "+", "type", "+", "'\".'", ")", ";", "}", ",", "function", "(", "error", ")", "{", "alertError", "(", "'Error: '", "+", "error", ".", "code", ")", ";", "}", ")", ";", "}", "catch", "(", "error", ")", "{", "alertError", "(", "'Error: '", "+", "error", ".", "code", ")", ";", "}", "}" ]
Changes the Auth state persistence to the specified one.
[ "Changes", "the", "Auth", "state", "persistence", "to", "the", "specified", "one", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L289-L301
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSignUp
function onSignUp() { var email = $('#signup-email').val(); var password = $('#signup-password').val(); auth.createUserWithEmailAndPassword(email, password) .then(onAuthUserCredentialSuccess, onAuthError); }
javascript
function onSignUp() { var email = $('#signup-email').val(); var password = $('#signup-password').val(); auth.createUserWithEmailAndPassword(email, password) .then(onAuthUserCredentialSuccess, onAuthError); }
[ "function", "onSignUp", "(", ")", "{", "var", "email", "=", "$", "(", "'#signup-email'", ")", ".", "val", "(", ")", ";", "var", "password", "=", "$", "(", "'#signup-password'", ")", ".", "val", "(", ")", ";", "auth", ".", "createUserWithEmailAndPassword", "(", "email", ",", "password", ")", ".", "then", "(", "onAuthUserCredentialSuccess", ",", "onAuthError", ")", ";", "}" ]
Signs up a new user with an email and a password.
[ "Signs", "up", "a", "new", "user", "with", "an", "email", "and", "a", "password", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L307-L312
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSignInWithEmailAndPassword
function onSignInWithEmailAndPassword() { var email = $('#signin-email').val(); var password = $('#signin-password').val(); auth.signInWithEmailAndPassword(email, password) .then(onAuthUserCredentialSuccess, onAuthError); }
javascript
function onSignInWithEmailAndPassword() { var email = $('#signin-email').val(); var password = $('#signin-password').val(); auth.signInWithEmailAndPassword(email, password) .then(onAuthUserCredentialSuccess, onAuthError); }
[ "function", "onSignInWithEmailAndPassword", "(", ")", "{", "var", "email", "=", "$", "(", "'#signin-email'", ")", ".", "val", "(", ")", ";", "var", "password", "=", "$", "(", "'#signin-password'", ")", ".", "val", "(", ")", ";", "auth", ".", "signInWithEmailAndPassword", "(", "email", ",", "password", ")", ".", "then", "(", "onAuthUserCredentialSuccess", ",", "onAuthError", ")", ";", "}" ]
Signs in a user with an email and a password.
[ "Signs", "in", "a", "user", "with", "an", "email", "and", "a", "password", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L318-L323
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSignInWithEmailLink
function onSignInWithEmailLink() { var email = $('#sign-in-with-email-link-email').val(); var link = $('#sign-in-with-email-link-link').val() || undefined; if (auth.isSignInWithEmailLink(link)) { auth.signInWithEmailLink(email, link).then(onAuthSuccess, onAuthError); } else { alertError('Sign in link is invalid'); } }
javascript
function onSignInWithEmailLink() { var email = $('#sign-in-with-email-link-email').val(); var link = $('#sign-in-with-email-link-link').val() || undefined; if (auth.isSignInWithEmailLink(link)) { auth.signInWithEmailLink(email, link).then(onAuthSuccess, onAuthError); } else { alertError('Sign in link is invalid'); } }
[ "function", "onSignInWithEmailLink", "(", ")", "{", "var", "email", "=", "$", "(", "'#sign-in-with-email-link-email'", ")", ".", "val", "(", ")", ";", "var", "link", "=", "$", "(", "'#sign-in-with-email-link-link'", ")", ".", "val", "(", ")", "||", "undefined", ";", "if", "(", "auth", ".", "isSignInWithEmailLink", "(", "link", ")", ")", "{", "auth", ".", "signInWithEmailLink", "(", "email", ",", "link", ")", ".", "then", "(", "onAuthSuccess", ",", "onAuthError", ")", ";", "}", "else", "{", "alertError", "(", "'Sign in link is invalid'", ")", ";", "}", "}" ]
Signs in a user with an email link.
[ "Signs", "in", "a", "user", "with", "an", "email", "link", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L329-L337
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onLinkWithEmailLink
function onLinkWithEmailLink() { var email = $('#link-with-email-link-email').val(); var link = $('#link-with-email-link-link').val() || undefined; var credential = firebase.auth.EmailAuthProvider .credentialWithLink(email, link); activeUser().linkWithCredential(credential) .then(onAuthUserCredentialSuccess, onAuthError); }
javascript
function onLinkWithEmailLink() { var email = $('#link-with-email-link-email').val(); var link = $('#link-with-email-link-link').val() || undefined; var credential = firebase.auth.EmailAuthProvider .credentialWithLink(email, link); activeUser().linkWithCredential(credential) .then(onAuthUserCredentialSuccess, onAuthError); }
[ "function", "onLinkWithEmailLink", "(", ")", "{", "var", "email", "=", "$", "(", "'#link-with-email-link-email'", ")", ".", "val", "(", ")", ";", "var", "link", "=", "$", "(", "'#link-with-email-link-link'", ")", ".", "val", "(", ")", "||", "undefined", ";", "var", "credential", "=", "firebase", ".", "auth", ".", "EmailAuthProvider", ".", "credentialWithLink", "(", "email", ",", "link", ")", ";", "activeUser", "(", ")", ".", "linkWithCredential", "(", "credential", ")", ".", "then", "(", "onAuthUserCredentialSuccess", ",", "onAuthError", ")", ";", "}" ]
Links a user with an email link.
[ "Links", "a", "user", "with", "an", "email", "link", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L342-L349
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onReauthenticateWithEmailLink
function onReauthenticateWithEmailLink() { var email = $('#link-with-email-link-email').val(); var link = $('#link-with-email-link-link').val() || undefined; var credential = firebase.auth.EmailAuthProvider .credentialWithLink(email, link); activeUser().reauthenticateWithCredential(credential) .then(function(result) { logAdditionalUserInfo(result); refreshUserData(); alertSuccess('User reauthenticated!'); }, onAuthError); }
javascript
function onReauthenticateWithEmailLink() { var email = $('#link-with-email-link-email').val(); var link = $('#link-with-email-link-link').val() || undefined; var credential = firebase.auth.EmailAuthProvider .credentialWithLink(email, link); activeUser().reauthenticateWithCredential(credential) .then(function(result) { logAdditionalUserInfo(result); refreshUserData(); alertSuccess('User reauthenticated!'); }, onAuthError); }
[ "function", "onReauthenticateWithEmailLink", "(", ")", "{", "var", "email", "=", "$", "(", "'#link-with-email-link-email'", ")", ".", "val", "(", ")", ";", "var", "link", "=", "$", "(", "'#link-with-email-link-link'", ")", ".", "val", "(", ")", "||", "undefined", ";", "var", "credential", "=", "firebase", ".", "auth", ".", "EmailAuthProvider", ".", "credentialWithLink", "(", "email", ",", "link", ")", ";", "activeUser", "(", ")", ".", "reauthenticateWithCredential", "(", "credential", ")", ".", "then", "(", "function", "(", "result", ")", "{", "logAdditionalUserInfo", "(", "result", ")", ";", "refreshUserData", "(", ")", ";", "alertSuccess", "(", "'User reauthenticated!'", ")", ";", "}", ",", "onAuthError", ")", ";", "}" ]
Re-authenticate a user with email link credential.
[ "Re", "-", "authenticate", "a", "user", "with", "email", "link", "credential", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L355-L366
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSignInWithCustomToken
function onSignInWithCustomToken(event) { // The token can be directly specified on the html element. var token = $('#user-custom-token').val(); auth.signInWithCustomToken(token) .then(onAuthUserCredentialSuccess, onAuthError); }
javascript
function onSignInWithCustomToken(event) { // The token can be directly specified on the html element. var token = $('#user-custom-token').val(); auth.signInWithCustomToken(token) .then(onAuthUserCredentialSuccess, onAuthError); }
[ "function", "onSignInWithCustomToken", "(", "event", ")", "{", "var", "token", "=", "$", "(", "'#user-custom-token'", ")", ".", "val", "(", ")", ";", "auth", ".", "signInWithCustomToken", "(", "token", ")", ".", "then", "(", "onAuthUserCredentialSuccess", ",", "onAuthError", ")", ";", "}" ]
Signs in with a custom token. @param {DOMEvent} event HTML DOM event returned by the listener.
[ "Signs", "in", "with", "a", "custom", "token", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L373-L379
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
onSignInWithGenericIdPCredential
function onSignInWithGenericIdPCredential() { var providerId = $('#signin-generic-idp-provider-id').val(); var idToken = $('#signin-generic-idp-id-token').val(); var accessToken = $('#signin-generic-idp-access-token').val(); var provider = new firebase.auth.OAuthProvider(providerId); auth.signInWithCredential( provider.credential(idToken, accessToken)) .then(onAuthUserCredentialSuccess, onAuthError); }
javascript
function onSignInWithGenericIdPCredential() { var providerId = $('#signin-generic-idp-provider-id').val(); var idToken = $('#signin-generic-idp-id-token').val(); var accessToken = $('#signin-generic-idp-access-token').val(); var provider = new firebase.auth.OAuthProvider(providerId); auth.signInWithCredential( provider.credential(idToken, accessToken)) .then(onAuthUserCredentialSuccess, onAuthError); }
[ "function", "onSignInWithGenericIdPCredential", "(", ")", "{", "var", "providerId", "=", "$", "(", "'#signin-generic-idp-provider-id'", ")", ".", "val", "(", ")", ";", "var", "idToken", "=", "$", "(", "'#signin-generic-idp-id-token'", ")", ".", "val", "(", ")", ";", "var", "accessToken", "=", "$", "(", "'#signin-generic-idp-access-token'", ")", ".", "val", "(", ")", ";", "var", "provider", "=", "new", "firebase", ".", "auth", ".", "OAuthProvider", "(", "providerId", ")", ";", "auth", ".", "signInWithCredential", "(", "provider", ".", "credential", "(", "idToken", ",", "accessToken", ")", ")", ".", "then", "(", "onAuthUserCredentialSuccess", ",", "onAuthError", ")", ";", "}" ]
Signs in with a generic IdP credential.
[ "Signs", "in", "with", "a", "generic", "IdP", "credential", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L394-L402
train
firebase/firebase-js-sdk
packages/auth/demo/public/script.js
makeApplicationVerifier
function makeApplicationVerifier(submitButtonId) { var container = recaptchaSize === 'invisible' ? submitButtonId : 'recaptcha-container'; applicationVerifier = new firebase.auth.RecaptchaVerifier(container, {'size': recaptchaSize}); }
javascript
function makeApplicationVerifier(submitButtonId) { var container = recaptchaSize === 'invisible' ? submitButtonId : 'recaptcha-container'; applicationVerifier = new firebase.auth.RecaptchaVerifier(container, {'size': recaptchaSize}); }
[ "function", "makeApplicationVerifier", "(", "submitButtonId", ")", "{", "var", "container", "=", "recaptchaSize", "===", "'invisible'", "?", "submitButtonId", ":", "'recaptcha-container'", ";", "applicationVerifier", "=", "new", "firebase", ".", "auth", ".", "RecaptchaVerifier", "(", "container", ",", "{", "'size'", ":", "recaptchaSize", "}", ")", ";", "}" ]
Initializes the ApplicationVerifier. @param {string} submitButtonId The ID of the DOM element of the button to which we attach the invisible reCAPTCHA. This is required even in visible mode.
[ "Initializes", "the", "ApplicationVerifier", "." ]
491598a499813dacc23724de5e237ec220cc560e
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L411-L417
train