id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
700
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderHeadTag
function renderHeadTag (tag) { const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag) return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}` }
javascript
function renderHeadTag (tag) { const { tagName, attributes, innerHTML, closeTag } = normalizeHeadTag(tag) return `<${tagName}${renderAttrs(attributes)}>${innerHTML}${closeTag ? `</${tagName}>` : ``}` }
[ "function", "renderHeadTag", "(", "tag", ")", "{", "const", "{", "tagName", ",", "attributes", ",", "innerHTML", ",", "closeTag", "}", "=", "normalizeHeadTag", "(", "tag", ")", "return", "`", "${", "tagName", "}", "${", "renderAttrs", "(", "attributes", ")", "}", "${", "innerHTML", "}", "${", "closeTag", "?", "`", "${", "tagName", "}", "`", ":", "`", "`", "}", "`", "}" ]
Render head tag @param {Object} tag @returns {string}
[ "Render", "head", "tag" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L206-L209
701
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderAttrs
function renderAttrs (attrs = {}) { const keys = Object.keys(attrs) if (keys.length) { return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ') } else { return '' } }
javascript
function renderAttrs (attrs = {}) { const keys = Object.keys(attrs) if (keys.length) { return ' ' + keys.map(name => `${name}="${escape(attrs[name])}"`).join(' ') } else { return '' } }
[ "function", "renderAttrs", "(", "attrs", "=", "{", "}", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "attrs", ")", "if", "(", "keys", ".", "length", ")", "{", "return", "' '", "+", "keys", ".", "map", "(", "name", "=>", "`", "${", "name", "}", "${", "escape", "(", "attrs", "[", "name", "]", ")", "}", "`", ")", ".", "join", "(", "' '", ")", "}", "else", "{", "return", "''", "}", "}" ]
Render html attributes @param {Object} attrs @returns {string}
[ "Render", "html", "attributes" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L218-L225
702
vuejs/vuepress
packages/@vuepress/core/lib/node/build/index.js
renderPageMeta
function renderPageMeta (meta) { if (!meta) return '' return meta.map(m => { let res = `<meta` Object.keys(m).forEach(key => { res += ` ${key}="${escape(m[key])}"` }) return res + `>` }).join('') }
javascript
function renderPageMeta (meta) { if (!meta) return '' return meta.map(m => { let res = `<meta` Object.keys(m).forEach(key => { res += ` ${key}="${escape(m[key])}"` }) return res + `>` }).join('') }
[ "function", "renderPageMeta", "(", "meta", ")", "{", "if", "(", "!", "meta", ")", "return", "''", "return", "meta", ".", "map", "(", "m", "=>", "{", "let", "res", "=", "`", "`", "Object", ".", "keys", "(", "m", ")", ".", "forEach", "(", "key", "=>", "{", "res", "+=", "`", "${", "key", "}", "${", "escape", "(", "m", "[", "key", "]", ")", "}", "`", "}", ")", "return", "res", "+", "`", "`", "}", ")", ".", "join", "(", "''", ")", "}" ]
Render meta tags @param {Array} meta @returns {Array<string>}
[ "Render", "meta", "tags" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/build/index.js#L234-L243
703
vuejs/vuepress
packages/vuepress/lib/util.js
CLI
async function CLI ({ beforeParse, afterParse }) { const cli = CAC() beforeParse && await beforeParse(cli) cli.parse(process.argv) afterParse && await afterParse(cli) }
javascript
async function CLI ({ beforeParse, afterParse }) { const cli = CAC() beforeParse && await beforeParse(cli) cli.parse(process.argv) afterParse && await afterParse(cli) }
[ "async", "function", "CLI", "(", "{", "beforeParse", ",", "afterParse", "}", ")", "{", "const", "cli", "=", "CAC", "(", ")", "beforeParse", "&&", "await", "beforeParse", "(", "cli", ")", "cli", ".", "parse", "(", "process", ".", "argv", ")", "afterParse", "&&", "await", "afterParse", "(", "cli", ")", "}" ]
Bootstrap a CAC cli @param {function} beforeParse @param {function} adterParse @returns {Promise<void>}
[ "Bootstrap", "a", "CAC", "cli" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/util.js#L17-L25
704
vuejs/vuepress
packages/vuepress/lib/util.js
wrapCommand
function wrapCommand (fn) { return (...args) => { return fn(...args).catch(err => { console.error(chalk.red(err.stack)) process.exitCode = 1 }) } }
javascript
function wrapCommand (fn) { return (...args) => { return fn(...args).catch(err => { console.error(chalk.red(err.stack)) process.exitCode = 1 }) } }
[ "function", "wrapCommand", "(", "fn", ")", "{", "return", "(", "...", "args", ")", "=>", "{", "return", "fn", "(", "...", "args", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "chalk", ".", "red", "(", "err", ".", "stack", ")", ")", "process", ".", "exitCode", "=", "1", "}", ")", "}", "}" ]
Wrap a function to catch error. @param {function} fn @returns {function(...[*]): (*|Promise|Promise<T | never>)}
[ "Wrap", "a", "function", "to", "catch", "error", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/util.js#L33-L40
705
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
resolveHost
function resolveHost (host) { const defaultHost = '0.0.0.0' host = host || defaultHost const displayHost = host === defaultHost ? 'localhost' : host return { displayHost, host } }
javascript
function resolveHost (host) { const defaultHost = '0.0.0.0' host = host || defaultHost const displayHost = host === defaultHost ? 'localhost' : host return { displayHost, host } }
[ "function", "resolveHost", "(", "host", ")", "{", "const", "defaultHost", "=", "'0.0.0.0'", "host", "=", "host", "||", "defaultHost", "const", "displayHost", "=", "host", "===", "defaultHost", "?", "'localhost'", ":", "host", "return", "{", "displayHost", ",", "host", "}", "}" ]
Resolve host. @param {string} host user's host @returns {{displayHost: string, host: string}}
[ "Resolve", "host", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L268-L278
706
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
resolvePort
async function resolvePort (port) { const portfinder = require('portfinder') portfinder.basePort = parseInt(port) || 8080 port = await portfinder.getPortPromise() return port }
javascript
async function resolvePort (port) { const portfinder = require('portfinder') portfinder.basePort = parseInt(port) || 8080 port = await portfinder.getPortPromise() return port }
[ "async", "function", "resolvePort", "(", "port", ")", "{", "const", "portfinder", "=", "require", "(", "'portfinder'", ")", "portfinder", ".", "basePort", "=", "parseInt", "(", "port", ")", "||", "8080", "port", "=", "await", "portfinder", ".", "getPortPromise", "(", ")", "return", "port", "}" ]
Resolve port. @param {number} port user's port @returns {Promise<number>}
[ "Resolve", "port", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L287-L292
707
vuejs/vuepress
packages/@vuepress/core/lib/node/dev/index.js
normalizeWatchFilePath
function normalizeWatchFilePath (filepath, baseDir) { const { isAbsolute, relative } = require('path') if (isAbsolute(filepath)) { return relative(baseDir, filepath) } return filepath }
javascript
function normalizeWatchFilePath (filepath, baseDir) { const { isAbsolute, relative } = require('path') if (isAbsolute(filepath)) { return relative(baseDir, filepath) } return filepath }
[ "function", "normalizeWatchFilePath", "(", "filepath", ",", "baseDir", ")", "{", "const", "{", "isAbsolute", ",", "relative", "}", "=", "require", "(", "'path'", ")", "if", "(", "isAbsolute", "(", "filepath", ")", ")", "{", "return", "relative", "(", "baseDir", ",", "filepath", ")", "}", "return", "filepath", "}" ]
Normalize file path and always return relative path, @param {string} filepath user's path @param {string} baseDir source directory @returns {string}
[ "Normalize", "file", "path", "and", "always", "return", "relative", "path" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/dev/index.js#L302-L308
708
vuejs/vuepress
packages/@vuepress/core/lib/node/internal-plugins/routes.js
routesCode
function routesCode (pages) { function genRoute ({ path: pagePath, key: componentName, frontmatter: { layout }, regularPath, _meta }) { let code = ` { name: ${JSON.stringify(componentName)}, path: ${JSON.stringify(pagePath)}, component: GlobalLayout, beforeEnter: (to, from, next) => { ensureAsyncComponentsLoaded(${JSON.stringify(layout || 'Layout')}, ${JSON.stringify(componentName)}).then(next) },${_meta ? `\n meta: ${JSON.stringify(_meta)}` : ''} }` const dncodedPath = decodeURIComponent(pagePath) if (dncodedPath !== pagePath) { code += `, { path: ${JSON.stringify(dncodedPath)}, redirect: ${JSON.stringify(pagePath)} }` } if (/\/$/.test(pagePath)) { code += `, { path: ${JSON.stringify(pagePath + 'index.html')}, redirect: ${JSON.stringify(pagePath)} }` } if (regularPath !== pagePath) { code += `, { path: ${JSON.stringify(regularPath)}, redirect: ${JSON.stringify(pagePath)} }` } return code } const notFoundRoute = `, { path: '*', component: GlobalLayout }` return ( `export const routes = [${pages.map(genRoute).join(',')}${notFoundRoute}\n]` ) }
javascript
function routesCode (pages) { function genRoute ({ path: pagePath, key: componentName, frontmatter: { layout }, regularPath, _meta }) { let code = ` { name: ${JSON.stringify(componentName)}, path: ${JSON.stringify(pagePath)}, component: GlobalLayout, beforeEnter: (to, from, next) => { ensureAsyncComponentsLoaded(${JSON.stringify(layout || 'Layout')}, ${JSON.stringify(componentName)}).then(next) },${_meta ? `\n meta: ${JSON.stringify(_meta)}` : ''} }` const dncodedPath = decodeURIComponent(pagePath) if (dncodedPath !== pagePath) { code += `, { path: ${JSON.stringify(dncodedPath)}, redirect: ${JSON.stringify(pagePath)} }` } if (/\/$/.test(pagePath)) { code += `, { path: ${JSON.stringify(pagePath + 'index.html')}, redirect: ${JSON.stringify(pagePath)} }` } if (regularPath !== pagePath) { code += `, { path: ${JSON.stringify(regularPath)}, redirect: ${JSON.stringify(pagePath)} }` } return code } const notFoundRoute = `, { path: '*', component: GlobalLayout }` return ( `export const routes = [${pages.map(genRoute).join(',')}${notFoundRoute}\n]` ) }
[ "function", "routesCode", "(", "pages", ")", "{", "function", "genRoute", "(", "{", "path", ":", "pagePath", ",", "key", ":", "componentName", ",", "frontmatter", ":", "{", "layout", "}", ",", "regularPath", ",", "_meta", "}", ")", "{", "let", "code", "=", "`", "${", "JSON", ".", "stringify", "(", "componentName", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "${", "JSON", ".", "stringify", "(", "layout", "||", "'Layout'", ")", "}", "${", "JSON", ".", "stringify", "(", "componentName", ")", "}", "${", "_meta", "?", "`", "\\n", "${", "JSON", ".", "stringify", "(", "_meta", ")", "}", "`", ":", "''", "}", "`", "const", "dncodedPath", "=", "decodeURIComponent", "(", "pagePath", ")", "if", "(", "dncodedPath", "!==", "pagePath", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "dncodedPath", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "if", "(", "/", "\\/$", "/", ".", "test", "(", "pagePath", ")", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "pagePath", "+", "'index.html'", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "if", "(", "regularPath", "!==", "pagePath", ")", "{", "code", "+=", "`", "${", "JSON", ".", "stringify", "(", "regularPath", ")", "}", "${", "JSON", ".", "stringify", "(", "pagePath", ")", "}", "`", "}", "return", "code", "}", "const", "notFoundRoute", "=", "`", "`", "return", "(", "`", "${", "pages", ".", "map", "(", "genRoute", ")", ".", "join", "(", "','", ")", "}", "${", "notFoundRoute", "}", "\\n", "`", ")", "}" ]
Get Vue routes code. @param {array} pages @returns {string}
[ "Get", "Vue", "routes", "code", "." ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/core/lib/node/internal-plugins/routes.js#L31-L88
709
vuejs/vuepress
packages/vuepress/lib/handleUnknownCommand.js
registerUnknownCommands
function registerUnknownCommands (cli, options) { cli.on('command:*', async () => { const { args, options: commandoptions } = cli logger.debug('global_options', options) logger.debug('cli_options', commandoptions) logger.debug('cli_args', args) const [commandName] = args const sourceDir = args[1] ? path.resolve(args[1]) : pwd const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd) logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory) logger.developer('sourceDir', sourceDir) if (inferredUserDocsDirectory && sourceDir !== inferredUserDocsDirectory) { logUnknownCommand(cli) console.log() logger.tip(`Did you miss to specify the target docs dir? e.g. ${chalk.cyan(`vuepress ${commandName} [targetDir]`)}.`) logger.tip(`A custom command registered by a plugin requires VuePress to locate your site configuration like ${chalk.cyan('vuepress dev')} or ${chalk.cyan('vuepress build')}.`) console.log() process.exit(1) } if (!inferredUserDocsDirectory) { logUnknownCommand(cli) process.exit(1) } logger.debug('Custom command', chalk.cyan(commandName)) CLI({ async beforeParse (subCli) { const app = createApp({ sourceDir: sourceDir, ...options, ...commandoptions }) await app.process() app.pluginAPI.applySyncOption('extendCli', subCli, app) console.log() }, async afterParse (subCli) { if (!subCli.matchedCommand) { logUnknownCommand(subCli) console.log() } } }) }) }
javascript
function registerUnknownCommands (cli, options) { cli.on('command:*', async () => { const { args, options: commandoptions } = cli logger.debug('global_options', options) logger.debug('cli_options', commandoptions) logger.debug('cli_args', args) const [commandName] = args const sourceDir = args[1] ? path.resolve(args[1]) : pwd const inferredUserDocsDirectory = await inferUserDocsDirectory(pwd) logger.developer('inferredUserDocsDirectory', inferredUserDocsDirectory) logger.developer('sourceDir', sourceDir) if (inferredUserDocsDirectory && sourceDir !== inferredUserDocsDirectory) { logUnknownCommand(cli) console.log() logger.tip(`Did you miss to specify the target docs dir? e.g. ${chalk.cyan(`vuepress ${commandName} [targetDir]`)}.`) logger.tip(`A custom command registered by a plugin requires VuePress to locate your site configuration like ${chalk.cyan('vuepress dev')} or ${chalk.cyan('vuepress build')}.`) console.log() process.exit(1) } if (!inferredUserDocsDirectory) { logUnknownCommand(cli) process.exit(1) } logger.debug('Custom command', chalk.cyan(commandName)) CLI({ async beforeParse (subCli) { const app = createApp({ sourceDir: sourceDir, ...options, ...commandoptions }) await app.process() app.pluginAPI.applySyncOption('extendCli', subCli, app) console.log() }, async afterParse (subCli) { if (!subCli.matchedCommand) { logUnknownCommand(subCli) console.log() } } }) }) }
[ "function", "registerUnknownCommands", "(", "cli", ",", "options", ")", "{", "cli", ".", "on", "(", "'command:*'", ",", "async", "(", ")", "=>", "{", "const", "{", "args", ",", "options", ":", "commandoptions", "}", "=", "cli", "logger", ".", "debug", "(", "'global_options'", ",", "options", ")", "logger", ".", "debug", "(", "'cli_options'", ",", "commandoptions", ")", "logger", ".", "debug", "(", "'cli_args'", ",", "args", ")", "const", "[", "commandName", "]", "=", "args", "const", "sourceDir", "=", "args", "[", "1", "]", "?", "path", ".", "resolve", "(", "args", "[", "1", "]", ")", ":", "pwd", "const", "inferredUserDocsDirectory", "=", "await", "inferUserDocsDirectory", "(", "pwd", ")", "logger", ".", "developer", "(", "'inferredUserDocsDirectory'", ",", "inferredUserDocsDirectory", ")", "logger", ".", "developer", "(", "'sourceDir'", ",", "sourceDir", ")", "if", "(", "inferredUserDocsDirectory", "&&", "sourceDir", "!==", "inferredUserDocsDirectory", ")", "{", "logUnknownCommand", "(", "cli", ")", "console", ".", "log", "(", ")", "logger", ".", "tip", "(", "`", "${", "chalk", ".", "cyan", "(", "`", "${", "commandName", "}", "`", ")", "}", "`", ")", "logger", ".", "tip", "(", "`", "${", "chalk", ".", "cyan", "(", "'vuepress dev'", ")", "}", "${", "chalk", ".", "cyan", "(", "'vuepress build'", ")", "}", "`", ")", "console", ".", "log", "(", ")", "process", ".", "exit", "(", "1", ")", "}", "if", "(", "!", "inferredUserDocsDirectory", ")", "{", "logUnknownCommand", "(", "cli", ")", "process", ".", "exit", "(", "1", ")", "}", "logger", ".", "debug", "(", "'Custom command'", ",", "chalk", ".", "cyan", "(", "commandName", ")", ")", "CLI", "(", "{", "async", "beforeParse", "(", "subCli", ")", "{", "const", "app", "=", "createApp", "(", "{", "sourceDir", ":", "sourceDir", ",", "...", "options", ",", "...", "commandoptions", "}", ")", "await", "app", ".", "process", "(", ")", "app", ".", "pluginAPI", ".", "applySyncOption", "(", "'extendCli'", ",", "subCli", ",", "app", ")", "console", ".", "log", "(", ")", "}", ",", "async", "afterParse", "(", "subCli", ")", "{", "if", "(", "!", "subCli", ".", "matchedCommand", ")", "{", "logUnknownCommand", "(", "subCli", ")", "console", ".", "log", "(", ")", "}", "}", "}", ")", "}", ")", "}" ]
Register a command to match all unmatched commands @param {CAC} cli
[ "Register", "a", "command", "to", "match", "all", "unmatched", "commands" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/vuepress/lib/handleUnknownCommand.js#L76-L124
710
vuejs/vuepress
packages/@vuepress/markdown/lib/tableOfContents.js
vBindEscape
function vBindEscape (strs, ...args) { return strs.reduce((prev, curr, index) => { return prev + curr + (index >= args.length ? '' : `"${JSON.stringify(args[index]) .replace(/"/g, "'") .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) }, '') }
javascript
function vBindEscape (strs, ...args) { return strs.reduce((prev, curr, index) => { return prev + curr + (index >= args.length ? '' : `"${JSON.stringify(args[index]) .replace(/"/g, "'") .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) }, '') }
[ "function", "vBindEscape", "(", "strs", ",", "...", "args", ")", "{", "return", "strs", ".", "reduce", "(", "(", "prev", ",", "curr", ",", "index", ")", "=>", "{", "return", "prev", "+", "curr", "+", "(", "index", ">=", "args", ".", "length", "?", "''", ":", "`", "${", "JSON", ".", "stringify", "(", "args", "[", "index", "]", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"'\"", ")", ".", "replace", "(", "/", "([^\\\\])(\\\\\\\\)*\\\\'", "/", "g", ",", "(", "_", ",", "char", ")", "=>", "char", "+", "'\\\\u0022'", ")", "}", "`", ")", "}", ",", "''", ")", "}" ]
escape double quotes in v-bind derivatives
[ "escape", "double", "quotes", "in", "v", "-", "bind", "derivatives" ]
15784acc0cf2e87de3c147895b2c3977b0195d78
https://github.com/vuejs/vuepress/blob/15784acc0cf2e87de3c147895b2c3977b0195d78/packages/@vuepress/markdown/lib/tableOfContents.js#L75-L83
711
juliangarnier/anime
src/index.js
setTargetsValue
function setTargetsValue(targets, properties) { const animatables = getAnimatables(targets); animatables.forEach(animatable => { for (let property in properties) { const value = getFunctionValue(properties[property], animatable); const target = animatable.target; const valueUnit = getUnit(value); const originalValue = getOriginalTargetValue(target, property, valueUnit, animatable); const unit = valueUnit || getUnit(originalValue); const to = getRelativeValue(validateValue(value, unit), originalValue); const animType = getAnimationType(target, property); setProgressValue[animType](target, property, to, animatable.transforms, true); } }); }
javascript
function setTargetsValue(targets, properties) { const animatables = getAnimatables(targets); animatables.forEach(animatable => { for (let property in properties) { const value = getFunctionValue(properties[property], animatable); const target = animatable.target; const valueUnit = getUnit(value); const originalValue = getOriginalTargetValue(target, property, valueUnit, animatable); const unit = valueUnit || getUnit(originalValue); const to = getRelativeValue(validateValue(value, unit), originalValue); const animType = getAnimationType(target, property); setProgressValue[animType](target, property, to, animatable.transforms, true); } }); }
[ "function", "setTargetsValue", "(", "targets", ",", "properties", ")", "{", "const", "animatables", "=", "getAnimatables", "(", "targets", ")", ";", "animatables", ".", "forEach", "(", "animatable", "=>", "{", "for", "(", "let", "property", "in", "properties", ")", "{", "const", "value", "=", "getFunctionValue", "(", "properties", "[", "property", "]", ",", "animatable", ")", ";", "const", "target", "=", "animatable", ".", "target", ";", "const", "valueUnit", "=", "getUnit", "(", "value", ")", ";", "const", "originalValue", "=", "getOriginalTargetValue", "(", "target", ",", "property", ",", "valueUnit", ",", "animatable", ")", ";", "const", "unit", "=", "valueUnit", "||", "getUnit", "(", "originalValue", ")", ";", "const", "to", "=", "getRelativeValue", "(", "validateValue", "(", "value", ",", "unit", ")", ",", "originalValue", ")", ";", "const", "animType", "=", "getAnimationType", "(", "target", ",", "property", ")", ";", "setProgressValue", "[", "animType", "]", "(", "target", ",", "property", ",", "to", ",", "animatable", ".", "transforms", ",", "true", ")", ";", "}", "}", ")", ";", "}" ]
Set Value helper
[ "Set", "Value", "helper" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/src/index.js#L777-L791
712
juliangarnier/anime
src/index.js
removeTargetsFromAnimations
function removeTargetsFromAnimations(targetsArray, animations) { for (let a = animations.length; a--;) { if (arrayContains(targetsArray, animations[a].animatable.target)) { animations.splice(a, 1); } } }
javascript
function removeTargetsFromAnimations(targetsArray, animations) { for (let a = animations.length; a--;) { if (arrayContains(targetsArray, animations[a].animatable.target)) { animations.splice(a, 1); } } }
[ "function", "removeTargetsFromAnimations", "(", "targetsArray", ",", "animations", ")", "{", "for", "(", "let", "a", "=", "animations", ".", "length", ";", "a", "--", ";", ")", "{", "if", "(", "arrayContains", "(", "targetsArray", ",", "animations", "[", "a", "]", ".", "animatable", ".", "target", ")", ")", "{", "animations", ".", "splice", "(", "a", ",", "1", ")", ";", "}", "}", "}" ]
Remove targets from animation
[ "Remove", "targets", "from", "animation" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/src/index.js#L1150-L1156
713
juliangarnier/anime
documentation/assets/js/website.js
onScroll
function onScroll(cb) { var isTicking = false; var scrollY = 0; var body = document.body; var html = document.documentElement; var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); function scroll() { scrollY = window.scrollY; if (cb) cb(scrollY, scrollHeight); requestTick(); } function requestTick() { if (!isTicking) requestAnimationFrame(updateScroll); isTicking = true; } function updateScroll() { isTicking = false; var currentScrollY = scrollY; } scroll(); window.onscroll = scroll; }
javascript
function onScroll(cb) { var isTicking = false; var scrollY = 0; var body = document.body; var html = document.documentElement; var scrollHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); function scroll() { scrollY = window.scrollY; if (cb) cb(scrollY, scrollHeight); requestTick(); } function requestTick() { if (!isTicking) requestAnimationFrame(updateScroll); isTicking = true; } function updateScroll() { isTicking = false; var currentScrollY = scrollY; } scroll(); window.onscroll = scroll; }
[ "function", "onScroll", "(", "cb", ")", "{", "var", "isTicking", "=", "false", ";", "var", "scrollY", "=", "0", ";", "var", "body", "=", "document", ".", "body", ";", "var", "html", "=", "document", ".", "documentElement", ";", "var", "scrollHeight", "=", "Math", ".", "max", "(", "body", ".", "scrollHeight", ",", "body", ".", "offsetHeight", ",", "html", ".", "clientHeight", ",", "html", ".", "scrollHeight", ",", "html", ".", "offsetHeight", ")", ";", "function", "scroll", "(", ")", "{", "scrollY", "=", "window", ".", "scrollY", ";", "if", "(", "cb", ")", "cb", "(", "scrollY", ",", "scrollHeight", ")", ";", "requestTick", "(", ")", ";", "}", "function", "requestTick", "(", ")", "{", "if", "(", "!", "isTicking", ")", "requestAnimationFrame", "(", "updateScroll", ")", ";", "isTicking", "=", "true", ";", "}", "function", "updateScroll", "(", ")", "{", "isTicking", "=", "false", ";", "var", "currentScrollY", "=", "scrollY", ";", "}", "scroll", "(", ")", ";", "window", ".", "onscroll", "=", "scroll", ";", "}" ]
Better scroll events
[ "Better", "scroll", "events" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L66-L87
714
juliangarnier/anime
documentation/assets/js/website.js
scrollToElement
function scrollToElement(el, offset) { var off = offset || 0; var rect = el.getBoundingClientRect(); var top = rect.top + off; var animation = anime({ targets: [document.body, document.documentElement], scrollTop: '+='+top, easing: 'easeInOutSine', duration: 1500 }); // onScroll(animation.pause); }
javascript
function scrollToElement(el, offset) { var off = offset || 0; var rect = el.getBoundingClientRect(); var top = rect.top + off; var animation = anime({ targets: [document.body, document.documentElement], scrollTop: '+='+top, easing: 'easeInOutSine', duration: 1500 }); // onScroll(animation.pause); }
[ "function", "scrollToElement", "(", "el", ",", "offset", ")", "{", "var", "off", "=", "offset", "||", "0", ";", "var", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ";", "var", "top", "=", "rect", ".", "top", "+", "off", ";", "var", "animation", "=", "anime", "(", "{", "targets", ":", "[", "document", ".", "body", ",", "document", ".", "documentElement", "]", ",", "scrollTop", ":", "'+='", "+", "top", ",", "easing", ":", "'easeInOutSine'", ",", "duration", ":", "1500", "}", ")", ";", "// onScroll(animation.pause);", "}" ]
Scroll to element
[ "Scroll", "to", "element" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L91-L102
715
juliangarnier/anime
documentation/assets/js/website.js
isElementInViewport
function isElementInViewport(el, inCB, outCB, rootMargin) { var margin = rootMargin || '-10%'; function handleIntersect(entries, observer) { var entry = entries[0]; if (entry.isIntersecting) { if (inCB && typeof inCB === 'function') inCB(el, entry); } else { if (outCB && typeof outCB === 'function') outCB(el, entry); } } var observer = new IntersectionObserver(handleIntersect, {rootMargin: margin}); observer.observe(el); }
javascript
function isElementInViewport(el, inCB, outCB, rootMargin) { var margin = rootMargin || '-10%'; function handleIntersect(entries, observer) { var entry = entries[0]; if (entry.isIntersecting) { if (inCB && typeof inCB === 'function') inCB(el, entry); } else { if (outCB && typeof outCB === 'function') outCB(el, entry); } } var observer = new IntersectionObserver(handleIntersect, {rootMargin: margin}); observer.observe(el); }
[ "function", "isElementInViewport", "(", "el", ",", "inCB", ",", "outCB", ",", "rootMargin", ")", "{", "var", "margin", "=", "rootMargin", "||", "'-10%'", ";", "function", "handleIntersect", "(", "entries", ",", "observer", ")", "{", "var", "entry", "=", "entries", "[", "0", "]", ";", "if", "(", "entry", ".", "isIntersecting", ")", "{", "if", "(", "inCB", "&&", "typeof", "inCB", "===", "'function'", ")", "inCB", "(", "el", ",", "entry", ")", ";", "}", "else", "{", "if", "(", "outCB", "&&", "typeof", "outCB", "===", "'function'", ")", "outCB", "(", "el", ",", "entry", ")", ";", "}", "}", "var", "observer", "=", "new", "IntersectionObserver", "(", "handleIntersect", ",", "{", "rootMargin", ":", "margin", "}", ")", ";", "observer", ".", "observe", "(", "el", ")", ";", "}" ]
Check if element is in viewport
[ "Check", "if", "element", "is", "in", "viewport" ]
875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a
https://github.com/juliangarnier/anime/blob/875a3d6745d4bff2e4c6ffe0e2d24aac3bf8a45a/documentation/assets/js/website.js#L106-L118
716
babel/babel
packages/babel-traverse/src/path/conversion.js
getThisBinding
function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([ child.node, t.assignmentExpression( "=", t.identifier(thisBinding), t.identifier("this"), ), ]); }, }); }); }
javascript
function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([ child.node, t.assignmentExpression( "=", t.identifier(thisBinding), t.identifier("this"), ), ]); }, }); }); }
[ "function", "getThisBinding", "(", "thisEnvFn", ",", "inConstructor", ")", "{", "return", "getBinding", "(", "thisEnvFn", ",", "\"this\"", ",", "thisBinding", "=>", "{", "if", "(", "!", "inConstructor", "||", "!", "hasSuperClass", "(", "thisEnvFn", ")", ")", "return", "t", ".", "thisExpression", "(", ")", ";", "const", "supers", "=", "new", "WeakSet", "(", ")", ";", "thisEnvFn", ".", "traverse", "(", "{", "Function", "(", "child", ")", "{", "if", "(", "child", ".", "isArrowFunctionExpression", "(", ")", ")", "return", ";", "child", ".", "skip", "(", ")", ";", "}", ",", "ClassProperty", "(", "child", ")", "{", "child", ".", "skip", "(", ")", ";", "}", ",", "CallExpression", "(", "child", ")", "{", "if", "(", "!", "child", ".", "get", "(", "\"callee\"", ")", ".", "isSuper", "(", ")", ")", "return", ";", "if", "(", "supers", ".", "has", "(", "child", ".", "node", ")", ")", "return", ";", "supers", ".", "add", "(", "child", ".", "node", ")", ";", "child", ".", "replaceWithMultiple", "(", "[", "child", ".", "node", ",", "t", ".", "assignmentExpression", "(", "\"=\"", ",", "t", ".", "identifier", "(", "thisBinding", ")", ",", "t", ".", "identifier", "(", "\"this\"", ")", ",", ")", ",", "]", ")", ";", "}", ",", "}", ")", ";", "}", ")", ";", "}" ]
Create a binding that evaluates to the "this" of the given function.
[ "Create", "a", "binding", "that", "evaluates", "to", "the", "this", "of", "the", "given", "function", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-traverse/src/path/conversion.js#L444-L473
717
babel/babel
packages/babel-generator/src/generators/statements.js
getLastStatement
function getLastStatement(statement) { if (!t.isStatement(statement.body)) return statement; return getLastStatement(statement.body); }
javascript
function getLastStatement(statement) { if (!t.isStatement(statement.body)) return statement; return getLastStatement(statement.body); }
[ "function", "getLastStatement", "(", "statement", ")", "{", "if", "(", "!", "t", ".", "isStatement", "(", "statement", ".", "body", ")", ")", "return", "statement", ";", "return", "getLastStatement", "(", "statement", ".", "body", ")", ";", "}" ]
Recursively get the last statement.
[ "Recursively", "get", "the", "last", "statement", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-generator/src/generators/statements.js#L45-L48
718
babel/babel
packages/babel-plugin-transform-block-scoping/src/index.js
isInLoop
function isInLoop(path) { const loopOrFunctionParent = path.find( path => path.isLoop() || path.isFunction(), ); return loopOrFunctionParent && loopOrFunctionParent.isLoop(); }
javascript
function isInLoop(path) { const loopOrFunctionParent = path.find( path => path.isLoop() || path.isFunction(), ); return loopOrFunctionParent && loopOrFunctionParent.isLoop(); }
[ "function", "isInLoop", "(", "path", ")", "{", "const", "loopOrFunctionParent", "=", "path", ".", "find", "(", "path", "=>", "path", ".", "isLoop", "(", ")", "||", "path", ".", "isFunction", "(", ")", ",", ")", ";", "return", "loopOrFunctionParent", "&&", "loopOrFunctionParent", ".", "isLoop", "(", ")", ";", "}" ]
If there is a loop ancestor closer than the closest function, we consider ourselves to be in a loop.
[ "If", "there", "is", "a", "loop", "ancestor", "closer", "than", "the", "closest", "function", "we", "consider", "ourselves", "to", "be", "in", "a", "loop", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-transform-block-scoping/src/index.js#L123-L129
719
babel/babel
packages/babel-plugin-proposal-object-rest-spread/src/index.js
replaceImpureComputedKeys
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const declarator = t.variableDeclarator(t.identifier(name), key.node); impureComputedPropertyDeclarators.push(declarator); key.replaceWith(t.identifier(name)); } } return impureComputedPropertyDeclarators; }
javascript
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const declarator = t.variableDeclarator(t.identifier(name), key.node); impureComputedPropertyDeclarators.push(declarator); key.replaceWith(t.identifier(name)); } } return impureComputedPropertyDeclarators; }
[ "function", "replaceImpureComputedKeys", "(", "path", ")", "{", "const", "impureComputedPropertyDeclarators", "=", "[", "]", ";", "for", "(", "const", "propPath", "of", "path", ".", "get", "(", "\"properties\"", ")", ")", "{", "const", "key", "=", "propPath", ".", "get", "(", "\"key\"", ")", ";", "if", "(", "propPath", ".", "node", ".", "computed", "&&", "!", "key", ".", "isPure", "(", ")", ")", "{", "const", "name", "=", "path", ".", "scope", ".", "generateUidBasedOnNode", "(", "key", ".", "node", ")", ";", "const", "declarator", "=", "t", ".", "variableDeclarator", "(", "t", ".", "identifier", "(", "name", ")", ",", "key", ".", "node", ")", ";", "impureComputedPropertyDeclarators", ".", "push", "(", "declarator", ")", ";", "key", ".", "replaceWith", "(", "t", ".", "identifier", "(", "name", ")", ")", ";", "}", "}", "return", "impureComputedPropertyDeclarators", ";", "}" ]
replaces impure computed keys with new identifiers and returns variable declarators of these new identifiers
[ "replaces", "impure", "computed", "keys", "with", "new", "identifiers", "and", "returns", "variable", "declarators", "of", "these", "new", "identifiers" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-object-rest-spread/src/index.js#L94-L106
720
babel/babel
packages/babel-plugin-proposal-object-rest-spread/src/index.js
createObjectSpread
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); const { keys, allLiteral } = extractNormalizedKeys(path); if (keys.length === 0) { return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression(getExtendsHelper(file), [ t.objectExpression([]), t.cloneNode(objRef), ]), ]; } let keyExpression; if (!allLiteral) { // map to toPropertyKey to handle the possible non-string values keyExpression = t.callExpression( t.memberExpression(t.arrayExpression(keys), t.identifier("map")), [file.addHelper("toPropertyKey")], ); } else { keyExpression = t.arrayExpression(keys); } return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression( file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [t.cloneNode(objRef), keyExpression], ), ]; }
javascript
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); const { keys, allLiteral } = extractNormalizedKeys(path); if (keys.length === 0) { return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression(getExtendsHelper(file), [ t.objectExpression([]), t.cloneNode(objRef), ]), ]; } let keyExpression; if (!allLiteral) { // map to toPropertyKey to handle the possible non-string values keyExpression = t.callExpression( t.memberExpression(t.arrayExpression(keys), t.identifier("map")), [file.addHelper("toPropertyKey")], ); } else { keyExpression = t.arrayExpression(keys); } return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression( file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [t.cloneNode(objRef), keyExpression], ), ]; }
[ "function", "createObjectSpread", "(", "path", ",", "file", ",", "objRef", ")", "{", "const", "props", "=", "path", ".", "get", "(", "\"properties\"", ")", ";", "const", "last", "=", "props", "[", "props", ".", "length", "-", "1", "]", ";", "t", ".", "assertRestElement", "(", "last", ".", "node", ")", ";", "const", "restElement", "=", "t", ".", "cloneNode", "(", "last", ".", "node", ")", ";", "last", ".", "remove", "(", ")", ";", "const", "impureComputedPropertyDeclarators", "=", "replaceImpureComputedKeys", "(", "path", ")", ";", "const", "{", "keys", ",", "allLiteral", "}", "=", "extractNormalizedKeys", "(", "path", ")", ";", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", "[", "impureComputedPropertyDeclarators", ",", "restElement", ".", "argument", ",", "t", ".", "callExpression", "(", "getExtendsHelper", "(", "file", ")", ",", "[", "t", ".", "objectExpression", "(", "[", "]", ")", ",", "t", ".", "cloneNode", "(", "objRef", ")", ",", "]", ")", ",", "]", ";", "}", "let", "keyExpression", ";", "if", "(", "!", "allLiteral", ")", "{", "// map to toPropertyKey to handle the possible non-string values", "keyExpression", "=", "t", ".", "callExpression", "(", "t", ".", "memberExpression", "(", "t", ".", "arrayExpression", "(", "keys", ")", ",", "t", ".", "identifier", "(", "\"map\"", ")", ")", ",", "[", "file", ".", "addHelper", "(", "\"toPropertyKey\"", ")", "]", ",", ")", ";", "}", "else", "{", "keyExpression", "=", "t", ".", "arrayExpression", "(", "keys", ")", ";", "}", "return", "[", "impureComputedPropertyDeclarators", ",", "restElement", ".", "argument", ",", "t", ".", "callExpression", "(", "file", ".", "addHelper", "(", "`", "${", "loose", "?", "\"Loose\"", ":", "\"\"", "}", "`", ")", ",", "[", "t", ".", "cloneNode", "(", "objRef", ")", ",", "keyExpression", "]", ",", ")", ",", "]", ";", "}" ]
expects path to an object pattern
[ "expects", "path", "to", "an", "object", "pattern" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-object-rest-spread/src/index.js#L124-L164
721
babel/babel
packages/babel-helper-module-transforms/src/index.js
buildInitStatement
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ), ); }
javascript
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ), ); }
[ "function", "buildInitStatement", "(", "metadata", ",", "exportNames", ",", "initExpr", ")", "{", "return", "t", ".", "expressionStatement", "(", "exportNames", ".", "reduce", "(", "(", "acc", ",", "exportName", ")", "=>", "template", ".", "expression", "`", "`", "(", "{", "EXPORTS", ":", "metadata", ".", "exportName", ",", "NAME", ":", "exportName", ",", "VALUE", ":", "acc", ",", "}", ")", ",", "initExpr", ",", ")", ",", ")", ";", "}" ]
Given a set of export names, create a set of nested assignments to initialize them all to a given expression.
[ "Given", "a", "set", "of", "export", "names", "create", "a", "set", "of", "nested", "assignments", "to", "initialize", "them", "all", "to", "a", "given", "expression", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-helper-module-transforms/src/index.js#L356-L368
722
babel/babel
packages/babel-code-frame/src/index.js
getDefs
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
javascript
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
[ "function", "getDefs", "(", "chalk", ")", "{", "return", "{", "gutter", ":", "chalk", ".", "grey", ",", "marker", ":", "chalk", ".", "red", ".", "bold", ",", "message", ":", "chalk", ".", "red", ".", "bold", ",", "}", ";", "}" ]
Chalk styles for code frame token types.
[ "Chalk", "styles", "for", "code", "frame", "token", "types", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-code-frame/src/index.js#L18-L24
723
babel/babel
packages/babel-standalone/src/transformScriptTags.js
load
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error("Could not load " + url); } } }; return xhr.send(null); }
javascript
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error("Could not load " + url); } } }; return xhr.send(null); }
[ "function", "load", "(", "url", ",", "successCallback", ",", "errorCallback", ")", "{", "const", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "// async, however scripts will be executed in the order they are in the", "// DOM to mirror normal script loading.", "xhr", ".", "open", "(", "\"GET\"", ",", "url", ",", "true", ")", ";", "if", "(", "\"overrideMimeType\"", "in", "xhr", ")", "{", "xhr", ".", "overrideMimeType", "(", "\"text/plain\"", ")", ";", "}", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "4", ")", "{", "if", "(", "xhr", ".", "status", "===", "0", "||", "xhr", ".", "status", "===", "200", ")", "{", "successCallback", "(", "xhr", ".", "responseText", ")", ";", "}", "else", "{", "errorCallback", "(", ")", ";", "throw", "new", "Error", "(", "\"Could not load \"", "+", "url", ")", ";", "}", "}", "}", ";", "return", "xhr", ".", "send", "(", "null", ")", ";", "}" ]
Load script from the provided url and pass the content to the callback.
[ "Load", "script", "from", "the", "provided", "url", "and", "pass", "the", "content", "to", "the", "callback", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-standalone/src/transformScriptTags.js#L64-L84
724
babel/babel
packages/babel-standalone/src/transformScriptTags.js
getPluginsOrPresetsFromScript
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding this // setting, and should use the default. return null; } return rawValue.split(",").map(item => item.trim()); }
javascript
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding this // setting, and should use the default. return null; } return rawValue.split(",").map(item => item.trim()); }
[ "function", "getPluginsOrPresetsFromScript", "(", "script", ",", "attributeName", ")", "{", "const", "rawValue", "=", "script", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "rawValue", "===", "\"\"", ")", "{", "// Empty string means to not load ANY presets or plugins", "return", "[", "]", ";", "}", "if", "(", "!", "rawValue", ")", "{", "// Any other falsy value (null, undefined) means we're not overriding this", "// setting, and should use the default.", "return", "null", ";", "}", "return", "rawValue", ".", "split", "(", "\",\"", ")", ".", "map", "(", "item", "=>", "item", ".", "trim", "(", ")", ")", ";", "}" ]
Converts a comma-separated data attribute string into an array of values. If the string is empty, returns an empty array. If the string is not defined, returns null.
[ "Converts", "a", "comma", "-", "separated", "data", "attribute", "string", "into", "an", "array", "of", "values", ".", "If", "the", "string", "is", "empty", "returns", "an", "empty", "array", ".", "If", "the", "string", "is", "not", "defined", "returns", "null", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-standalone/src/transformScriptTags.js#L91-L103
725
babel/babel
packages/babel-traverse/src/path/evaluation.js
deopt
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
javascript
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
[ "function", "deopt", "(", "path", ",", "state", ")", "{", "if", "(", "!", "state", ".", "confident", ")", "return", ";", "state", ".", "deoptPath", "=", "path", ";", "state", ".", "confident", "=", "false", ";", "}" ]
Deopts the evaluation
[ "Deopts", "the", "evaluation" ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-traverse/src/path/evaluation.js#L34-L38
726
babel/babel
packages/babel-helper-replace-supers/src/index.js
getPrototypeOfExpression
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); }
javascript
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); }
[ "function", "getPrototypeOfExpression", "(", "objectRef", ",", "isStatic", ",", "file", ",", "isPrivateMethod", ")", "{", "objectRef", "=", "t", ".", "cloneNode", "(", "objectRef", ")", ";", "const", "targetRef", "=", "isStatic", "||", "isPrivateMethod", "?", "objectRef", ":", "t", ".", "memberExpression", "(", "objectRef", ",", "t", ".", "identifier", "(", "\"prototype\"", ")", ")", ";", "return", "t", ".", "callExpression", "(", "file", ".", "addHelper", "(", "\"getPrototypeOf\"", ")", ",", "[", "targetRef", "]", ")", ";", "}" ]
Creates an expression which result is the proto of objectRef. @example <caption>isStatic === true</caption> helpers.getPrototypeOf(CLASS) @example <caption>isStatic === false</caption> helpers.getPrototypeOf(CLASS.prototype)
[ "Creates", "an", "expression", "which", "result", "is", "the", "proto", "of", "objectRef", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-helper-replace-supers/src/index.js#L18-L26
727
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyEnsureOrdering
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier( "dec", )); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); }
javascript
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier( "dec", )); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); }
[ "function", "applyEnsureOrdering", "(", "path", ")", "{", "// TODO: This should probably also hoist computed properties.", "const", "decorators", "=", "(", "path", ".", "isClass", "(", ")", "?", "[", "path", "]", ".", "concat", "(", "path", ".", "get", "(", "\"body.body\"", ")", ")", ":", "path", ".", "get", "(", "\"properties\"", ")", ")", ".", "reduce", "(", "(", "acc", ",", "prop", ")", "=>", "acc", ".", "concat", "(", "prop", ".", "node", ".", "decorators", "||", "[", "]", ")", ",", "[", "]", ")", ";", "const", "identDecorators", "=", "decorators", ".", "filter", "(", "decorator", "=>", "!", "t", ".", "isIdentifier", "(", "decorator", ".", "expression", ")", ",", ")", ";", "if", "(", "identDecorators", ".", "length", "===", "0", ")", "return", ";", "return", "t", ".", "sequenceExpression", "(", "identDecorators", ".", "map", "(", "decorator", "=>", "{", "const", "expression", "=", "decorator", ".", "expression", ";", "const", "id", "=", "(", "decorator", ".", "expression", "=", "path", ".", "scope", ".", "generateDeclaredUidIdentifier", "(", "\"dec\"", ",", ")", ")", ";", "return", "t", ".", "assignmentExpression", "(", "\"=\"", ",", "id", ",", "expression", ")", ";", "}", ")", ".", "concat", "(", "[", "path", ".", "node", "]", ")", ",", ")", ";", "}" ]
If the decorator expressions are non-identifiers, hoist them to before the class so we can be sure that they are evaluated in order.
[ "If", "the", "decorator", "expressions", "are", "non", "-", "identifiers", "hoist", "them", "to", "before", "the", "class", "so", "we", "can", "be", "sure", "that", "they", "are", "evaluated", "in", "order", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L34-L57
728
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyClassDecorators
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function(acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); }
javascript
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function(acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); }
[ "function", "applyClassDecorators", "(", "classPath", ")", "{", "if", "(", "!", "hasClassDecorators", "(", "classPath", ".", "node", ")", ")", "return", ";", "const", "decorators", "=", "classPath", ".", "node", ".", "decorators", "||", "[", "]", ";", "classPath", ".", "node", ".", "decorators", "=", "null", ";", "const", "name", "=", "classPath", ".", "scope", ".", "generateDeclaredUidIdentifier", "(", "\"class\"", ")", ";", "return", "decorators", ".", "map", "(", "dec", "=>", "dec", ".", "expression", ")", ".", "reverse", "(", ")", ".", "reduce", "(", "function", "(", "acc", ",", "decorator", ")", "{", "return", "buildClassDecorator", "(", "{", "CLASS_REF", ":", "t", ".", "cloneNode", "(", "name", ")", ",", "DECORATOR", ":", "t", ".", "cloneNode", "(", "decorator", ")", ",", "INNER", ":", "acc", ",", "}", ")", ".", "expression", ";", "}", ",", "classPath", ".", "node", ")", ";", "}" ]
Given a class expression with class-level decorators, create a new expression with the proper decorated behavior.
[ "Given", "a", "class", "expression", "with", "class", "-", "level", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L63-L81
729
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyMethodDecorators
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
javascript
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
[ "function", "applyMethodDecorators", "(", "path", ",", "state", ")", "{", "if", "(", "!", "hasMethodDecorators", "(", "path", ".", "node", ".", "body", ".", "body", ")", ")", "return", ";", "return", "applyTargetDecorators", "(", "path", ",", "state", ",", "path", ".", "node", ".", "body", ".", "body", ")", ";", "}" ]
Given a class expression with method-level decorators, create a new expression with the proper decorated behavior.
[ "Given", "a", "class", "expression", "with", "method", "-", "level", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L91-L95
730
babel/babel
packages/babel-plugin-proposal-decorators/src/transformer-legacy.js
applyObjectDecorators
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
javascript
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
[ "function", "applyObjectDecorators", "(", "path", ",", "state", ")", "{", "if", "(", "!", "hasMethodDecorators", "(", "path", ".", "node", ".", "properties", ")", ")", "return", ";", "return", "applyTargetDecorators", "(", "path", ",", "state", ",", "path", ".", "node", ".", "properties", ")", ";", "}" ]
Given an object expression with property decorators, create a new expression with the proper decorated behavior.
[ "Given", "an", "object", "expression", "with", "property", "decorators", "create", "a", "new", "expression", "with", "the", "proper", "decorated", "behavior", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js#L105-L109
731
babel/babel
packages/babel-highlight/src/index.js
getDefs
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold, }; }
javascript
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold, }; }
[ "function", "getDefs", "(", "chalk", ")", "{", "return", "{", "keyword", ":", "chalk", ".", "cyan", ",", "capitalized", ":", "chalk", ".", "yellow", ",", "jsx_tag", ":", "chalk", ".", "yellow", ",", "punctuator", ":", "chalk", ".", "yellow", ",", "// bracket: intentionally omitted.", "number", ":", "chalk", ".", "magenta", ",", "string", ":", "chalk", ".", "green", ",", "regex", ":", "chalk", ".", "magenta", ",", "comment", ":", "chalk", ".", "grey", ",", "invalid", ":", "chalk", ".", "white", ".", "bgRed", ".", "bold", ",", "}", ";", "}" ]
Chalk styles for token types.
[ "Chalk", "styles", "for", "token", "types", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-highlight/src/index.js#L8-L21
732
babel/babel
packages/babel-highlight/src/index.js
getTokenType
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</") ) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if ( token.type === "invalid" && (token.value === "@" || token.value === "#") ) { return "punctuator"; } return token.type; }
javascript
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</") ) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if ( token.type === "invalid" && (token.value === "@" || token.value === "#") ) { return "punctuator"; } return token.type; }
[ "function", "getTokenType", "(", "match", ")", "{", "const", "[", "offset", ",", "text", "]", "=", "match", ".", "slice", "(", "-", "2", ")", ";", "const", "token", "=", "matchToToken", "(", "match", ")", ";", "if", "(", "token", ".", "type", "===", "\"name\"", ")", "{", "if", "(", "esutils", ".", "keyword", ".", "isReservedWordES6", "(", "token", ".", "value", ")", ")", "{", "return", "\"keyword\"", ";", "}", "if", "(", "JSX_TAG", ".", "test", "(", "token", ".", "value", ")", "&&", "(", "text", "[", "offset", "-", "1", "]", "===", "\"<\"", "||", "text", ".", "substr", "(", "offset", "-", "2", ",", "2", ")", "==", "\"</\"", ")", ")", "{", "return", "\"jsx_tag\"", ";", "}", "if", "(", "token", ".", "value", "[", "0", "]", "!==", "token", ".", "value", "[", "0", "]", ".", "toLowerCase", "(", ")", ")", "{", "return", "\"capitalized\"", ";", "}", "}", "if", "(", "token", ".", "type", "===", "\"punctuator\"", "&&", "BRACKET", ".", "test", "(", "token", ".", "value", ")", ")", "{", "return", "\"bracket\"", ";", "}", "if", "(", "token", ".", "type", "===", "\"invalid\"", "&&", "(", "token", ".", "value", "===", "\"@\"", "||", "token", ".", "value", "===", "\"#\"", ")", ")", "{", "return", "\"punctuator\"", ";", "}", "return", "token", ".", "type", ";", "}" ]
Get the type of token, specifying punctuator type.
[ "Get", "the", "type", "of", "token", "specifying", "punctuator", "type", "." ]
1969e6b6aa7d90be3fbb3aca98ea96849656a55a
https://github.com/babel/babel/blob/1969e6b6aa7d90be3fbb3aca98ea96849656a55a/packages/babel-highlight/src/index.js#L41-L74
733
TryGhost/Ghost
core/server/services/auth/oauth.js
exchangePassword
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user return models.User.check({email: username, password: password}) .then(function then(user) { return authUtils.createTokens({ clientId: client.id, userId: user.id }); }) .then(function then(response) { web.shared.middlewares.api.spamPrevention.userLogin() .reset(authInfo.ip, username + 'login'); return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in}); }) .catch(function (err) { done(err, false); }); }
javascript
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user return models.User.check({email: username, password: password}) .then(function then(user) { return authUtils.createTokens({ clientId: client.id, userId: user.id }); }) .then(function then(response) { web.shared.middlewares.api.spamPrevention.userLogin() .reset(authInfo.ip, username + 'login'); return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in}); }) .catch(function (err) { done(err, false); }); }
[ "function", "exchangePassword", "(", "client", ",", "username", ",", "password", ",", "scope", ",", "body", ",", "authInfo", ",", "done", ")", "{", "if", "(", "!", "client", "||", "!", "client", ".", "id", ")", "{", "return", "done", "(", "new", "common", ".", "errors", ".", "UnauthorizedError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.middleware.auth.clientCredentialsNotProvided'", ")", "}", ")", ",", "false", ")", ";", "}", "// Validate the user", "return", "models", ".", "User", ".", "check", "(", "{", "email", ":", "username", ",", "password", ":", "password", "}", ")", ".", "then", "(", "function", "then", "(", "user", ")", "{", "return", "authUtils", ".", "createTokens", "(", "{", "clientId", ":", "client", ".", "id", ",", "userId", ":", "user", ".", "id", "}", ")", ";", "}", ")", ".", "then", "(", "function", "then", "(", "response", ")", "{", "web", ".", "shared", ".", "middlewares", ".", "api", ".", "spamPrevention", ".", "userLogin", "(", ")", ".", "reset", "(", "authInfo", ".", "ip", ",", "username", "+", "'login'", ")", ";", "return", "done", "(", "null", ",", "response", ".", "access_token", ",", "response", ".", "refresh_token", ",", "{", "expires_in", ":", "response", ".", "expires_in", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "done", "(", "err", ",", "false", ")", ";", "}", ")", ";", "}" ]
We are required to pass in authInfo in order to reset spam counter for user login
[ "We", "are", "required", "to", "pass", "in", "authInfo", "in", "order", "to", "reset", "spam", "counter", "for", "user", "login" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/auth/oauth.js#L64-L88
734
TryGhost/Ghost
core/server/api/v0.1/authentication.js
assertSetupCompleted
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted'); function throwReason(reason) { throw new common.errors.NoPermissionError({message: reason}); } if (isSetup) { throwReason(completed); } else { throwReason(notCompleted); } }); }; }
javascript
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted'); function throwReason(reason) { throw new common.errors.NoPermissionError({message: reason}); } if (isSetup) { throwReason(completed); } else { throwReason(notCompleted); } }); }; }
[ "function", "assertSetupCompleted", "(", "status", ")", "{", "return", "function", "checkPermission", "(", "__", ")", "{", "return", "checkSetup", "(", ")", ".", "then", "(", "(", "isSetup", ")", "=>", "{", "if", "(", "isSetup", "===", "status", ")", "{", "return", "__", ";", "}", "const", "completed", "=", "common", ".", "i18n", ".", "t", "(", "'errors.api.authentication.setupAlreadyCompleted'", ")", ",", "notCompleted", "=", "common", ".", "i18n", ".", "t", "(", "'errors.api.authentication.setupMustBeCompleted'", ")", ";", "function", "throwReason", "(", "reason", ")", "{", "throw", "new", "common", ".", "errors", ".", "NoPermissionError", "(", "{", "message", ":", "reason", "}", ")", ";", "}", "if", "(", "isSetup", ")", "{", "throwReason", "(", "completed", ")", ";", "}", "else", "{", "throwReason", "(", "notCompleted", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Allows an assertion to be made about setup status. @param {Boolean} status True: setup must be complete. False: setup must not be complete. @return {Function} returns a "task ready" function
[ "Allows", "an", "assertion", "to", "be", "made", "about", "setup", "status", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/authentication.js#L37-L58
735
TryGhost/Ghost
core/server/helpers/navigation.js
_isCurrentUrl
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
javascript
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
[ "function", "_isCurrentUrl", "(", "href", ",", "currentUrl", ")", "{", "if", "(", "!", "currentUrl", ")", "{", "return", "false", ";", "}", "var", "strippedHref", "=", "href", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ",", "strippedCurrentUrl", "=", "currentUrl", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ";", "return", "strippedHref", "===", "strippedCurrentUrl", ";", "}" ]
strips trailing slashes and compares urls
[ "strips", "trailing", "slashes", "and", "compares", "urls" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/helpers/navigation.js#L53-L61
736
TryGhost/Ghost
core/server/models/settings.js
parseDefaultSettings
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: crypto.randomBytes(32).toString('hex'), members_session_secret: crypto.randomBytes(32).toString('hex'), theme_session_secret: crypto.randomBytes(32).toString('hex') }; const membersKeypair = keypair({ bits: 1024 }); dynamicDefault.members_public_key = membersKeypair.public; dynamicDefault.members_private_key = membersKeypair.private; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; if (dynamicDefault[setting.key]) { setting.defaultValue = dynamicDefault[setting.key]; } defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; }
javascript
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: crypto.randomBytes(32).toString('hex'), members_session_secret: crypto.randomBytes(32).toString('hex'), theme_session_secret: crypto.randomBytes(32).toString('hex') }; const membersKeypair = keypair({ bits: 1024 }); dynamicDefault.members_public_key = membersKeypair.public; dynamicDefault.members_private_key = membersKeypair.private; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; if (dynamicDefault[setting.key]) { setting.defaultValue = dynamicDefault[setting.key]; } defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; }
[ "function", "parseDefaultSettings", "(", ")", "{", "var", "defaultSettingsInCategories", "=", "require", "(", "'../data/schema/'", ")", ".", "defaultSettings", ",", "defaultSettingsFlattened", "=", "{", "}", ",", "dynamicDefault", "=", "{", "db_hash", ":", "uuid", ".", "v4", "(", ")", ",", "public_hash", ":", "crypto", ".", "randomBytes", "(", "15", ")", ".", "toString", "(", "'hex'", ")", ",", "// @TODO: session_secret would ideally be named \"admin_session_secret\"", "session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", ",", "members_session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", ",", "theme_session_secret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'hex'", ")", "}", ";", "const", "membersKeypair", "=", "keypair", "(", "{", "bits", ":", "1024", "}", ")", ";", "dynamicDefault", ".", "members_public_key", "=", "membersKeypair", ".", "public", ";", "dynamicDefault", ".", "members_private_key", "=", "membersKeypair", ".", "private", ";", "_", ".", "each", "(", "defaultSettingsInCategories", ",", "function", "each", "(", "settings", ",", "categoryName", ")", "{", "_", ".", "each", "(", "settings", ",", "function", "each", "(", "setting", ",", "settingName", ")", "{", "setting", ".", "type", "=", "categoryName", ";", "setting", ".", "key", "=", "settingName", ";", "if", "(", "dynamicDefault", "[", "setting", ".", "key", "]", ")", "{", "setting", ".", "defaultValue", "=", "dynamicDefault", "[", "setting", ".", "key", "]", ";", "}", "defaultSettingsFlattened", "[", "settingName", "]", "=", "setting", ";", "}", ")", ";", "}", ")", ";", "return", "defaultSettingsFlattened", ";", "}" ]
For neatness, the defaults file is split into categories. It's much easier for us to work with it as a single level instead of iterating those categories every time
[ "For", "neatness", "the", "defaults", "file", "is", "split", "into", "categories", ".", "It", "s", "much", "easier", "for", "us", "to", "work", "with", "it", "as", "a", "single", "level", "instead", "of", "iterating", "those", "categories", "every", "time" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/settings.js#L16-L48
737
TryGhost/Ghost
core/server/lib/fs/package-json/parse.js
parsePackageJson
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { var hasRequiredKeys, json, err; try { json = JSON.parse(source); hasRequiredKeys = json.name && json.version; if (!hasRequiredKeys) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } return json; } catch (parseError) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } }); }
javascript
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { var hasRequiredKeys, json, err; try { json = JSON.parse(source); hasRequiredKeys = json.name && json.version; if (!hasRequiredKeys) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } return json; } catch (parseError) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } }); }
[ "function", "parsePackageJson", "(", "path", ")", "{", "return", "fs", ".", "readFile", "(", "path", ")", ".", "catch", "(", "function", "(", ")", "{", "var", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.couldNotReadPackage'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ".", "then", "(", "function", "(", "source", ")", "{", "var", "hasRequiredKeys", ",", "json", ",", "err", ";", "try", "{", "json", "=", "JSON", ".", "parse", "(", "source", ")", ";", "hasRequiredKeys", "=", "json", ".", "name", "&&", "json", ".", "version", ";", "if", "(", "!", "hasRequiredKeys", ")", "{", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.nameOrVersionMissing'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "err", ".", "help", "=", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.willBeRequired'", ",", "{", "url", ":", "'https://docs.ghost.org/api/handlebars-themes/'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "return", "json", ";", "}", "catch", "(", "parseError", ")", "{", "err", "=", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.themeFileIsMalformed'", ")", ")", ";", "err", ".", "context", "=", "path", ";", "err", ".", "help", "=", "common", ".", "i18n", ".", "t", "(", "'errors.utils.parsepackagejson.willBeRequired'", ",", "{", "url", ":", "'https://docs.ghost.org/api/handlebars-themes/'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Parse package.json and validate it has all the required fields
[ "Parse", "package", ".", "json", "and", "validate", "it", "has", "all", "the", "required", "fields" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/fs/package-json/parse.js#L14-L47
738
TryGhost/Ghost
core/server/data/importer/index.js
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
javascript
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
[ "function", "(", "items", ")", "{", "return", "'+('", "+", "_", ".", "reduce", "(", "items", ",", "function", "(", "memo", ",", "ext", ")", "{", "return", "memo", "!==", "''", "?", "memo", "+", "'|'", "+", "ext", ":", "ext", ";", "}", ",", "''", ")", "+", "')'", ";", "}" ]
Convert items into a glob string @param {String[]} items @returns {String}
[ "Convert", "items", "into", "a", "glob", "string" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L72-L76
739
TryGhost/Ghost
core/server/data/importer/index.js
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ), dirMatches = glob.sync( this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} ), oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')}); } // If this folder contains importable files or a content or images directory if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) { return true; } if (extMatchesAll.length < 1) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')}); } throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')}); }
javascript
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ), dirMatches = glob.sync( this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} ), oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')}); } // If this folder contains importable files or a content or images directory if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) { return true; } if (extMatchesAll.length < 1) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')}); } throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')}); }
[ "function", "(", "directory", ")", "{", "// Globs match content in the root or inside a single directory", "var", "extMatchesBase", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "extMatchesAll", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ALL_DIRS", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "dirMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "this", ".", "getDirectories", "(", ")", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "oldRoonMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "[", "'drafts'", ",", "'published'", ",", "'deleted'", "]", ",", "ROOT_OR_SINGLE_DIR", ")", ",", "{", "cwd", ":", "directory", "}", ")", ";", "// This is a temporary extra message for the old format roon export which doesn't work with Ghost", "if", "(", "oldRoonMatches", ".", "length", ">", "0", ")", "{", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.unsupportedRoonExport'", ")", "}", ")", ";", "}", "// If this folder contains importable files or a content or images directory", "if", "(", "extMatchesBase", ".", "length", ">", "0", "||", "(", "dirMatches", ".", "length", ">", "0", "&&", "extMatchesAll", ".", "length", ">", "0", ")", ")", "{", "return", "true", ";", "}", "if", "(", "extMatchesAll", ".", "length", "<", "1", ")", "{", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.noContentToImport'", ")", "}", ")", ";", "}", "throw", "new", "common", ".", "errors", ".", "UnsupportedMediaTypeError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.invalidZipStructure'", ")", "}", ")", ";", "}" ]
Checks the content of a zip folder to see if it is valid. Importable content includes any files or directories which the handlers can process Importable content must be found either in the root, or inside one base directory @param {String} directory @returns {Promise}
[ "Checks", "the", "content", "of", "a", "zip", "folder", "to", "see", "if", "it", "is", "valid", ".", "Importable", "content", "includes", "any", "files", "or", "directories", "which", "the", "handlers", "can", "process", "Importable", "content", "must", "be", "found", "either", "in", "the", "root", "or", "inside", "one", "base", "directory" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L138-L165
740
TryGhost/Ghost
core/server/data/importer/index.js
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
javascript
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
[ "function", "(", "filePath", ")", "{", "const", "tmpDir", "=", "path", ".", "join", "(", "os", ".", "tmpdir", "(", ")", ",", "uuid", ".", "v4", "(", ")", ")", ";", "this", ".", "fileToDelete", "=", "tmpDir", ";", "return", "Promise", ".", "promisify", "(", "extract", ")", "(", "filePath", ",", "{", "dir", ":", "tmpDir", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "tmpDir", ";", "}", ")", ";", "}" ]
Use the extract module to extract the given zip file to a temp directory & return the temp directory path @param {String} filePath @returns {Promise[]} Files
[ "Use", "the", "extract", "module", "to", "extract", "the", "given", "zip", "file", "to", "a", "temp", "directory", "&", "return", "the", "temp", "directory", "path" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L171-L178
741
TryGhost/Ghost
core/server/data/importer/index.js
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
javascript
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
[ "function", "(", "handler", ",", "directory", ")", "{", "var", "globPattern", "=", "this", ".", "getExtensionGlob", "(", "handler", ".", "extensions", ",", "ALL_DIRS", ")", ";", "return", "_", ".", "map", "(", "glob", ".", "sync", "(", "globPattern", ",", "{", "cwd", ":", "directory", "}", ")", ",", "function", "(", "file", ")", "{", "return", "{", "name", ":", "file", ",", "path", ":", "path", ".", "join", "(", "directory", ",", "file", ")", "}", ";", "}", ")", ";", "}" ]
Use the handler extensions to get a globbing pattern, then use that to fetch all the files from the zip which are relevant to the given handler, and return them as a name and path combo @param {Object} handler @param {String} directory @returns [] Files
[ "Use", "the", "handler", "extensions", "to", "get", "a", "globbing", "pattern", "then", "use", "that", "to", "fetch", "all", "the", "files", "from", "the", "zip", "which", "are", "relevant", "to", "the", "given", "handler", "and", "return", "them", "as", "a", "name", "and", "path", "combo" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L186-L191
742
TryGhost/Ghost
core/server/data/importer/index.js
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { return; } // There is a base directory, grab it from any ext match extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ); if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) { throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')}); } return extMatchesAll[0].split('/')[0]; }
javascript
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { return; } // There is a base directory, grab it from any ext match extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ); if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) { throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')}); } return extMatchesAll[0].split('/')[0]; }
[ "function", "(", "directory", ")", "{", "// Globs match root level only", "var", "extMatches", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ROOT_ONLY", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "dirMatches", "=", "glob", ".", "sync", "(", "this", ".", "getDirectoryGlob", "(", "this", ".", "getDirectories", "(", ")", ",", "ROOT_ONLY", ")", ",", "{", "cwd", ":", "directory", "}", ")", ",", "extMatchesAll", ";", "// There is no base directory", "if", "(", "extMatches", ".", "length", ">", "0", "||", "dirMatches", ".", "length", ">", "0", ")", "{", "return", ";", "}", "// There is a base directory, grab it from any ext match", "extMatchesAll", "=", "glob", ".", "sync", "(", "this", ".", "getExtensionGlob", "(", "this", ".", "getExtensions", "(", ")", ",", "ALL_DIRS", ")", ",", "{", "cwd", ":", "directory", "}", ")", ";", "if", "(", "extMatchesAll", ".", "length", "<", "1", "||", "extMatchesAll", "[", "0", "]", ".", "split", "(", "'/'", ")", "<", "1", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.data.importer.index.invalidZipFileBaseDirectory'", ")", "}", ")", ";", "}", "return", "extMatchesAll", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", ";", "}" ]
Get the name of the single base directory if there is one, else return an empty string @param {String} directory @returns {Promise (String)}
[ "Get", "the", "name", "of", "the", "single", "base", "directory", "if", "there", "is", "one", "else", "return", "an", "empty", "string" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L197-L216
743
TryGhost/Ghost
core/server/data/importer/index.js
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(function (importData) { // Step 3: Actually do the import // @TODO: It would be cool to have some sort of dry run flag here return self.doImport(importData, importOptions); }).then(function (importData) { // Step 4: Report on the import return self.generateReport(importData); }).finally(() => self.cleanUp()); // Step 5: Cleanup any files }
javascript
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(function (importData) { // Step 3: Actually do the import // @TODO: It would be cool to have some sort of dry run flag here return self.doImport(importData, importOptions); }).then(function (importData) { // Step 4: Report on the import return self.generateReport(importData); }).finally(() => self.cleanUp()); // Step 5: Cleanup any files }
[ "function", "(", "file", ",", "importOptions", "=", "{", "}", ")", "{", "var", "self", "=", "this", ";", "// Step 1: Handle converting the file to usable data", "return", "this", ".", "loadFile", "(", "file", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "// Step 2: Let the importers pre-process the data", "return", "self", ".", "preProcess", "(", "importData", ")", ";", "}", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "// Step 3: Actually do the import", "// @TODO: It would be cool to have some sort of dry run flag here", "return", "self", ".", "doImport", "(", "importData", ",", "importOptions", ")", ";", "}", ")", ".", "then", "(", "function", "(", "importData", ")", "{", "// Step 4: Report on the import", "return", "self", ".", "generateReport", "(", "importData", ")", ";", "}", ")", ".", "finally", "(", "(", ")", "=>", "self", ".", "cleanUp", "(", ")", ")", ";", "// Step 5: Cleanup any files", "}" ]
Import From File The main method of the ImportManager, call this to kick everything off! @param {File} file @param {importOptions} importOptions to allow override of certain import features such as locking a user @returns {Promise}
[ "Import", "From", "File", "The", "main", "method", "of", "the", "ImportManager", "call", "this", "to", "kick", "everything", "off!" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/importer/index.js#L356-L371
744
TryGhost/Ghost
core/server/data/meta/schema.js
trimSchema
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
javascript
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
[ "function", "trimSchema", "(", "schema", ")", "{", "var", "schemaObject", "=", "{", "}", ";", "_", ".", "each", "(", "schema", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "!==", "null", "&&", "typeof", "value", "!==", "'undefined'", ")", "{", "schemaObject", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "schemaObject", ";", "}" ]
Creates the final schema object with values that are not null
[ "Creates", "the", "final", "schema", "object", "with", "values", "that", "are", "not", "null" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/meta/schema.js#L26-L36
745
TryGhost/Ghost
core/server/lib/promise/sequence.js
sequence
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { results.push(result); return results; }); } else { return Promise.resolve().then(() => { results.push(response); return results; }); } }, []); }
javascript
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { results.push(result); return results; }); } else { return Promise.resolve().then(() => { results.push(response); return results; }); } }, []); }
[ "function", "sequence", "(", "tasks", "/* Any Arguments */", ")", "{", "const", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "return", "Promise", ".", "reduce", "(", "tasks", ",", "function", "(", "results", ",", "task", ")", "{", "const", "response", "=", "task", ".", "apply", "(", "this", ",", "args", ")", ";", "if", "(", "response", "&&", "response", ".", "then", ")", "{", "return", "response", ".", "then", "(", "function", "(", "result", ")", "{", "results", ".", "push", "(", "result", ")", ";", "return", "results", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "results", ".", "push", "(", "response", ")", ";", "return", "results", ";", "}", ")", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
expects an array of functions returning a promise
[ "expects", "an", "array", "of", "functions", "returning", "a", "promise" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/promise/sequence.js#L6-L24
746
TryGhost/Ghost
core/server/data/validation/index.js
characterOccurance
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if (!chars[char]) { chars[char] = 1; } else { chars[char] += 1; } }); // check if any of the accumulated chars exceed the allowed occurancy // of 50% of the words' length. _.forIn(chars, function (charCount) { if (charCount >= allowedOccurancy) { valid = false; } }); return valid; }
javascript
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if (!chars[char]) { chars[char] = 1; } else { chars[char] += 1; } }); // check if any of the accumulated chars exceed the allowed occurancy // of 50% of the words' length. _.forIn(chars, function (charCount) { if (charCount >= allowedOccurancy) { valid = false; } }); return valid; }
[ "function", "characterOccurance", "(", "stringToTest", ")", "{", "var", "chars", "=", "{", "}", ",", "allowedOccurancy", ",", "valid", "=", "true", ";", "stringToTest", "=", "_", ".", "toString", "(", "stringToTest", ")", ";", "allowedOccurancy", "=", "stringToTest", ".", "length", "/", "2", ";", "// Loop through string and accumulate character counts", "_", ".", "each", "(", "stringToTest", ",", "function", "(", "char", ")", "{", "if", "(", "!", "chars", "[", "char", "]", ")", "{", "chars", "[", "char", "]", "=", "1", ";", "}", "else", "{", "chars", "[", "char", "]", "+=", "1", ";", "}", "}", ")", ";", "// check if any of the accumulated chars exceed the allowed occurancy", "// of 50% of the words' length.", "_", ".", "forIn", "(", "chars", ",", "function", "(", "charCount", ")", "{", "if", "(", "charCount", ">=", "allowedOccurancy", ")", "{", "valid", "=", "false", ";", "}", "}", ")", ";", "return", "valid", ";", "}" ]
Counts repeated characters in a string. When 50% or more characters are the same, we return false and therefore invalidate the string. @param {String} stringToTest The password string to check. @return {Boolean}
[ "Counts", "repeated", "characters", "in", "a", "string", ".", "When", "50%", "or", "more", "characters", "are", "the", "same", "we", "return", "false", "and", "therefore", "invalidate", "the", "string", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/validation/index.js#L27-L53
747
TryGhost/Ghost
core/server/models/permission.js
permittedAttributes
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
javascript
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
[ "function", "permittedAttributes", "(", ")", "{", "let", "filteredKeys", "=", "ghostBookshelf", ".", "Model", ".", "prototype", ".", "permittedAttributes", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "relationships", ".", "forEach", "(", "(", "key", ")", "=>", "{", "filteredKeys", ".", "push", "(", "key", ")", ";", "}", ")", ";", "return", "filteredKeys", ";", "}" ]
The base model keeps only the columns, which are defined in the schema. We have to add the relations on top, otherwise bookshelf-relations has no access to the nested relations, which should be updated.
[ "The", "base", "model", "keeps", "only", "the", "columns", "which", "are", "defined", "in", "the", "schema", ".", "We", "have", "to", "add", "the", "relations", "on", "top", "otherwise", "bookshelf", "-", "relations", "has", "no", "access", "to", "the", "nested", "relations", "which", "should", "be", "updated", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/permission.js#L20-L28
748
TryGhost/Ghost
core/server/services/apps/loader.js
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping the activate() with a when because it's possible // to not return a promise from it. return Promise.resolve(app.activate(proxy)).return(app); }
javascript
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping the activate() with a when because it's possible // to not return a promise from it. return Promise.resolve(app.activate(proxy)).return(app); }
[ "function", "(", "name", ")", "{", "const", "{", "app", ",", "proxy", "}", "=", "getAppByName", "(", "name", ")", ";", "// Check for an activate() method on the app.", "if", "(", "!", "_", ".", "isFunction", "(", "app", ".", "activate", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "common", ".", "i18n", ".", "t", "(", "'errors.apps.noActivateMethodLoadingApp.error'", ",", "{", "name", ":", "name", "}", ")", ")", ")", ";", "}", "// Wrapping the activate() with a when because it's possible", "// to not return a promise from it.", "return", "Promise", ".", "resolve", "(", "app", ".", "activate", "(", "proxy", ")", ")", ".", "return", "(", "app", ")", ";", "}" ]
Activate a app and return it
[ "Activate", "a", "app", "and", "return", "it" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/apps/loader.js#L33-L44
749
TryGhost/Ghost
core/server/apps/amp/lib/router.js
getPostData
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two collections. * * @TODO: * * This is not optimal and caused by the fact how apps currently work. But apps weren't designed * for dynamic routing. * * I think if the responsible, target router would first take care fetching/determining the post, the * request could then be forwarded to this app. Then we don't have to: * * 1. care about fetching the post * 2. care about if the post can be served * 3. then this app would act like an extension * * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc. */ const permalinks = urlService.getPermalinkByUrl(urlWithoutSubdirectoryWithoutAmp, {withUrlOptions: true}); if (!permalinks) { return next(new common.errors.NotFoundError({ message: common.i18n.t('errors.errors.pageNotFound') })); } // @NOTE: amp is not supported for static pages // @TODO: https://github.com/TryGhost/Ghost/issues/10548 helpers.entryLookup(urlWithoutSubdirectoryWithoutAmp, {permalinks, query: {controller: 'postsPublic', resource: 'posts'}}, res.locals) .then((result) => { if (result && result.entry) { req.body.post = result.entry; } next(); }) .catch(next); }
javascript
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two collections. * * @TODO: * * This is not optimal and caused by the fact how apps currently work. But apps weren't designed * for dynamic routing. * * I think if the responsible, target router would first take care fetching/determining the post, the * request could then be forwarded to this app. Then we don't have to: * * 1. care about fetching the post * 2. care about if the post can be served * 3. then this app would act like an extension * * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc. */ const permalinks = urlService.getPermalinkByUrl(urlWithoutSubdirectoryWithoutAmp, {withUrlOptions: true}); if (!permalinks) { return next(new common.errors.NotFoundError({ message: common.i18n.t('errors.errors.pageNotFound') })); } // @NOTE: amp is not supported for static pages // @TODO: https://github.com/TryGhost/Ghost/issues/10548 helpers.entryLookup(urlWithoutSubdirectoryWithoutAmp, {permalinks, query: {controller: 'postsPublic', resource: 'posts'}}, res.locals) .then((result) => { if (result && result.entry) { req.body.post = result.entry; } next(); }) .catch(next); }
[ "function", "getPostData", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "body", "=", "req", ".", "body", "||", "{", "}", ";", "const", "urlWithoutSubdirectoryWithoutAmp", "=", "res", ".", "locals", ".", "relativeUrl", ".", "match", "(", "/", "(.*?\\/)amp\\/?$", "/", ")", "[", "1", "]", ";", "/**\n * @NOTE\n *\n * We have to figure out the target permalink, otherwise it would be possible to serve a post\n * which lives in two collections.\n *\n * @TODO:\n *\n * This is not optimal and caused by the fact how apps currently work. But apps weren't designed\n * for dynamic routing.\n *\n * I think if the responsible, target router would first take care fetching/determining the post, the\n * request could then be forwarded to this app. Then we don't have to:\n *\n * 1. care about fetching the post\n * 2. care about if the post can be served\n * 3. then this app would act like an extension\n *\n * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc.\n */", "const", "permalinks", "=", "urlService", ".", "getPermalinkByUrl", "(", "urlWithoutSubdirectoryWithoutAmp", ",", "{", "withUrlOptions", ":", "true", "}", ")", ";", "if", "(", "!", "permalinks", ")", "{", "return", "next", "(", "new", "common", ".", "errors", ".", "NotFoundError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.errors.pageNotFound'", ")", "}", ")", ")", ";", "}", "// @NOTE: amp is not supported for static pages", "// @TODO: https://github.com/TryGhost/Ghost/issues/10548", "helpers", ".", "entryLookup", "(", "urlWithoutSubdirectoryWithoutAmp", ",", "{", "permalinks", ",", "query", ":", "{", "controller", ":", "'postsPublic'", ",", "resource", ":", "'posts'", "}", "}", ",", "res", ".", "locals", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "if", "(", "result", "&&", "result", ".", "entry", ")", "{", "req", ".", "body", ".", "post", "=", "result", ".", "entry", ";", "}", "next", "(", ")", ";", "}", ")", ".", "catch", "(", "next", ")", ";", "}" ]
This here is a controller. In fact, this whole file is nothing more than a controller + renderer & doesn't need to be a router
[ "This", "here", "is", "a", "controller", ".", "In", "fact", "this", "whole", "file", "is", "nothing", "more", "than", "a", "controller", "+", "renderer", "&", "doesn", "t", "need", "to", "be", "a", "router" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/apps/amp/lib/router.js#L33-L77
750
TryGhost/Ghost
core/server/data/meta/image-dimensions.js
getImageDimensions
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo.url) }; return Promise .props(fetch) .then(function (imageObj) { _.forEach(imageObj, function (key, value) { if (_.has(key, 'width') && _.has(key, 'height')) { // We have some restrictions for publisher.logo: // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), // we will fake it in some cases or not produce an imageObject at all. if (value === 'logo') { if (key.height <= 60 && key.width <= 600) { _.assign(metaData.blog[value], { dimensions: { width: key.width, height: key.height } }); } else if (key.width === key.height) { // CASE: the logo is too large, but it is a square. We fake it... _.assign(metaData.blog[value], { dimensions: { width: 60, height: 60 } }); } } else { _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); } } }); return metaData; }); }
javascript
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo.url) }; return Promise .props(fetch) .then(function (imageObj) { _.forEach(imageObj, function (key, value) { if (_.has(key, 'width') && _.has(key, 'height')) { // We have some restrictions for publisher.logo: // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), // we will fake it in some cases or not produce an imageObject at all. if (value === 'logo') { if (key.height <= 60 && key.width <= 600) { _.assign(metaData.blog[value], { dimensions: { width: key.width, height: key.height } }); } else if (key.width === key.height) { // CASE: the logo is too large, but it is a square. We fake it... _.assign(metaData.blog[value], { dimensions: { width: 60, height: 60 } }); } } else { _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); } } }); return metaData; }); }
[ "function", "getImageDimensions", "(", "metaData", ")", "{", "var", "fetch", "=", "{", "coverImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "coverImage", ".", "url", ")", ",", "authorImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "authorImage", ".", "url", ")", ",", "ogImage", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "ogImage", ".", "url", ")", ",", "logo", ":", "imageLib", ".", "imageSizeCache", "(", "metaData", ".", "blog", ".", "logo", ".", "url", ")", "}", ";", "return", "Promise", ".", "props", "(", "fetch", ")", ".", "then", "(", "function", "(", "imageObj", ")", "{", "_", ".", "forEach", "(", "imageObj", ",", "function", "(", "key", ",", "value", ")", "{", "if", "(", "_", ".", "has", "(", "key", ",", "'width'", ")", "&&", "_", ".", "has", "(", "key", ",", "'height'", ")", ")", "{", "// We have some restrictions for publisher.logo:", "// The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px).", "// Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453),", "// we will fake it in some cases or not produce an imageObject at all.", "if", "(", "value", "===", "'logo'", ")", "{", "if", "(", "key", ".", "height", "<=", "60", "&&", "key", ".", "width", "<=", "600", ")", "{", "_", ".", "assign", "(", "metaData", ".", "blog", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "key", ".", "width", ",", "height", ":", "key", ".", "height", "}", "}", ")", ";", "}", "else", "if", "(", "key", ".", "width", "===", "key", ".", "height", ")", "{", "// CASE: the logo is too large, but it is a square. We fake it...", "_", ".", "assign", "(", "metaData", ".", "blog", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "60", ",", "height", ":", "60", "}", "}", ")", ";", "}", "}", "else", "{", "_", ".", "assign", "(", "metaData", "[", "value", "]", ",", "{", "dimensions", ":", "{", "width", ":", "key", ".", "width", ",", "height", ":", "key", ".", "height", "}", "}", ")", ";", "}", "}", "}", ")", ";", "return", "metaData", ";", "}", ")", ";", "}" ]
Get Image dimensions @param {object} metaData @returns {object} metaData @description for image properties in meta data (coverImage, authorImage and blog.logo), `getCachedImageSizeFromUrl` is called to receive image width and height
[ "Get", "Image", "dimensions" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/data/meta/image-dimensions.js#L12-L59
751
TryGhost/Ghost
core/server/services/permissions/can-this.js
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } // Grab the object id (if specified, could be null) permObjId = perm.get('object_id'); // If we didn't specify a model (any thing) // or the permission didn't have an id scope set // then the "thing" has permission if (!modelId || !permObjId) { return true; } // Otherwise, check if the id's match // TODO: String vs Int comparison possibility here? return modelId === permObjId; }
javascript
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } // Grab the object id (if specified, could be null) permObjId = perm.get('object_id'); // If we didn't specify a model (any thing) // or the permission didn't have an id scope set // then the "thing" has permission if (!modelId || !permObjId) { return true; } // Otherwise, check if the id's match // TODO: String vs Int comparison possibility here? return modelId === permObjId; }
[ "function", "(", "perm", ")", "{", "var", "permObjId", ";", "// Look for a matching action type and object type first", "if", "(", "perm", ".", "get", "(", "'action_type'", ")", "!==", "actType", "||", "perm", ".", "get", "(", "'object_type'", ")", "!==", "objType", ")", "{", "return", "false", ";", "}", "// Grab the object id (if specified, could be null)", "permObjId", "=", "perm", ".", "get", "(", "'object_id'", ")", ";", "// If we didn't specify a model (any thing)", "// or the permission didn't have an id scope set", "// then the \"thing\" has permission", "if", "(", "!", "modelId", "||", "!", "permObjId", ")", "{", "return", "true", ";", "}", "// Otherwise, check if the id's match", "// TODO: String vs Int comparison possibility here?", "return", "modelId", "===", "permObjId", ";", "}" ]
Iterate through the user permissions looking for an affirmation
[ "Iterate", "through", "the", "user", "permissions", "looking", "for", "an", "affirmation" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/permissions/can-this.js#L58-L79
752
TryGhost/Ghost
core/server/api/v0.1/mail.js
sendMail
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ type: 'warn', message: [ common.i18n.t('warnings.index.unableToSendEmail'), common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'}) ].join(' ') }] }, {context: {internal: true}} ); } return Promise.reject(err); }); }
javascript
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ type: 'warn', message: [ common.i18n.t('warnings.index.unableToSendEmail'), common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'}) ].join(' ') }] }, {context: {internal: true}} ); } return Promise.reject(err); }); }
[ "function", "sendMail", "(", "object", ")", "{", "if", "(", "!", "(", "mailer", "instanceof", "mail", ".", "GhostMailer", ")", ")", "{", "mailer", "=", "new", "mail", ".", "GhostMailer", "(", ")", ";", "}", "return", "mailer", ".", "send", "(", "object", ".", "mail", "[", "0", "]", ".", "message", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "if", "(", "mailer", ".", "state", ".", "usingDirect", ")", "{", "notificationsAPI", ".", "add", "(", "{", "notifications", ":", "[", "{", "type", ":", "'warn'", ",", "message", ":", "[", "common", ".", "i18n", ".", "t", "(", "'warnings.index.unableToSendEmail'", ")", ",", "common", ".", "i18n", ".", "t", "(", "'common.seeLinkForInstructions'", ",", "{", "link", ":", "'https://docs.ghost.org/mail/'", "}", ")", "]", ".", "join", "(", "' '", ")", "}", "]", "}", ",", "{", "context", ":", "{", "internal", ":", "true", "}", "}", ")", ";", "}", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "}" ]
Send mail helper
[ "Send", "mail", "helper" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/mail.js#L18-L41
753
TryGhost/Ghost
core/server/apps/subscribers/lib/router.js
errorHandler
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res); } next(error); }
javascript
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res); } next(error); }
[ "function", "errorHandler", "(", "error", ",", "req", ",", "res", ",", "next", ")", "{", "req", ".", "body", ".", "email", "=", "''", ";", "req", ".", "body", ".", "subscribed_url", "=", "santizeUrl", "(", "req", ".", "body", ".", "subscribed_url", ")", ";", "req", ".", "body", ".", "subscribed_referrer", "=", "santizeUrl", "(", "req", ".", "body", ".", "subscribed_referrer", ")", ";", "if", "(", "error", ".", "statusCode", "!==", "404", ")", "{", "res", ".", "locals", ".", "error", "=", "error", ";", "return", "_renderer", "(", "req", ",", "res", ")", ";", "}", "next", "(", "error", ")", ";", "}" ]
Takes care of sanitizing the email input. XSS prevention. For success cases, we don't have to worry, because then the input contained a valid email address.
[ "Takes", "care", "of", "sanitizing", "the", "email", "input", ".", "XSS", "prevention", ".", "For", "success", "cases", "we", "don", "t", "have", "to", "worry", "because", "then", "the", "input", "contained", "a", "valid", "email", "address", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/apps/subscribers/lib/router.js#L33-L44
754
TryGhost/Ghost
core/server/api/v0.1/subscribers.js
exportSubscribers
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
javascript
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
[ "function", "exportSubscribers", "(", ")", "{", "return", "models", ".", "Subscriber", ".", "findAll", "(", "options", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "return", "formatCSV", "(", "data", ".", "toJSON", "(", "options", ")", ")", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "return", "Promise", ".", "reject", "(", "new", "common", ".", "errors", ".", "GhostError", "(", "{", "err", ":", "err", "}", ")", ")", ";", "}", ")", ";", "}" ]
Export data, otherwise send error 500
[ "Export", "data", "otherwise", "send", "error", "500" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v0.1/subscribers.js#L285-L291
755
TryGhost/Ghost
core/server/lib/common/i18n.js
t
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then // loop through them and return an array of translated/formatted strings. Otherwise, just return the normal // translated/formatted string. if (Array.isArray(string)) { msg = []; string.forEach(function (s) { let m = new MessageFormat(s, currentLocale); try { m.format(bindings); } catch (err) { logging.error(err.message); // fallback m = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); m = msg.format(); } msg.push(m); }); } else { msg = new MessageFormat(string, currentLocale); try { msg = msg.format(bindings); } catch (err) { logging.error(err.message); // fallback msg = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); msg = msg.format(); } } return msg; }
javascript
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then // loop through them and return an array of translated/formatted strings. Otherwise, just return the normal // translated/formatted string. if (Array.isArray(string)) { msg = []; string.forEach(function (s) { let m = new MessageFormat(s, currentLocale); try { m.format(bindings); } catch (err) { logging.error(err.message); // fallback m = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); m = msg.format(); } msg.push(m); }); } else { msg = new MessageFormat(string, currentLocale); try { msg = msg.format(bindings); } catch (err) { logging.error(err.message); // fallback msg = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); msg = msg.format(); } } return msg; }
[ "function", "t", "(", "path", ",", "bindings", ")", "{", "let", "string", ",", "isTheme", ",", "msg", ";", "currentLocale", "=", "I18n", ".", "locale", "(", ")", ";", "if", "(", "bindings", "!==", "undefined", ")", "{", "isTheme", "=", "bindings", ".", "isThemeString", ";", "delete", "bindings", ".", "isThemeString", ";", "}", "string", "=", "I18n", ".", "findString", "(", "path", ",", "{", "isThemeString", ":", "isTheme", "}", ")", ";", "// If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then", "// loop through them and return an array of translated/formatted strings. Otherwise, just return the normal", "// translated/formatted string.", "if", "(", "Array", ".", "isArray", "(", "string", ")", ")", "{", "msg", "=", "[", "]", ";", "string", ".", "forEach", "(", "function", "(", "s", ")", "{", "let", "m", "=", "new", "MessageFormat", "(", "s", ",", "currentLocale", ")", ";", "try", "{", "m", ".", "format", "(", "bindings", ")", ";", "}", "catch", "(", "err", ")", "{", "logging", ".", "error", "(", "err", ".", "message", ")", ";", "// fallback", "m", "=", "new", "MessageFormat", "(", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ",", "currentLocale", ")", ";", "m", "=", "msg", ".", "format", "(", ")", ";", "}", "msg", ".", "push", "(", "m", ")", ";", "}", ")", ";", "}", "else", "{", "msg", "=", "new", "MessageFormat", "(", "string", ",", "currentLocale", ")", ";", "try", "{", "msg", "=", "msg", ".", "format", "(", "bindings", ")", ";", "}", "catch", "(", "err", ")", "{", "logging", ".", "error", "(", "err", ".", "message", ")", ";", "// fallback", "msg", "=", "new", "MessageFormat", "(", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ",", "currentLocale", ")", ";", "msg", "=", "msg", ".", "format", "(", ")", ";", "}", "}", "return", "msg", ";", "}" ]
Helper method to find and compile the given data context with a proper string resource. @param {string} path Path with in the JSON language file to desired string (ie: "errors.init.jsNotBuilt") @param {object} [bindings] @returns {string}
[ "Helper", "method", "to", "find", "and", "compile", "the", "given", "data", "context", "with", "a", "proper", "string", "resource", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/common/i18n.js#L61-L106
756
TryGhost/Ghost
core/server/lib/common/i18n.js
findString
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; } // If not in memory, load translations for core if (coreStrings === undefined) { I18n.init(); } if (options.isThemeString) { // If not in memory, load translations for theme if (themeStrings === undefined) { I18n.loadThemeTranslations(); } // Both jsonpath's dot-notation and bracket-notation start with '$' // E.g.: $.store.book.title or $['store']['book']['title'] // The {{t}} translation helper passes the default English text // The full Unicode jsonpath with '$' is built here // jp.stringify and jp.value are jsonpath methods // Info: https://www.npmjs.com/package/jsonpath path = jp.stringify(['$', msgPath]); candidateString = jp.value(themeStrings, path) || msgPath; } else { // Backend messages use dot-notation, and the '$.' prefix is added here // While bracket-notation allows any Unicode characters in keys for themes, // dot-notation allows only word characters in keys for backend messages // (that is \w or [A-Za-z0-9_] in RegExp) path = `$.${msgPath}`; candidateString = jp.value(coreStrings, path); } matchingString = candidateString || {}; if (isObject(matchingString) || isEqual(matchingString, {})) { if (options.log) { logging.error(new errors.IncorrectUsageError({ message: `i18n error: path "${msgPath}" was not found` })); } matchingString = coreStrings.errors.errors.anErrorOccurred; } return matchingString; }
javascript
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; } // If not in memory, load translations for core if (coreStrings === undefined) { I18n.init(); } if (options.isThemeString) { // If not in memory, load translations for theme if (themeStrings === undefined) { I18n.loadThemeTranslations(); } // Both jsonpath's dot-notation and bracket-notation start with '$' // E.g.: $.store.book.title or $['store']['book']['title'] // The {{t}} translation helper passes the default English text // The full Unicode jsonpath with '$' is built here // jp.stringify and jp.value are jsonpath methods // Info: https://www.npmjs.com/package/jsonpath path = jp.stringify(['$', msgPath]); candidateString = jp.value(themeStrings, path) || msgPath; } else { // Backend messages use dot-notation, and the '$.' prefix is added here // While bracket-notation allows any Unicode characters in keys for themes, // dot-notation allows only word characters in keys for backend messages // (that is \w or [A-Za-z0-9_] in RegExp) path = `$.${msgPath}`; candidateString = jp.value(coreStrings, path); } matchingString = candidateString || {}; if (isObject(matchingString) || isEqual(matchingString, {})) { if (options.log) { logging.error(new errors.IncorrectUsageError({ message: `i18n error: path "${msgPath}" was not found` })); } matchingString = coreStrings.errors.errors.anErrorOccurred; } return matchingString; }
[ "function", "findString", "(", "msgPath", ",", "opts", ")", "{", "const", "options", "=", "merge", "(", "{", "log", ":", "true", "}", ",", "opts", "||", "{", "}", ")", ";", "let", "candidateString", ",", "matchingString", ",", "path", ";", "// no path? no string", "if", "(", "msgPath", ".", "length", "===", "0", "||", "!", "isString", "(", "msgPath", ")", ")", "{", "chalk", ".", "yellow", "(", "'i18n.t() - received an empty path.'", ")", ";", "return", "''", ";", "}", "// If not in memory, load translations for core", "if", "(", "coreStrings", "===", "undefined", ")", "{", "I18n", ".", "init", "(", ")", ";", "}", "if", "(", "options", ".", "isThemeString", ")", "{", "// If not in memory, load translations for theme", "if", "(", "themeStrings", "===", "undefined", ")", "{", "I18n", ".", "loadThemeTranslations", "(", ")", ";", "}", "// Both jsonpath's dot-notation and bracket-notation start with '$'", "// E.g.: $.store.book.title or $['store']['book']['title']", "// The {{t}} translation helper passes the default English text", "// The full Unicode jsonpath with '$' is built here", "// jp.stringify and jp.value are jsonpath methods", "// Info: https://www.npmjs.com/package/jsonpath", "path", "=", "jp", ".", "stringify", "(", "[", "'$'", ",", "msgPath", "]", ")", ";", "candidateString", "=", "jp", ".", "value", "(", "themeStrings", ",", "path", ")", "||", "msgPath", ";", "}", "else", "{", "// Backend messages use dot-notation, and the '$.' prefix is added here", "// While bracket-notation allows any Unicode characters in keys for themes,", "// dot-notation allows only word characters in keys for backend messages", "// (that is \\w or [A-Za-z0-9_] in RegExp)", "path", "=", "`", "${", "msgPath", "}", "`", ";", "candidateString", "=", "jp", ".", "value", "(", "coreStrings", ",", "path", ")", ";", "}", "matchingString", "=", "candidateString", "||", "{", "}", ";", "if", "(", "isObject", "(", "matchingString", ")", "||", "isEqual", "(", "matchingString", ",", "{", "}", ")", ")", "{", "if", "(", "options", ".", "log", ")", "{", "logging", ".", "error", "(", "new", "errors", ".", "IncorrectUsageError", "(", "{", "message", ":", "`", "${", "msgPath", "}", "`", "}", ")", ")", ";", "}", "matchingString", "=", "coreStrings", ".", "errors", ".", "errors", ".", "anErrorOccurred", ";", "}", "return", "matchingString", ";", "}" ]
Parse JSON file for matching locale, returns string giving path. @param {string} msgPath Path with in the JSON language file to desired string (ie: "errors.init.jsNotBuilt") @returns {string}
[ "Parse", "JSON", "file", "for", "matching", "locale", "returns", "string", "giving", "path", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/lib/common/i18n.js#L114-L164
757
TryGhost/Ghost
core/server/models/post.js
onSaved
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].indexOf(status) !== -1) { model.emitChange(status, options); } }
javascript
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].indexOf(status) !== -1) { model.emitChange(status, options); } }
[ "function", "onSaved", "(", "model", ",", "response", ",", "options", ")", "{", "ghostBookshelf", ".", "Model", ".", "prototype", ".", "onSaved", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "options", ".", "method", "!==", "'insert'", ")", "{", "return", ";", "}", "var", "status", "=", "model", ".", "get", "(", "'status'", ")", ";", "model", ".", "emitChange", "(", "'added'", ",", "options", ")", ";", "if", "(", "[", "'published'", ",", "'scheduled'", "]", ".", "indexOf", "(", "status", ")", "!==", "-", "1", ")", "{", "model", ".", "emitChange", "(", "status", ",", "options", ")", ";", "}", "}" ]
We update the tags after the Post was inserted. We update the tags before the Post was updated, see `onSaving` event. `onCreated` is called before `onSaved`. `onSaved` is the last event in the line - triggered for updating or inserting data. bookshelf-relations listens on `created` + `updated`. We ensure that we are catching the event after bookshelf relations.
[ "We", "update", "the", "tags", "after", "the", "Post", "was", "inserted", ".", "We", "update", "the", "tags", "before", "the", "Post", "was", "updated", "see", "onSaving", "event", ".", "onCreated", "is", "called", "before", "onSaved", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/post.js#L97-L111
758
TryGhost/Ghost
core/server/models/post.js
filterData
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
javascript
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
[ "function", "filterData", "(", "data", ")", "{", "var", "filteredData", "=", "ghostBookshelf", ".", "Model", ".", "filterData", ".", "apply", "(", "this", ",", "arguments", ")", ",", "extraData", "=", "_", ".", "pick", "(", "data", ",", "this", ".", "prototype", ".", "relationships", ")", ";", "_", ".", "merge", "(", "filteredData", ",", "extraData", ")", ";", "return", "filteredData", ";", "}" ]
Manually add 'tags' attribute since it's not in the schema and call parent. @param {Object} data Has keys representing the model's attributes/fields in the database. @return {Object} The filtered results of the passed in data, containing only what's allowed in the schema.
[ "Manually", "add", "tags", "attribute", "since", "it", "s", "not", "in", "the", "schema", "and", "call", "parent", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/post.js#L749-L755
759
TryGhost/Ghost
core/server/api/v2/utils/serializers/output/utils/members.js
hideMembersOnlyContent
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.original.context.member; if (!postHasMemberTag) { return PERMIT_CONTENT; } if (!requestFromMember) { return BLOCK_CONTENT; } const memberHasPlan = !!(frame.original.context.member.plans || []).length; if (!membersService.api.isPaymentConfigured()) { return PERMIT_CONTENT; } if (memberHasPlan) { return PERMIT_CONTENT; } return BLOCK_CONTENT; }
javascript
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.original.context.member; if (!postHasMemberTag) { return PERMIT_CONTENT; } if (!requestFromMember) { return BLOCK_CONTENT; } const memberHasPlan = !!(frame.original.context.member.plans || []).length; if (!membersService.api.isPaymentConfigured()) { return PERMIT_CONTENT; } if (memberHasPlan) { return PERMIT_CONTENT; } return BLOCK_CONTENT; }
[ "function", "hideMembersOnlyContent", "(", "attrs", ",", "frame", ")", "{", "const", "membersEnabled", "=", "labs", ".", "isSet", "(", "'members'", ")", ";", "if", "(", "!", "membersEnabled", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "const", "postHasMemberTag", "=", "attrs", ".", "tags", "&&", "attrs", ".", "tags", ".", "find", "(", "(", "tag", ")", "=>", "{", "return", "(", "tag", ".", "name", "===", "MEMBER_TAG", ")", ";", "}", ")", ";", "const", "requestFromMember", "=", "frame", ".", "original", ".", "context", ".", "member", ";", "if", "(", "!", "postHasMemberTag", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "if", "(", "!", "requestFromMember", ")", "{", "return", "BLOCK_CONTENT", ";", "}", "const", "memberHasPlan", "=", "!", "!", "(", "frame", ".", "original", ".", "context", ".", "member", ".", "plans", "||", "[", "]", ")", ".", "length", ";", "if", "(", "!", "membersService", ".", "api", ".", "isPaymentConfigured", "(", ")", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "if", "(", "memberHasPlan", ")", "{", "return", "PERMIT_CONTENT", ";", "}", "return", "BLOCK_CONTENT", ";", "}" ]
Checks if request should hide memnbers only content
[ "Checks", "if", "request", "should", "hide", "memnbers", "only", "content" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/api/v2/utils/serializers/output/utils/members.js#L8-L33
760
TryGhost/Ghost
core/server/services/url/utils.js
getVersionPath
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = apiVersions[versionData]; } let versionPath = versionData[requestedVersionType]; return `/${versionPath}/`; }
javascript
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = apiVersions[versionData]; } let versionPath = versionData[requestedVersionType]; return `/${versionPath}/`; }
[ "function", "getVersionPath", "(", "options", ")", "{", "const", "apiVersions", "=", "config", ".", "get", "(", "'api:versions'", ")", ";", "let", "requestedVersion", "=", "options", ".", "version", "||", "'v0.1'", ";", "let", "requestedVersionType", "=", "options", ".", "type", "||", "'content'", ";", "let", "versionData", "=", "apiVersions", "[", "requestedVersion", "]", ";", "if", "(", "typeof", "versionData", "===", "'string'", ")", "{", "versionData", "=", "apiVersions", "[", "versionData", "]", ";", "}", "let", "versionPath", "=", "versionData", "[", "requestedVersionType", "]", ";", "return", "`", "${", "versionPath", "}", "`", ";", "}" ]
Returns path containing only the path for the specific version asked or deprecated by default @param {Object} options {version} for which to get the path(stable, actice, deprecated), {type} admin|content: defaults to {version: deprecated, type: content} @return {string} API version path
[ "Returns", "path", "containing", "only", "the", "path", "for", "the", "specific", "version", "asked", "or", "deprecated", "by", "default" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L29-L39
761
TryGhost/Ghost
core/server/services/url/utils.js
getBlogUrl
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
javascript
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
[ "function", "getBlogUrl", "(", "secure", ")", "{", "var", "blogUrl", ";", "if", "(", "secure", ")", "{", "blogUrl", "=", "config", ".", "get", "(", "'url'", ")", ".", "replace", "(", "'http://'", ",", "'https://'", ")", ";", "}", "else", "{", "blogUrl", "=", "config", ".", "get", "(", "'url'", ")", ";", "}", "if", "(", "!", "blogUrl", ".", "match", "(", "/", "\\/$", "/", ")", ")", "{", "blogUrl", "+=", "'/'", ";", "}", "return", "blogUrl", ";", "}" ]
Returns the base URL of the blog as set in the config. Secure: If the request is secure, we want to force returning the blog url as https. Imagine Ghost runs with http, but nginx allows SSL connections. @param {boolean} secure @return {string} URL returns the url as defined in config, but always with a trailing `/`
[ "Returns", "the", "base", "URL", "of", "the", "blog", "as", "set", "in", "the", "config", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L51-L65
762
TryGhost/Ghost
core/server/services/url/utils.js
getSubdir
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
javascript
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
[ "function", "getSubdir", "(", ")", "{", "// Parse local path location", "var", "localPath", "=", "url", ".", "parse", "(", "config", ".", "get", "(", "'url'", ")", ")", ".", "path", ",", "subdir", ";", "// Remove trailing slash", "if", "(", "localPath", "!==", "'/'", ")", "{", "localPath", "=", "localPath", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ";", "}", "subdir", "=", "localPath", "===", "'/'", "?", "''", ":", "localPath", ";", "return", "subdir", ";", "}" ]
Returns a subdirectory URL, if defined so in the config. @return {string} URL a subdirectory if configured.
[ "Returns", "a", "subdirectory", "URL", "if", "defined", "so", "in", "the", "config", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L71-L83
763
TryGhost/Ghost
core/server/services/url/utils.js
replacePermalink
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedAtMoment.format('YYYY'); }, month: function () { return publishedAtMoment.format('MM'); }, day: function () { return publishedAtMoment.format('DD'); }, author: function () { return resource.primary_author.slug; }, primary_author: function () { return resource.primary_author ? resource.primary_author.slug : primaryTagFallback; }, primary_tag: function () { return resource.primary_tag ? resource.primary_tag.slug : primaryTagFallback; }, slug: function () { return resource.slug; }, id: function () { return resource.id; } }; // replace tags like :slug or :year with actual values output = output.replace(/(:[a-z_]+)/g, function (match) { if (_.has(permalinkLookUp, match.substr(1))) { return permalinkLookUp[match.substr(1)](); } }); return output; }
javascript
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedAtMoment.format('YYYY'); }, month: function () { return publishedAtMoment.format('MM'); }, day: function () { return publishedAtMoment.format('DD'); }, author: function () { return resource.primary_author.slug; }, primary_author: function () { return resource.primary_author ? resource.primary_author.slug : primaryTagFallback; }, primary_tag: function () { return resource.primary_tag ? resource.primary_tag.slug : primaryTagFallback; }, slug: function () { return resource.slug; }, id: function () { return resource.id; } }; // replace tags like :slug or :year with actual values output = output.replace(/(:[a-z_]+)/g, function (match) { if (_.has(permalinkLookUp, match.substr(1))) { return permalinkLookUp[match.substr(1)](); } }); return output; }
[ "function", "replacePermalink", "(", "permalink", ",", "resource", ")", "{", "let", "output", "=", "permalink", ",", "primaryTagFallback", "=", "'all'", ",", "publishedAtMoment", "=", "moment", ".", "tz", "(", "resource", ".", "published_at", "||", "Date", ".", "now", "(", ")", ",", "settingsCache", ".", "get", "(", "'active_timezone'", ")", ")", ",", "permalinkLookUp", "=", "{", "year", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'YYYY'", ")", ";", "}", ",", "month", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'MM'", ")", ";", "}", ",", "day", ":", "function", "(", ")", "{", "return", "publishedAtMoment", ".", "format", "(", "'DD'", ")", ";", "}", ",", "author", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_author", ".", "slug", ";", "}", ",", "primary_author", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_author", "?", "resource", ".", "primary_author", ".", "slug", ":", "primaryTagFallback", ";", "}", ",", "primary_tag", ":", "function", "(", ")", "{", "return", "resource", ".", "primary_tag", "?", "resource", ".", "primary_tag", ".", "slug", ":", "primaryTagFallback", ";", "}", ",", "slug", ":", "function", "(", ")", "{", "return", "resource", ".", "slug", ";", "}", ",", "id", ":", "function", "(", ")", "{", "return", "resource", ".", "id", ";", "}", "}", ";", "// replace tags like :slug or :year with actual values", "output", "=", "output", ".", "replace", "(", "/", "(:[a-z_]+)", "/", "g", ",", "function", "(", "match", ")", "{", "if", "(", "_", ".", "has", "(", "permalinkLookUp", ",", "match", ".", "substr", "(", "1", ")", ")", ")", "{", "return", "permalinkLookUp", "[", "match", ".", "substr", "(", "1", ")", "]", "(", ")", ";", "}", "}", ")", ";", "return", "output", ";", "}" ]
creates the url path for a post based on blog timezone and permalink pattern
[ "creates", "the", "url", "path", "for", "a", "post", "based", "on", "blog", "timezone", "and", "permalink", "pattern" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L204-L243
764
TryGhost/Ghost
core/server/services/url/utils.js
makeAbsoluteUrls
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { el = htmlContent(el); let attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { const parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // CASE: don't convert internal links if (attributeValue[0] === '#') { return; } if (options.assetsOnly && !attributeValue.match(staticImageUrlPrefixRegex)) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. const baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; }
javascript
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { el = htmlContent(el); let attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { const parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // CASE: don't convert internal links if (attributeValue[0] === '#') { return; } if (options.assetsOnly && !attributeValue.match(staticImageUrlPrefixRegex)) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. const baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; }
[ "function", "makeAbsoluteUrls", "(", "html", ",", "siteUrl", ",", "itemUrl", ",", "options", "=", "{", "assetsOnly", ":", "false", "}", ")", "{", "html", "=", "html", "||", "''", ";", "const", "htmlContent", "=", "cheerio", ".", "load", "(", "html", ",", "{", "decodeEntities", ":", "false", "}", ")", ";", "const", "staticImageUrlPrefixRegex", "=", "new", "RegExp", "(", "STATIC_IMAGE_URL_PREFIX", ")", ";", "// convert relative resource urls to absolute", "[", "'href'", ",", "'src'", "]", ".", "forEach", "(", "function", "forEach", "(", "attributeName", ")", "{", "htmlContent", "(", "'['", "+", "attributeName", "+", "']'", ")", ".", "each", "(", "function", "each", "(", "ix", ",", "el", ")", "{", "el", "=", "htmlContent", "(", "el", ")", ";", "let", "attributeValue", "=", "el", ".", "attr", "(", "attributeName", ")", ";", "// if URL is absolute move on to the next element", "try", "{", "const", "parsed", "=", "url", ".", "parse", "(", "attributeValue", ")", ";", "if", "(", "parsed", ".", "protocol", ")", "{", "return", ";", "}", "// Do not convert protocol relative URLs", "if", "(", "attributeValue", ".", "lastIndexOf", "(", "'//'", ",", "0", ")", "===", "0", ")", "{", "return", ";", "}", "}", "catch", "(", "e", ")", "{", "return", ";", "}", "// CASE: don't convert internal links", "if", "(", "attributeValue", "[", "0", "]", "===", "'#'", ")", "{", "return", ";", "}", "if", "(", "options", ".", "assetsOnly", "&&", "!", "attributeValue", ".", "match", "(", "staticImageUrlPrefixRegex", ")", ")", "{", "return", ";", "}", "// compose an absolute URL", "// if the relative URL begins with a '/' use the blog URL (including sub-directory)", "// as the base URL, otherwise use the post's URL.", "const", "baseUrl", "=", "attributeValue", "[", "0", "]", "===", "'/'", "?", "siteUrl", ":", "itemUrl", ";", "attributeValue", "=", "urlJoin", "(", "baseUrl", ",", "attributeValue", ")", ";", "el", ".", "attr", "(", "attributeName", ",", "attributeValue", ")", ";", "}", ")", ";", "}", ")", ";", "return", "htmlContent", ";", "}" ]
Make absolute URLs @param {string} html @param {string} siteUrl (blog URL) @param {string} itemUrl (URL of current context) @returns {object} htmlContent @description Takes html, blog url and item url and converts relative url into absolute urls. Returns an object. The html string can be accessed by calling `html()` on the variable that takes the result of this function
[ "Make", "absolute", "URLs" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/services/url/utils.js#L395-L442
765
TryGhost/Ghost
core/server/models/base/index.js
initialize
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) { newObj.setId(); } } }); [ 'fetching', 'fetching:collection', 'fetched', 'fetched:collection', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saving', 'saved' ].forEach(function (eventName) { var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1); if (functionName.indexOf(':') !== -1) { functionName = functionName.slice(0, functionName.indexOf(':')) + functionName[functionName.indexOf(':') + 1].toUpperCase() + functionName.slice(functionName.indexOf(':') + 2); functionName = functionName.replace(':', ''); } if (!self[functionName]) { return; } self.on(eventName, self[functionName]); }); // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work. proto.initialize.call(this); }
javascript
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) { newObj.setId(); } } }); [ 'fetching', 'fetching:collection', 'fetched', 'fetched:collection', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saving', 'saved' ].forEach(function (eventName) { var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1); if (functionName.indexOf(':') !== -1) { functionName = functionName.slice(0, functionName.indexOf(':')) + functionName[functionName.indexOf(':') + 1].toUpperCase() + functionName.slice(functionName.indexOf(':') + 2); functionName = functionName.replace(':', ''); } if (!self[functionName]) { return; } self.on(eventName, self[functionName]); }); // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work. proto.initialize.call(this); }
[ "function", "initialize", "(", ")", "{", "var", "self", "=", "this", ";", "// NOTE: triggered before `creating`/`updating`", "this", ".", "on", "(", "'saving'", ",", "function", "onSaving", "(", "newObj", ",", "attrs", ",", "options", ")", "{", "if", "(", "options", ".", "method", "===", "'insert'", ")", "{", "// id = 0 is still a valid value for external usage", "if", "(", "_", ".", "isUndefined", "(", "newObj", ".", "id", ")", "||", "_", ".", "isNull", "(", "newObj", ".", "id", ")", ")", "{", "newObj", ".", "setId", "(", ")", ";", "}", "}", "}", ")", ";", "[", "'fetching'", ",", "'fetching:collection'", ",", "'fetched'", ",", "'fetched:collection'", ",", "'creating'", ",", "'created'", ",", "'updating'", ",", "'updated'", ",", "'destroying'", ",", "'destroyed'", ",", "'saving'", ",", "'saved'", "]", ".", "forEach", "(", "function", "(", "eventName", ")", "{", "var", "functionName", "=", "'on'", "+", "eventName", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "eventName", ".", "slice", "(", "1", ")", ";", "if", "(", "functionName", ".", "indexOf", "(", "':'", ")", "!==", "-", "1", ")", "{", "functionName", "=", "functionName", ".", "slice", "(", "0", ",", "functionName", ".", "indexOf", "(", "':'", ")", ")", "+", "functionName", "[", "functionName", ".", "indexOf", "(", "':'", ")", "+", "1", "]", ".", "toUpperCase", "(", ")", "+", "functionName", ".", "slice", "(", "functionName", ".", "indexOf", "(", "':'", ")", "+", "2", ")", ";", "functionName", "=", "functionName", ".", "replace", "(", "':'", ",", "''", ")", ";", "}", "if", "(", "!", "self", "[", "functionName", "]", ")", "{", "return", ";", "}", "self", ".", "on", "(", "eventName", ",", "self", "[", "functionName", "]", ")", ";", "}", ")", ";", "// @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work.", "proto", ".", "initialize", ".", "call", "(", "this", ")", ";", "}" ]
Bookshelf `initialize` - declare a constructor-like method for model creation
[ "Bookshelf", "initialize", "-", "declare", "a", "constructor", "-", "like", "method", "for", "model", "creation" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L223-L268
766
TryGhost/Ghost
core/server/models/base/index.js
onUpdating
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('updated_by', String(this.contextUser(options))); } } if (options && options.context && !options.context.internal && !options.importing) { if (schema.tables[this.tableName].hasOwnProperty('created_at')) { if (model.hasDateChanged('created_at', {beforeWrite: true})) { model.set('created_at', this.previous('created_at')); } } if (schema.tables[this.tableName].hasOwnProperty('created_by')) { if (model.hasChanged('created_by')) { model.set('created_by', String(this.previous('created_by'))); } } } // CASE: do not allow setting only the `updated_at` field, exception: importing if (schema.tables[this.tableName].hasOwnProperty('updated_at') && !options.importing) { if (options.migrating) { model.set('updated_at', model.previous('updated_at')); } else if (Object.keys(model.changed).length === 1 && model.changed.updated_at) { model.set('updated_at', model.previous('updated_at')); delete model.changed.updated_at; } } model._changed = _.cloneDeep(model.changed); return Promise.resolve(this.onValidate(model, attr, options)); }
javascript
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('updated_by', String(this.contextUser(options))); } } if (options && options.context && !options.context.internal && !options.importing) { if (schema.tables[this.tableName].hasOwnProperty('created_at')) { if (model.hasDateChanged('created_at', {beforeWrite: true})) { model.set('created_at', this.previous('created_at')); } } if (schema.tables[this.tableName].hasOwnProperty('created_by')) { if (model.hasChanged('created_by')) { model.set('created_by', String(this.previous('created_by'))); } } } // CASE: do not allow setting only the `updated_at` field, exception: importing if (schema.tables[this.tableName].hasOwnProperty('updated_at') && !options.importing) { if (options.migrating) { model.set('updated_at', model.previous('updated_at')); } else if (Object.keys(model.changed).length === 1 && model.changed.updated_at) { model.set('updated_at', model.previous('updated_at')); delete model.changed.updated_at; } } model._changed = _.cloneDeep(model.changed); return Promise.resolve(this.onValidate(model, attr, options)); }
[ "function", "onUpdating", "(", "model", ",", "attr", ",", "options", ")", "{", "if", "(", "this", ".", "relationships", ")", "{", "model", ".", "changed", "=", "_", ".", "omit", "(", "model", ".", "changed", ",", "this", ".", "relationships", ")", ";", "}", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'updated_by'", ")", ")", "{", "if", "(", "!", "options", ".", "importing", "&&", "!", "options", ".", "migrating", ")", "{", "this", ".", "set", "(", "'updated_by'", ",", "String", "(", "this", ".", "contextUser", "(", "options", ")", ")", ")", ";", "}", "}", "if", "(", "options", "&&", "options", ".", "context", "&&", "!", "options", ".", "context", ".", "internal", "&&", "!", "options", ".", "importing", ")", "{", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'created_at'", ")", ")", "{", "if", "(", "model", ".", "hasDateChanged", "(", "'created_at'", ",", "{", "beforeWrite", ":", "true", "}", ")", ")", "{", "model", ".", "set", "(", "'created_at'", ",", "this", ".", "previous", "(", "'created_at'", ")", ")", ";", "}", "}", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'created_by'", ")", ")", "{", "if", "(", "model", ".", "hasChanged", "(", "'created_by'", ")", ")", "{", "model", ".", "set", "(", "'created_by'", ",", "String", "(", "this", ".", "previous", "(", "'created_by'", ")", ")", ")", ";", "}", "}", "}", "// CASE: do not allow setting only the `updated_at` field, exception: importing", "if", "(", "schema", ".", "tables", "[", "this", ".", "tableName", "]", ".", "hasOwnProperty", "(", "'updated_at'", ")", "&&", "!", "options", ".", "importing", ")", "{", "if", "(", "options", ".", "migrating", ")", "{", "model", ".", "set", "(", "'updated_at'", ",", "model", ".", "previous", "(", "'updated_at'", ")", ")", ";", "}", "else", "if", "(", "Object", ".", "keys", "(", "model", ".", "changed", ")", ".", "length", "===", "1", "&&", "model", ".", "changed", ".", "updated_at", ")", "{", "model", ".", "set", "(", "'updated_at'", ",", "model", ".", "previous", "(", "'updated_at'", ")", ")", ";", "delete", "model", ".", "changed", ".", "updated_at", ";", "}", "}", "model", ".", "_changed", "=", "_", ".", "cloneDeep", "(", "model", ".", "changed", ")", ";", "return", "Promise", ".", "resolve", "(", "this", ".", "onValidate", "(", "model", ",", "attr", ",", "options", ")", ")", ";", "}" ]
Changing resources implies setting these properties on the server side - set `updated_by` based on the context - ensure `created_at` never changes - ensure `created_by` never changes - the bookshelf `timestamps` plugin sets `updated_at` automatically Exceptions: - importing data - internal context - if no context @deprecated: x_by fields (https://github.com/TryGhost/Ghost/issues/10286)
[ "Changing", "resources", "implies", "setting", "these", "properties", "on", "the", "server", "side", "-", "set", "updated_by", "based", "on", "the", "context", "-", "ensure", "created_at", "never", "changes", "-", "ensure", "created_by", "never", "changes", "-", "the", "bookshelf", "timestamps", "plugin", "sets", "updated_at", "automatically" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L376-L414
767
TryGhost/Ghost
core/server/models/base/index.js
fixDates
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss'); } }); return attrs; }
javascript
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss'); } }); return attrs; }
[ "function", "fixDates", "(", "attrs", ")", "{", "var", "self", "=", "this", ";", "_", ".", "each", "(", "attrs", ",", "function", "each", "(", "value", ",", "key", ")", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", ".", "hasOwnProperty", "(", "key", ")", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", "[", "key", "]", ".", "type", "===", "'dateTime'", ")", "{", "attrs", "[", "key", "]", "=", "moment", "(", "value", ")", ".", "format", "(", "'YYYY-MM-DD HH:mm:ss'", ")", ";", "}", "}", ")", ";", "return", "attrs", ";", "}" ]
before we insert dates into the database, we have to normalize date format is now in each db the same
[ "before", "we", "insert", "dates", "into", "the", "database", "we", "have", "to", "normalize", "date", "format", "is", "now", "in", "each", "db", "the", "same" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L443-L455
768
TryGhost/Ghost
core/server/models/base/index.js
fixBools
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); return attrs; }
javascript
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); return attrs; }
[ "function", "fixBools", "(", "attrs", ")", "{", "var", "self", "=", "this", ";", "_", ".", "each", "(", "attrs", ",", "function", "each", "(", "value", ",", "key", ")", "{", "if", "(", "schema", ".", "tables", "[", "self", ".", "tableName", "]", ".", "hasOwnProperty", "(", "key", ")", "&&", "schema", ".", "tables", "[", "self", ".", "tableName", "]", "[", "key", "]", ".", "type", "===", "'bool'", ")", "{", "attrs", "[", "key", "]", "=", "value", "?", "true", ":", "false", ";", "}", "}", ")", ";", "return", "attrs", ";", "}" ]
Convert integers to real booleans
[ "Convert", "integers", "to", "real", "booleans" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L488-L498
769
TryGhost/Ghost
core/server/models/base/index.js
contextUser
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** * @NOTE: * * This is a dirty hotfix for v0.1 only. * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286). * * We return the owner ID '1' in case an integration updates or creates * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations. * API v2 will introduce a new feature to solve inserting/updating resources * from users or integrations. API v2 won't expose `x_by` columns anymore. * * --- * * Why using ID '1'? WAIT. What??????? * * See https://github.com/TryGhost/Ghost/issues/9299. * * We currently don't read the correct owner ID from the database and assume it's '1'. * This is a leftover from switching from auto increment ID's to Object ID's. * But this takes too long to refactor out now. If an internal update happens, we also * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else, * if you transfer ownership. */ return ghostBookshelf.Model.internalUser; } else if (options.context.internal) { return ghostBookshelf.Model.internalUser; } else if (this.get('id')) { return this.get('id'); } else if (options.context.external) { return ghostBookshelf.Model.externalUser; } else { throw new common.errors.NotFoundError({ message: common.i18n.t('errors.models.base.index.missingContext'), level: 'critical' }); } }
javascript
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** * @NOTE: * * This is a dirty hotfix for v0.1 only. * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286). * * We return the owner ID '1' in case an integration updates or creates * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations. * API v2 will introduce a new feature to solve inserting/updating resources * from users or integrations. API v2 won't expose `x_by` columns anymore. * * --- * * Why using ID '1'? WAIT. What??????? * * See https://github.com/TryGhost/Ghost/issues/9299. * * We currently don't read the correct owner ID from the database and assume it's '1'. * This is a leftover from switching from auto increment ID's to Object ID's. * But this takes too long to refactor out now. If an internal update happens, we also * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else, * if you transfer ownership. */ return ghostBookshelf.Model.internalUser; } else if (options.context.internal) { return ghostBookshelf.Model.internalUser; } else if (this.get('id')) { return this.get('id'); } else if (options.context.external) { return ghostBookshelf.Model.externalUser; } else { throw new common.errors.NotFoundError({ message: common.i18n.t('errors.models.base.index.missingContext'), level: 'critical' }); } }
[ "function", "contextUser", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "context", "=", "options", ".", "context", "||", "{", "}", ";", "if", "(", "options", ".", "context", ".", "user", "||", "ghostBookshelf", ".", "Model", ".", "isExternalUser", "(", "options", ".", "context", ".", "user", ")", ")", "{", "return", "options", ".", "context", ".", "user", ";", "}", "else", "if", "(", "options", ".", "context", ".", "integration", ")", "{", "/**\n * @NOTE:\n *\n * This is a dirty hotfix for v0.1 only.\n * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286).\n *\n * We return the owner ID '1' in case an integration updates or creates\n * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations.\n * API v2 will introduce a new feature to solve inserting/updating resources\n * from users or integrations. API v2 won't expose `x_by` columns anymore.\n *\n * ---\n *\n * Why using ID '1'? WAIT. What???????\n *\n * See https://github.com/TryGhost/Ghost/issues/9299.\n *\n * We currently don't read the correct owner ID from the database and assume it's '1'.\n * This is a leftover from switching from auto increment ID's to Object ID's.\n * But this takes too long to refactor out now. If an internal update happens, we also\n * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else,\n * if you transfer ownership.\n */", "return", "ghostBookshelf", ".", "Model", ".", "internalUser", ";", "}", "else", "if", "(", "options", ".", "context", ".", "internal", ")", "{", "return", "ghostBookshelf", ".", "Model", ".", "internalUser", ";", "}", "else", "if", "(", "this", ".", "get", "(", "'id'", ")", ")", "{", "return", "this", ".", "get", "(", "'id'", ")", ";", "}", "else", "if", "(", "options", ".", "context", ".", "external", ")", "{", "return", "ghostBookshelf", ".", "Model", ".", "externalUser", ";", "}", "else", "{", "throw", "new", "common", ".", "errors", ".", "NotFoundError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.index.missingContext'", ")", ",", "level", ":", "'critical'", "}", ")", ";", "}", "}" ]
Get the user from the options object
[ "Get", "the", "user", "from", "the", "options", "object" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L533-L576
770
TryGhost/Ghost
core/server/models/base/index.js
toJSON
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attributes = this._previousAttributes; if (this.relationships) { this.relationships.forEach((relation) => { if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) { clonedModel.related(relation).models = this._previousRelations[relation].models; } }); } return proto.toJSON.call(clonedModel, options); } return proto.toJSON.call(this, options); }
javascript
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attributes = this._previousAttributes; if (this.relationships) { this.relationships.forEach((relation) => { if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) { clonedModel.related(relation).models = this._previousRelations[relation].models; } }); } return proto.toJSON.call(clonedModel, options); } return proto.toJSON.call(this, options); }
[ "function", "toJSON", "(", "unfilteredOptions", ")", "{", "const", "options", "=", "ghostBookshelf", ".", "Model", ".", "filterOptions", "(", "unfilteredOptions", ",", "'toJSON'", ")", ";", "options", ".", "omitPivot", "=", "true", ";", "// CASE: get JSON of previous attrs", "if", "(", "options", ".", "previous", ")", "{", "const", "clonedModel", "=", "_", ".", "cloneDeep", "(", "this", ")", ";", "clonedModel", ".", "attributes", "=", "this", ".", "_previousAttributes", ";", "if", "(", "this", ".", "relationships", ")", "{", "this", ".", "relationships", ".", "forEach", "(", "(", "relation", ")", "=>", "{", "if", "(", "this", ".", "_previousRelations", "&&", "this", ".", "_previousRelations", ".", "hasOwnProperty", "(", "relation", ")", ")", "{", "clonedModel", ".", "related", "(", "relation", ")", ".", "models", "=", "this", ".", "_previousRelations", "[", "relation", "]", ".", "models", ";", "}", "}", ")", ";", "}", "return", "proto", ".", "toJSON", ".", "call", "(", "clonedModel", ",", "options", ")", ";", "}", "return", "proto", ".", "toJSON", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
`shallow` - won't return relations `omitPivot` - won't return pivot fields `toJSON` calls `serialize`. @param unfilteredOptions @returns {*}
[ "shallow", "-", "won", "t", "return", "relations", "omitPivot", "-", "won", "t", "return", "pivot", "fields" ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L597-L618
771
TryGhost/Ghost
core/server/models/base/index.js
permittedOptions
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case 'destroy': return baseOptions.concat(extraOptions, ['id', 'destroyBy', 'require']); case 'edit': return baseOptions.concat(extraOptions, ['id', 'require']); case 'findOne': return baseOptions.concat(extraOptions, ['columns', 'require']); case 'findAll': return baseOptions.concat(extraOptions, ['columns']); case 'findPage': return baseOptions.concat(extraOptions, ['filter', 'order', 'page', 'limit', 'columns']); default: return baseOptions.concat(extraOptions); } }
javascript
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case 'destroy': return baseOptions.concat(extraOptions, ['id', 'destroyBy', 'require']); case 'edit': return baseOptions.concat(extraOptions, ['id', 'require']); case 'findOne': return baseOptions.concat(extraOptions, ['columns', 'require']); case 'findAll': return baseOptions.concat(extraOptions, ['columns']); case 'findPage': return baseOptions.concat(extraOptions, ['filter', 'order', 'page', 'limit', 'columns']); default: return baseOptions.concat(extraOptions); } }
[ "function", "permittedOptions", "(", "methodName", ")", "{", "const", "baseOptions", "=", "[", "'context'", ",", "'withRelated'", "]", ";", "const", "extraOptions", "=", "[", "'transacting'", ",", "'importing'", ",", "'forUpdate'", ",", "'migrating'", "]", ";", "switch", "(", "methodName", ")", "{", "case", "'toJSON'", ":", "return", "baseOptions", ".", "concat", "(", "'shallow'", ",", "'columns'", ",", "'previous'", ")", ";", "case", "'destroy'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'id'", ",", "'destroyBy'", ",", "'require'", "]", ")", ";", "case", "'edit'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'id'", ",", "'require'", "]", ")", ";", "case", "'findOne'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'columns'", ",", "'require'", "]", ")", ";", "case", "'findAll'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'columns'", "]", ")", ";", "case", "'findPage'", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ",", "[", "'filter'", ",", "'order'", ",", "'page'", ",", "'limit'", ",", "'columns'", "]", ")", ";", "default", ":", "return", "baseOptions", ".", "concat", "(", "extraOptions", ")", ";", "}", "}" ]
Returns an array of keys permitted in every method's `options` hash. Can be overridden and added to by a model's `permittedOptions` method. importing: is used when import a JSON file or when migrating the database @return {Object} Keys allowed in the `options` hash of every model's method.
[ "Returns", "an", "array", "of", "keys", "permitted", "in", "every", "method", "s", "options", "hash", ".", "Can", "be", "overridden", "and", "added", "to", "by", "a", "model", "s", "permittedOptions", "method", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L677-L697
772
TryGhost/Ghost
core/server/models/base/index.js
sanitizeData
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: property}), code: 'DATE_INVALID' }); } data[property] = moment(value).toDate(); } if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) { _.each(data[property], (relation, indexInArr) => { _.each(relation, (value, relationProperty) => { if (value !== null && schema.tables[this.prototype.relationshipBelongsTo[property]].hasOwnProperty(relationProperty) && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: relationProperty}), code: 'DATE_INVALID' }); } data[property][indexInArr][relationProperty] = moment(value).toDate(); } }); }); } }); return data; }
javascript
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: property}), code: 'DATE_INVALID' }); } data[property] = moment(value).toDate(); } if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) { _.each(data[property], (relation, indexInArr) => { _.each(relation, (value, relationProperty) => { if (value !== null && schema.tables[this.prototype.relationshipBelongsTo[property]].hasOwnProperty(relationProperty) && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: relationProperty}), code: 'DATE_INVALID' }); } data[property][indexInArr][relationProperty] = moment(value).toDate(); } }); }); } }); return data; }
[ "function", "sanitizeData", "(", "data", ")", "{", "var", "tableName", "=", "_", ".", "result", "(", "this", ".", "prototype", ",", "'tableName'", ")", ",", "date", ";", "_", ".", "each", "(", "data", ",", "(", "value", ",", "property", ")", "=>", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "tableName", "]", ".", "hasOwnProperty", "(", "property", ")", "&&", "schema", ".", "tables", "[", "tableName", "]", "[", "property", "]", ".", "type", "===", "'dateTime'", "&&", "typeof", "value", "===", "'string'", ")", "{", "date", "=", "new", "Date", "(", "value", ")", ";", "// CASE: client sends `0000-00-00 00:00:00`", "if", "(", "isNaN", "(", "date", ")", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.invalidDate'", ",", "{", "key", ":", "property", "}", ")", ",", "code", ":", "'DATE_INVALID'", "}", ")", ";", "}", "data", "[", "property", "]", "=", "moment", "(", "value", ")", ".", "toDate", "(", ")", ";", "}", "if", "(", "this", ".", "prototype", ".", "relationships", "&&", "this", ".", "prototype", ".", "relationships", ".", "indexOf", "(", "property", ")", "!==", "-", "1", ")", "{", "_", ".", "each", "(", "data", "[", "property", "]", ",", "(", "relation", ",", "indexInArr", ")", "=>", "{", "_", ".", "each", "(", "relation", ",", "(", "value", ",", "relationProperty", ")", "=>", "{", "if", "(", "value", "!==", "null", "&&", "schema", ".", "tables", "[", "this", ".", "prototype", ".", "relationshipBelongsTo", "[", "property", "]", "]", ".", "hasOwnProperty", "(", "relationProperty", ")", "&&", "schema", ".", "tables", "[", "this", ".", "prototype", ".", "relationshipBelongsTo", "[", "property", "]", "]", "[", "relationProperty", "]", ".", "type", "===", "'dateTime'", "&&", "typeof", "value", "===", "'string'", ")", "{", "date", "=", "new", "Date", "(", "value", ")", ";", "// CASE: client sends `0000-00-00 00:00:00`", "if", "(", "isNaN", "(", "date", ")", ")", "{", "throw", "new", "common", ".", "errors", ".", "ValidationError", "(", "{", "message", ":", "common", ".", "i18n", ".", "t", "(", "'errors.models.base.invalidDate'", ",", "{", "key", ":", "relationProperty", "}", ")", ",", "code", ":", "'DATE_INVALID'", "}", ")", ";", "}", "data", "[", "property", "]", "[", "indexInArr", "]", "[", "relationProperty", "]", "=", "moment", "(", "value", ")", ".", "toDate", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "data", ";", "}" ]
`sanitizeData` ensures that client data is in the correct format for further operations. Dates: - client dates are sent as ISO 8601 format (moment(..).format()) - server dates are in JS Date format >> when bookshelf fetches data from the database, all dates are in JS Dates >> see `parse` - Bookshelf updates the model with the new client data via the `set` function - Bookshelf uses a simple `isEqual` function from lodash to detect real changes - .previous(attr) and .get(attr) returns false obviously - internally we use our `hasDateChanged` if we have to compare previous dates - but Bookshelf is not in our control for this case @IMPORTANT Before the new client data get's inserted again, the dates get's re-transformed into proper strings, see `format`. @IMPORTANT Sanitize relations.
[ "sanitizeData", "ensures", "that", "client", "data", "is", "in", "the", "correct", "format", "for", "further", "operations", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L735-L783
773
TryGhost/Ghost
core/server/models/base/index.js
filterByVisibility
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, function (items, item, key) { if (!item.visibility && !explicit || _.includes(visibility, item.visibility)) { var newItem = fn ? fn(item) : item; if (_.isArray(items)) { memo.push(newItem); } else { memo[key] = newItem; } } return memo; }, memo); }
javascript
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, function (items, item, key) { if (!item.visibility && !explicit || _.includes(visibility, item.visibility)) { var newItem = fn ? fn(item) : item; if (_.isArray(items)) { memo.push(newItem); } else { memo[key] = newItem; } } return memo; }, memo); }
[ "function", "filterByVisibility", "(", "items", ",", "visibility", ",", "explicit", ",", "fn", ")", "{", "var", "memo", "=", "_", ".", "isArray", "(", "items", ")", "?", "[", "]", ":", "{", "}", ";", "if", "(", "_", ".", "includes", "(", "visibility", ",", "'all'", ")", ")", "{", "return", "fn", "?", "_", ".", "map", "(", "items", ",", "fn", ")", ":", "items", ";", "}", "// We don't want to change the structure of what is returned", "return", "_", ".", "reduce", "(", "items", ",", "function", "(", "items", ",", "item", ",", "key", ")", "{", "if", "(", "!", "item", ".", "visibility", "&&", "!", "explicit", "||", "_", ".", "includes", "(", "visibility", ",", "item", ".", "visibility", ")", ")", "{", "var", "newItem", "=", "fn", "?", "fn", "(", "item", ")", ":", "item", ";", "if", "(", "_", ".", "isArray", "(", "items", ")", ")", "{", "memo", ".", "push", "(", "newItem", ")", ";", "}", "else", "{", "memo", "[", "key", "]", "=", "newItem", ";", "}", "}", "return", "memo", ";", "}", ",", "memo", ")", ";", "}" ]
All models which have a visibility property, can use this static helper function. Filter models by visibility. @param {Array|Object} items @param {Array} visibility @param {Boolean} [explicit] @param {Function} [fn] @returns {Array|Object} filtered items
[ "All", "models", "which", "have", "a", "visibility", "property", "can", "use", "this", "static", "helper", "function", ".", "Filter", "models", "by", "visibility", "." ]
bb7bb55cf3e60af99ebbc56099928827b58461bc
https://github.com/TryGhost/Ghost/blob/bb7bb55cf3e60af99ebbc56099928827b58461bc/core/server/models/base/index.js#L1168-L1187
774
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
handleMessage
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type, id: id, payload: true}); }); break; case 'query-index': self.postMessage({type: type, id: id, payload: {query: payload, results: queryIndex(payload)}}); break; default: self.postMessage({type: type, id: id, payload: {error: 'invalid message type'}}) } }
javascript
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type, id: id, payload: true}); }); break; case 'query-index': self.postMessage({type: type, id: id, payload: {query: payload, results: queryIndex(payload)}}); break; default: self.postMessage({type: type, id: id, payload: {error: 'invalid message type'}}) } }
[ "function", "handleMessage", "(", "message", ")", "{", "var", "type", "=", "message", ".", "data", ".", "type", ";", "var", "id", "=", "message", ".", "data", ".", "id", ";", "var", "payload", "=", "message", ".", "data", ".", "payload", ";", "switch", "(", "type", ")", "{", "case", "'load-index'", ":", "makeRequest", "(", "SEARCH_TERMS_URL", ",", "function", "(", "searchInfo", ")", "{", "index", "=", "createIndex", "(", "loadIndex", "(", "searchInfo", ")", ")", ";", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "true", "}", ")", ";", "}", ")", ";", "break", ";", "case", "'query-index'", ":", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "{", "query", ":", "payload", ",", "results", ":", "queryIndex", "(", "payload", ")", "}", "}", ")", ";", "break", ";", "default", ":", "self", ".", "postMessage", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "payload", ":", "{", "error", ":", "'invalid message type'", "}", "}", ")", "}", "}" ]
The worker receives a message to load the index and to query the index
[ "The", "worker", "receives", "a", "message", "to", "load", "the", "index", "and", "to", "query", "the", "index" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L42-L59
775
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
makeRequest
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
javascript
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
[ "function", "makeRequest", "(", "url", ",", "callback", ")", "{", "// The JSON file that is loaded should be an array of PageInfo:", "var", "searchDataRequest", "=", "new", "XMLHttpRequest", "(", ")", ";", "searchDataRequest", ".", "onload", "=", "function", "(", ")", "{", "callback", "(", "JSON", ".", "parse", "(", "this", ".", "responseText", ")", ")", ";", "}", ";", "searchDataRequest", ".", "open", "(", "'GET'", ",", "url", ")", ";", "searchDataRequest", ".", "send", "(", ")", ";", "}" ]
Use XHR to make a request to the server
[ "Use", "XHR", "to", "make", "a", "request", "to", "the", "server" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L62-L71
776
ReactiveX/rxjs
docs_app/src/app/search/search-worker.js
loadIndex
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = page; }); }; }
javascript
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = page; }); }; }
[ "function", "loadIndex", "(", "searchInfo", "/*: SearchInfo */", ")", "{", "return", "function", "(", "index", ")", "{", "// Store the pages data to be used in mapping query results back to pages", "// Add search terms from each page to the search index", "searchInfo", ".", "forEach", "(", "function", "(", "page", "/*: PageInfo */", ")", "{", "index", ".", "add", "(", "page", ")", ";", "pages", "[", "page", ".", "path", "]", "=", "page", ";", "}", ")", ";", "}", ";", "}" ]
Create the search index from the searchInfo which contains the information about each page to be indexed
[ "Create", "the", "search", "index", "from", "the", "searchInfo", "which", "contains", "the", "information", "about", "each", "page", "to", "be", "indexed" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/docs_app/src/app/search/search-worker.js#L75-L84
777
ReactiveX/rxjs
.make-helpers.js
createImportTargets
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.resolve(__dirname); module.exports = function() { return ${JSON.stringify(importMap, null, 4)}; } ` fs.outputFileSync(targetDirectory + 'path-mapping.js', outputData); }
javascript
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.resolve(__dirname); module.exports = function() { return ${JSON.stringify(importMap, null, 4)}; } ` fs.outputFileSync(targetDirectory + 'path-mapping.js', outputData); }
[ "function", "createImportTargets", "(", "importTargets", ",", "targetName", ",", "targetDirectory", ")", "{", "const", "importMap", "=", "{", "}", ";", "for", "(", "const", "x", "in", "importTargets", ")", "{", "importMap", "[", "'rxjs/'", "+", "x", "]", "=", "(", "'rxjs-compat/'", "+", "targetName", "+", "importTargets", "[", "x", "]", ")", ".", "replace", "(", "/", "\\.js$", "/", ",", "''", ")", ";", "}", "const", "outputData", "=", "`", "${", "JSON", ".", "stringify", "(", "importMap", ",", "null", ",", "4", ")", "}", "`", "fs", ".", "outputFileSync", "(", "targetDirectory", "+", "'path-mapping.js'", ",", "outputData", ")", ";", "}" ]
Create a file that exports the importTargets object
[ "Create", "a", "file", "that", "exports", "the", "importTargets", "object" ]
1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f
https://github.com/ReactiveX/rxjs/blob/1037a1d1e6b80c7218e7ffdf8c0d96a612653a4f/.make-helpers.js#L40-L59
778
jhipster/generator-jhipster
generators/aws-containers/lib/utils.js
spinner
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) .catch(err => { spinner.stop(); reject(err); }); }); }
javascript
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) .catch(err => { spinner.stop(); reject(err); }); }); }
[ "function", "spinner", "(", "promise", ",", "text", "=", "'loading'", ",", "spinnerIcon", "=", "'monkey'", ")", "{", "const", "spinner", "=", "ora", "(", "{", "spinner", ":", "spinnerIcon", ",", "text", "}", ")", ".", "start", "(", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "promise", ".", "then", "(", "resolved", "=>", "{", "spinner", ".", "stop", "(", ")", ";", "resolve", "(", "resolved", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "spinner", ".", "stop", "(", ")", ";", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
eslint-disable-line Wraps the promise in a CLI spinner @param promise @param text @param spinnerIcon
[ "eslint", "-", "disable", "-", "line", "Wraps", "the", "promise", "in", "a", "CLI", "spinner" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/utils.js#L28-L41
779
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askTypeOfApplication
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; return this.prompt(prompts).then(props => { const applicationType = props.applicationType; this.deploymentApplicationType = props.applicationType; if (applicationType) { this.log(applicationType); done(); } else { this.abort = true; done(); } }); }
javascript
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; return this.prompt(prompts).then(props => { const applicationType = props.applicationType; this.deploymentApplicationType = props.applicationType; if (applicationType) { this.log(applicationType); done(); } else { this.abort = true; done(); } }); }
[ "function", "askTypeOfApplication", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'applicationType'", ",", "message", ":", "'Which *type* of application would you like to deploy?'", ",", "choices", ":", "[", "{", "value", ":", "'monolith'", ",", "name", ":", "'Monolithic application'", "}", ",", "{", "value", ":", "'microservice'", ",", "name", ":", "'Microservice application'", "}", "]", ",", "default", ":", "'monolith'", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "applicationType", "=", "props", ".", "applicationType", ";", "this", ".", "deploymentApplicationType", "=", "props", ".", "applicationType", ";", "if", "(", "applicationType", ")", "{", "this", ".", "log", "(", "applicationType", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user what type of application is to be created?
[ "Ask", "user", "what", "type", "of", "application", "is", "to", "be", "created?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L116-L150
780
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askRegion
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region) : this.awsFacts.defaultRegion } ]; return this.prompt(prompts).then(props => { const region = props.region; if (region) { this.aws.region = region; done(); } else { this.abort = true; done(); } }); }
javascript
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region) : this.awsFacts.defaultRegion } ]; return this.prompt(prompts).then(props => { const region = props.region; if (region) { this.aws.region = region; done(); } else { this.abort = true; done(); } }); }
[ "function", "askRegion", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'region'", ",", "message", ":", "'Which region?'", ",", "choices", ":", "regionList", ",", "default", ":", "this", ".", "aws", ".", "region", "?", "_", ".", "indexOf", "(", "regionList", ",", "this", ".", "aws", ".", "region", ")", ":", "this", ".", "awsFacts", ".", "defaultRegion", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "region", "=", "props", ".", "region", ";", "if", "(", "region", ")", "{", "this", ".", "aws", ".", "region", "=", "region", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user what type of Region is to be created?
[ "Ask", "user", "what", "type", "of", "Region", "is", "to", "be", "created?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L155-L178
781
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askCloudFormation
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFormationName || this.baseName, validate: input => { if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) { return 'Stack name must contain letters, digits, or hyphens '; } return true; } } ]; return this.prompt(prompts).then(props => { const cloudFormationName = props.cloudFormationName; if (cloudFormationName) { this.aws.cloudFormationName = cloudFormationName; while (this.aws.cloudFormationName.includes('_')) { this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', ''); } this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`); done(); } else { this.abort = true; done(); } }); }
javascript
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFormationName || this.baseName, validate: input => { if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) { return 'Stack name must contain letters, digits, or hyphens '; } return true; } } ]; return this.prompt(prompts).then(props => { const cloudFormationName = props.cloudFormationName; if (cloudFormationName) { this.aws.cloudFormationName = cloudFormationName; while (this.aws.cloudFormationName.includes('_')) { this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', ''); } this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`); done(); } else { this.abort = true; done(); } }); }
[ "function", "askCloudFormation", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'input'", ",", "name", ":", "'cloudFormationName'", ",", "message", ":", "\"Please enter your stack's name. (must be unique within a region)\"", ",", "default", ":", "this", ".", "aws", ".", "cloudFormationName", "||", "this", ".", "baseName", ",", "validate", ":", "input", "=>", "{", "if", "(", "_", ".", "isEmpty", "(", "input", ")", "||", "!", "input", ".", "match", "(", "CLOUDFORMATION_STACK_NAME", ")", ")", "{", "return", "'Stack name must contain letters, digits, or hyphens '", ";", "}", "return", "true", ";", "}", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "cloudFormationName", "=", "props", ".", "cloudFormationName", ";", "if", "(", "cloudFormationName", ")", "{", "this", ".", "aws", ".", "cloudFormationName", "=", "cloudFormationName", ";", "while", "(", "this", ".", "aws", ".", "cloudFormationName", ".", "includes", "(", "'_'", ")", ")", "{", "this", ".", "aws", ".", "cloudFormationName", "=", "_", ".", "replace", "(", "this", ".", "aws", ".", "cloudFormationName", ",", "'_'", ",", "''", ")", ";", "}", "this", ".", "log", "(", "`", "${", "this", ".", "aws", ".", "cloudFormationName", "}", "`", ")", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user for CloudFormation name.
[ "Ask", "user", "for", "CloudFormation", "name", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L183-L215
782
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askPerformances
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptPerformance.call(this, config, awsConfig).then(performance => { awsConfig.performance = performance; awsConfig.fargate = { ...awsConfig.fargate, ...PERF_TO_CONFIG[performance].fargate }; awsConfig.database = { ...awsConfig.database, ...PERF_TO_CONFIG[performance].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptPerformance.call(this, config, awsConfig).then(performance => { awsConfig.performance = performance; awsConfig.fargate = { ...awsConfig.fargate, ...PERF_TO_CONFIG[performance].fargate }; awsConfig.database = { ...awsConfig.database, ...PERF_TO_CONFIG[performance].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
[ "function", "askPerformances", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "chainPromises", "=", "index", "=>", "{", "if", "(", "index", "===", "this", ".", "appConfigs", ".", "length", ")", "{", "done", "(", ")", ";", "return", "null", ";", "}", "const", "config", "=", "this", ".", "appConfigs", "[", "index", "]", ";", "const", "awsConfig", "=", "this", ".", "aws", ".", "apps", ".", "find", "(", "a", "=>", "a", ".", "baseName", "===", "config", ".", "baseName", ")", "||", "{", "baseName", ":", "config", ".", "baseName", "}", ";", "return", "promptPerformance", ".", "call", "(", "this", ",", "config", ",", "awsConfig", ")", ".", "then", "(", "performance", "=>", "{", "awsConfig", ".", "performance", "=", "performance", ";", "awsConfig", ".", "fargate", "=", "{", "...", "awsConfig", ".", "fargate", ",", "...", "PERF_TO_CONFIG", "[", "performance", "]", ".", "fargate", "}", ";", "awsConfig", ".", "database", "=", "{", "...", "awsConfig", ".", "database", ",", "...", "PERF_TO_CONFIG", "[", "performance", "]", ".", "database", "}", ";", "_", ".", "remove", "(", "this", ".", "aws", ".", "apps", ",", "a", "=>", "_", ".", "isEqual", "(", "a", ",", "awsConfig", ")", ")", ";", "this", ".", "aws", ".", "apps", ".", "push", "(", "awsConfig", ")", ";", "return", "chainPromises", "(", "index", "+", "1", ")", ";", "}", ")", ";", "}", ";", "return", "chainPromises", "(", "0", ")", ";", "}" ]
As user to select AWS performance.
[ "As", "user", "to", "select", "AWS", "performance", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L220-L243
783
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askScaling
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptScaling.call(this, config, awsConfig).then(scaling => { awsConfig.scaling = scaling; awsConfig.fargate = { ...awsConfig.fargate, ...SCALING_TO_CONFIG[scaling].fargate }; awsConfig.database = { ...awsConfig.database, ...SCALING_TO_CONFIG[scaling].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptScaling.call(this, config, awsConfig).then(scaling => { awsConfig.scaling = scaling; awsConfig.fargate = { ...awsConfig.fargate, ...SCALING_TO_CONFIG[scaling].fargate }; awsConfig.database = { ...awsConfig.database, ...SCALING_TO_CONFIG[scaling].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
[ "function", "askScaling", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "chainPromises", "=", "index", "=>", "{", "if", "(", "index", "===", "this", ".", "appConfigs", ".", "length", ")", "{", "done", "(", ")", ";", "return", "null", ";", "}", "const", "config", "=", "this", ".", "appConfigs", "[", "index", "]", ";", "const", "awsConfig", "=", "this", ".", "aws", ".", "apps", ".", "find", "(", "a", "=>", "a", ".", "baseName", "===", "config", ".", "baseName", ")", "||", "{", "baseName", ":", "config", ".", "baseName", "}", ";", "return", "promptScaling", ".", "call", "(", "this", ",", "config", ",", "awsConfig", ")", ".", "then", "(", "scaling", "=>", "{", "awsConfig", ".", "scaling", "=", "scaling", ";", "awsConfig", ".", "fargate", "=", "{", "...", "awsConfig", ".", "fargate", ",", "...", "SCALING_TO_CONFIG", "[", "scaling", "]", ".", "fargate", "}", ";", "awsConfig", ".", "database", "=", "{", "...", "awsConfig", ".", "database", ",", "...", "SCALING_TO_CONFIG", "[", "scaling", "]", ".", "database", "}", ";", "_", ".", "remove", "(", "this", ".", "aws", ".", "apps", ",", "a", "=>", "_", ".", "isEqual", "(", "a", ",", "awsConfig", ")", ")", ";", "this", ".", "aws", ".", "apps", ".", "push", "(", "awsConfig", ")", ";", "return", "chainPromises", "(", "index", "+", "1", ")", ";", "}", ")", ";", "}", ";", "return", "chainPromises", "(", "0", ")", ";", "}" ]
Ask about scaling
[ "Ask", "about", "scaling" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L291-L313
784
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askVPC
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${vpc.IsDefault}, state: ${vpc.State})`, value: vpc.VpcId, short: vpc.VpcId }; }); const prompts = [ { type: 'list', name: 'targetVPC', message: 'Please select your target Virtual Private Network.', choices: vpcList, default: this.aws.vpc.id } ]; return this.prompt(prompts).then(props => { const targetVPC = props.targetVPC; if (targetVPC) { this.aws.vpc.id = targetVPC; this.aws.vpc.cidr = _.find(this.awsFacts.availableVpcs, ['VpcId', targetVPC]).CidrBlock; done(); } else { this.abort = true; done(); } }); }
javascript
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${vpc.IsDefault}, state: ${vpc.State})`, value: vpc.VpcId, short: vpc.VpcId }; }); const prompts = [ { type: 'list', name: 'targetVPC', message: 'Please select your target Virtual Private Network.', choices: vpcList, default: this.aws.vpc.id } ]; return this.prompt(prompts).then(props => { const targetVPC = props.targetVPC; if (targetVPC) { this.aws.vpc.id = targetVPC; this.aws.vpc.cidr = _.find(this.awsFacts.availableVpcs, ['VpcId', targetVPC]).CidrBlock; done(); } else { this.abort = true; done(); } }); }
[ "function", "askVPC", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "vpcList", "=", "this", ".", "awsFacts", ".", "availableVpcs", ".", "map", "(", "vpc", "=>", "{", "const", "friendlyName", "=", "_getFriendlyNameFromTag", "(", "vpc", ")", ";", "return", "{", "name", ":", "`", "${", "vpc", ".", "VpcId", "}", "${", "friendlyName", "?", "`", "${", "friendlyName", "}", "`", ":", "''", "}", "${", "vpc", ".", "IsDefault", "}", "${", "vpc", ".", "State", "}", "`", ",", "value", ":", "vpc", ".", "VpcId", ",", "short", ":", "vpc", ".", "VpcId", "}", ";", "}", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'list'", ",", "name", ":", "'targetVPC'", ",", "message", ":", "'Please select your target Virtual Private Network.'", ",", "choices", ":", "vpcList", ",", "default", ":", "this", ".", "aws", ".", "vpc", ".", "id", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "const", "targetVPC", "=", "props", ".", "targetVPC", ";", "if", "(", "targetVPC", ")", "{", "this", ".", "aws", ".", "vpc", ".", "id", "=", "targetVPC", ";", "this", ".", "aws", ".", "vpc", ".", "cidr", "=", "_", ".", "find", "(", "this", ".", "awsFacts", ".", "availableVpcs", ",", "[", "'VpcId'", ",", "targetVPC", "]", ")", ".", "CidrBlock", ";", "done", "(", ")", ";", "}", "else", "{", "this", ".", "abort", "=", "true", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}" ]
Ask user to select target Virtual Private Network
[ "Ask", "user", "to", "select", "target", "Virtual", "Private", "Network" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L347-L381
785
jhipster/generator-jhipster
generators/aws-containers/prompts.js
askDeployNow
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(props => { this.deployNow = props.deployNow; done(); }); }
javascript
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(props => { this.deployNow = props.deployNow; done(); }); }
[ "function", "askDeployNow", "(", ")", "{", "if", "(", "this", ".", "abort", ")", "return", "null", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "const", "prompts", "=", "[", "{", "type", ":", "'confirm'", ",", "name", ":", "'deployNow'", ",", "message", ":", "'Would you like to deploy now?.'", ",", "default", ":", "true", "}", "]", ";", "return", "this", ".", "prompt", "(", "prompts", ")", ".", "then", "(", "props", "=>", "{", "this", ".", "deployNow", "=", "props", ".", "deployNow", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Ask user if they would like to deploy now?
[ "Ask", "user", "if", "they", "would", "like", "to", "deploy", "now?" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/prompts.js#L495-L511
786
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_doesEventContainsNestedStackId
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; } if (_.isNil(stack.PhysicalResourceId)) { return false; } return _hasLabelNestedStackName(stack.PhysicalResourceId); }
javascript
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; } if (_.isNil(stack.PhysicalResourceId)) { return false; } return _hasLabelNestedStackName(stack.PhysicalResourceId); }
[ "function", "_doesEventContainsNestedStackId", "(", "stack", ")", "{", "if", "(", "stack", ".", "ResourceType", "!==", "'AWS::CloudFormation::Stack'", ")", "{", "return", "false", ";", "}", "if", "(", "stack", ".", "ResourceStatusReason", "!==", "'Resource creation Initiated'", ")", "{", "return", "false", ";", "}", "if", "(", "stack", ".", "ResourceStatus", "!==", "'CREATE_IN_PROGRESS'", ")", "{", "return", "false", ";", "}", "if", "(", "_", ".", "isNil", "(", "stack", ".", "PhysicalResourceId", ")", ")", "{", "return", "false", ";", "}", "return", "_hasLabelNestedStackName", "(", "stack", ".", "PhysicalResourceId", ")", ";", "}" ]
Check if the stack event contains the name a Nested Stack name. @param stack The StackEvent object. @returns {boolean} true if the object contain a Nested Stack name, false otherwise. @private
[ "Check", "if", "the", "stack", "event", "contains", "the", "name", "a", "Nested", "Stack", "name", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L266-L281
787
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_formatStatus
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { statusColorFn = chalk.greenBright; } const sanitizedStatus = _.replace(status, '_', ' '); const paddedStatus = _.padEnd(sanitizedStatus, STACK_EVENT_STATUS_DISPLAY_LENGTH); return statusColorFn(paddedStatus); }
javascript
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { statusColorFn = chalk.greenBright; } const sanitizedStatus = _.replace(status, '_', ' '); const paddedStatus = _.padEnd(sanitizedStatus, STACK_EVENT_STATUS_DISPLAY_LENGTH); return statusColorFn(paddedStatus); }
[ "function", "_formatStatus", "(", "status", ")", "{", "let", "statusColorFn", "=", "chalk", ".", "grey", ";", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'IN_PROGRESS'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "yellow", ";", "}", "else", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'FAILED'", ")", "||", "_", ".", "startsWith", "(", "status", ",", "'DELETE'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "red", ";", "}", "else", "if", "(", "_", ".", "endsWith", "(", "status", ",", "'COMPLETE'", ")", ")", "{", "statusColorFn", "=", "chalk", ".", "greenBright", ";", "}", "const", "sanitizedStatus", "=", "_", ".", "replace", "(", "status", ",", "'_'", ",", "' '", ")", ";", "const", "paddedStatus", "=", "_", ".", "padEnd", "(", "sanitizedStatus", ",", "STACK_EVENT_STATUS_DISPLAY_LENGTH", ")", ";", "return", "statusColorFn", "(", "paddedStatus", ")", ";", "}" ]
returns a formatted status string ready to be displayed @param status @returns {*} a string @private
[ "returns", "a", "formatted", "status", "string", "ready", "to", "be", "displayed" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L289-L302
788
jhipster/generator-jhipster
generators/aws-containers/lib/cloudFormation.js
_getStackLogLine
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(stack.ResourceType); return `${time} ${spacing}${status} ${resourceType}\t${stackName}`; }
javascript
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(stack.ResourceType); return `${time} ${spacing}${status} ${resourceType}\t${stackName}`; }
[ "function", "_getStackLogLine", "(", "stack", ",", "indentation", "=", "0", ")", "{", "const", "time", "=", "chalk", ".", "blue", "(", "`", "${", "stack", ".", "Timestamp", ".", "toLocaleTimeString", "(", ")", "}", "`", ")", ";", "const", "spacing", "=", "_", ".", "repeat", "(", "'\\t'", ",", "indentation", ")", ";", "const", "status", "=", "_formatStatus", "(", "stack", ".", "ResourceStatus", ")", ";", "const", "stackName", "=", "chalk", ".", "grey", "(", "stack", ".", "StackName", ")", ";", "const", "resourceType", "=", "chalk", ".", "bold", "(", "stack", ".", "ResourceType", ")", ";", "return", "`", "${", "time", "}", "${", "spacing", "}", "${", "status", "}", "${", "resourceType", "}", "\\t", "${", "stackName", "}", "`", ";", "}" ]
Generate an enriched string to display a CloudFormation Stack creation event. @param stack Stack event @param indentation level of indentation to display (between the date and the rest of the log) @returns {string} @private
[ "Generate", "an", "enriched", "string", "to", "display", "a", "CloudFormation", "Stack", "creation", "event", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/aws-containers/lib/cloudFormation.js#L311-L319
789
jhipster/generator-jhipster
generators/docker-cli.js
loginToAws
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }), { silent: true } ); }
javascript
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }), { silent: true } ); }
[ "function", "loginToAws", "(", "region", ",", "accountId", ",", "username", ",", "password", ")", "{", "const", "commandLine", "=", "`", "${", "password", "}", "${", "accountId", "}", "${", "region", "}", "`", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "command", "(", "commandLine", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "stdout", ")", ";", "}", ")", ",", "{", "silent", ":", "true", "}", ")", ";", "}" ]
Log docker to AWS. @param region @param accountId @param username @param password @returns {Promise}
[ "Log", "docker", "to", "AWS", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-cli.js#L119-L131
790
jhipster/generator-jhipster
generators/docker-cli.js
pushImage
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
javascript
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
[ "function", "pushImage", "(", "repository", ")", "{", "const", "commandLine", "=", "`", "${", "repository", "}", "`", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "command", "(", "commandLine", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "stdout", ")", ";", "}", ")", ")", ";", "}" ]
Pushes the locally constructed Docker image to the supplied respository @param repository tag, for example: 111111111.dkr.ecr.us-east-1.amazonaws.com/sample @returns {Promise<any>}
[ "Pushes", "the", "locally", "constructed", "Docker", "image", "to", "the", "supplied", "respository" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-cli.js#L138-L148
791
jhipster/generator-jhipster
generators/docker-utils.js
checkDocker
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { const dockerVersion = stdout.split(' ')[2].replace(/,/g, ''); const dockerVersionMajor = dockerVersion.split('.')[0]; const dockerVersionMinor = dockerVersion.split('.')[1]; if (dockerVersionMajor < 1 || (dockerVersionMajor === 1 && dockerVersionMinor < 10)) { this.log( chalk.red( `${'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Docker version found: '}${dockerVersion}\n` + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { this.log.ok('Docker is installed'); } } done(); }); }
javascript
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { const dockerVersion = stdout.split(' ')[2].replace(/,/g, ''); const dockerVersionMajor = dockerVersion.split('.')[0]; const dockerVersionMinor = dockerVersion.split('.')[1]; if (dockerVersionMajor < 1 || (dockerVersionMajor === 1 && dockerVersionMinor < 10)) { this.log( chalk.red( `${'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Docker version found: '}${dockerVersion}\n` + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { this.log.ok('Docker is installed'); } } done(); }); }
[ "function", "checkDocker", "(", ")", "{", "if", "(", "this", ".", "abort", "||", "this", ".", "skipChecks", ")", "return", ";", "const", "done", "=", "this", ".", "async", "(", ")", ";", "shelljs", ".", "exec", "(", "'docker -v'", ",", "{", "silent", ":", "true", "}", ",", "(", "code", ",", "stdout", ",", "stderr", ")", "=>", "{", "if", "(", "stderr", ")", "{", "this", ".", "log", "(", "chalk", ".", "red", "(", "'Docker version 1.10.0 or later is not installed on your computer.\\n'", "+", "' Read http://docs.docker.com/engine/installation/#installation\\n'", ")", ")", ";", "this", ".", "abort", "=", "true", ";", "}", "else", "{", "const", "dockerVersion", "=", "stdout", ".", "split", "(", "' '", ")", "[", "2", "]", ".", "replace", "(", "/", ",", "/", "g", ",", "''", ")", ";", "const", "dockerVersionMajor", "=", "dockerVersion", ".", "split", "(", "'.'", ")", "[", "0", "]", ";", "const", "dockerVersionMinor", "=", "dockerVersion", ".", "split", "(", "'.'", ")", "[", "1", "]", ";", "if", "(", "dockerVersionMajor", "<", "1", "||", "(", "dockerVersionMajor", "===", "1", "&&", "dockerVersionMinor", "<", "10", ")", ")", "{", "this", ".", "log", "(", "chalk", ".", "red", "(", "`", "${", "'Docker version 1.10.0 or later is not installed on your computer.\\n'", "+", "' Docker version found: '", "}", "${", "dockerVersion", "}", "\\n", "`", "+", "' Read http://docs.docker.com/engine/installation/#installation\\n'", ")", ")", ";", "this", ".", "abort", "=", "true", ";", "}", "else", "{", "this", ".", "log", ".", "ok", "(", "'Docker is installed'", ")", ";", "}", "}", "done", "(", ")", ";", "}", ")", ";", "}" ]
Check that Docker exists. @param failOver flag
[ "Check", "that", "Docker", "exists", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-utils.js#L39-L71
792
jhipster/generator-jhipster
generators/docker-utils.js
checkImageExist
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/target/docker`); this.dockerBuildCommand = './mvnw -Pprod verify jib:dockerBuild'; } else { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/build/docker`); this.dockerBuildCommand = './gradlew bootWar -Pprod jibDockerBuild'; } if (shelljs.ls(imagePath).length === 0) { this.warning = true; this.warningMessage += ` ${chalk.cyan(this.dockerBuildCommand)} in ${this.destinationPath(this.directoryPath + opts.cwd)}\n`; } }
javascript
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/target/docker`); this.dockerBuildCommand = './mvnw -Pprod verify jib:dockerBuild'; } else { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/build/docker`); this.dockerBuildCommand = './gradlew bootWar -Pprod jibDockerBuild'; } if (shelljs.ls(imagePath).length === 0) { this.warning = true; this.warningMessage += ` ${chalk.cyan(this.dockerBuildCommand)} in ${this.destinationPath(this.directoryPath + opts.cwd)}\n`; } }
[ "function", "checkImageExist", "(", "opts", "=", "{", "cwd", ":", "'./'", ",", "appConfig", ":", "null", "}", ")", "{", "if", "(", "this", ".", "abort", ")", "return", ";", "let", "imagePath", "=", "''", ";", "this", ".", "warning", "=", "false", ";", "this", ".", "warningMessage", "=", "'To generate the missing Docker image(s), please run:\\n'", ";", "if", "(", "opts", ".", "appConfig", ".", "buildTool", "===", "'maven'", ")", "{", "imagePath", "=", "this", ".", "destinationPath", "(", "`", "${", "opts", ".", "cwd", "+", "opts", ".", "cwd", "}", "`", ")", ";", "this", ".", "dockerBuildCommand", "=", "'./mvnw -Pprod verify jib:dockerBuild'", ";", "}", "else", "{", "imagePath", "=", "this", ".", "destinationPath", "(", "`", "${", "opts", ".", "cwd", "+", "opts", ".", "cwd", "}", "`", ")", ";", "this", ".", "dockerBuildCommand", "=", "'./gradlew bootWar -Pprod jibDockerBuild'", ";", "}", "if", "(", "shelljs", ".", "ls", "(", "imagePath", ")", ".", "length", "===", "0", ")", "{", "this", ".", "warning", "=", "true", ";", "this", ".", "warningMessage", "+=", "`", "${", "chalk", ".", "cyan", "(", "this", ".", "dockerBuildCommand", ")", "}", "${", "this", ".", "destinationPath", "(", "this", ".", "directoryPath", "+", "opts", ".", "cwd", ")", "}", "\\n", "`", ";", "}", "}" ]
Check that a Docker image exists in a JHipster app. @param opts Options to pass. @property pwd JHipster app directory. default is './' @property appConfig Configuration for the current application
[ "Check", "that", "a", "Docker", "image", "exists", "in", "a", "JHipster", "app", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/docker-utils.js#L80-L98
793
jhipster/generator-jhipster
cli/import-jdl.js
importJDL
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, forceNoFiltering: this.options.force }); let importState = { exportedEntities: [], exportedApplications: [], exportedDeployments: [] }; try { importState = jdlImporter.import(); logger.debug(`importState exportedEntities: ${importState.exportedEntities.length}`); logger.debug(`importState exportedApplications: ${importState.exportedApplications.length}`); logger.debug(`importState exportedDeployments: ${importState.exportedDeployments.length}`); updateDeploymentState(importState); if (importState.exportedEntities.length > 0) { const entityNames = _.uniq(importState.exportedEntities.map(exportedEntity => exportedEntity.name)).join(', '); logger.info(`Found entities: ${chalk.yellow(entityNames)}.`); } else { logger.info(chalk.yellow('No change in entity configurations, no entities were updated.')); } logger.info('The JDL has been successfully parsed'); } catch (error) { logger.debug('Error:', error); if (error) { const errorName = `${error.name}:` || ''; const errorMessage = error.message || ''; logger.log(chalk.red(`${errorName} ${errorMessage}`)); } logger.error(`Error while parsing applications and entities from the JDL ${error}`, error); } return importState; }
javascript
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, forceNoFiltering: this.options.force }); let importState = { exportedEntities: [], exportedApplications: [], exportedDeployments: [] }; try { importState = jdlImporter.import(); logger.debug(`importState exportedEntities: ${importState.exportedEntities.length}`); logger.debug(`importState exportedApplications: ${importState.exportedApplications.length}`); logger.debug(`importState exportedDeployments: ${importState.exportedDeployments.length}`); updateDeploymentState(importState); if (importState.exportedEntities.length > 0) { const entityNames = _.uniq(importState.exportedEntities.map(exportedEntity => exportedEntity.name)).join(', '); logger.info(`Found entities: ${chalk.yellow(entityNames)}.`); } else { logger.info(chalk.yellow('No change in entity configurations, no entities were updated.')); } logger.info('The JDL has been successfully parsed'); } catch (error) { logger.debug('Error:', error); if (error) { const errorName = `${error.name}:` || ''; const errorMessage = error.message || ''; logger.log(chalk.red(`${errorName} ${errorMessage}`)); } logger.error(`Error while parsing applications and entities from the JDL ${error}`, error); } return importState; }
[ "function", "importJDL", "(", ")", "{", "logger", ".", "info", "(", "'The JDL is being parsed.'", ")", ";", "const", "jdlImporter", "=", "new", "jhiCore", ".", "JDLImporter", "(", "this", ".", "jdlFiles", ",", "{", "databaseType", ":", "this", ".", "prodDatabaseType", ",", "applicationType", ":", "this", ".", "applicationType", ",", "applicationName", ":", "this", ".", "baseName", ",", "generatorVersion", ":", "packagejs", ".", "version", ",", "forceNoFiltering", ":", "this", ".", "options", ".", "force", "}", ")", ";", "let", "importState", "=", "{", "exportedEntities", ":", "[", "]", ",", "exportedApplications", ":", "[", "]", ",", "exportedDeployments", ":", "[", "]", "}", ";", "try", "{", "importState", "=", "jdlImporter", ".", "import", "(", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedEntities", ".", "length", "}", "`", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedApplications", ".", "length", "}", "`", ")", ";", "logger", ".", "debug", "(", "`", "${", "importState", ".", "exportedDeployments", ".", "length", "}", "`", ")", ";", "updateDeploymentState", "(", "importState", ")", ";", "if", "(", "importState", ".", "exportedEntities", ".", "length", ">", "0", ")", "{", "const", "entityNames", "=", "_", ".", "uniq", "(", "importState", ".", "exportedEntities", ".", "map", "(", "exportedEntity", "=>", "exportedEntity", ".", "name", ")", ")", ".", "join", "(", "', '", ")", ";", "logger", ".", "info", "(", "`", "${", "chalk", ".", "yellow", "(", "entityNames", ")", "}", "`", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "chalk", ".", "yellow", "(", "'No change in entity configurations, no entities were updated.'", ")", ")", ";", "}", "logger", ".", "info", "(", "'The JDL has been successfully parsed'", ")", ";", "}", "catch", "(", "error", ")", "{", "logger", ".", "debug", "(", "'Error:'", ",", "error", ")", ";", "if", "(", "error", ")", "{", "const", "errorName", "=", "`", "${", "error", ".", "name", "}", "`", "||", "''", ";", "const", "errorMessage", "=", "error", ".", "message", "||", "''", ";", "logger", ".", "log", "(", "chalk", ".", "red", "(", "`", "${", "errorName", "}", "${", "errorMessage", "}", "`", ")", ")", ";", "}", "logger", ".", "error", "(", "`", "${", "error", "}", "`", ",", "error", ")", ";", "}", "return", "importState", ";", "}" ]
Imports the Applications and Entities defined in JDL The app .yo-rc.json files and entity json files are written to disk
[ "Imports", "the", "Applications", "and", "Entities", "defined", "in", "JDL", "The", "app", ".", "yo", "-", "rc", ".", "json", "files", "and", "entity", "json", "files", "are", "written", "to", "disk" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/cli/import-jdl.js#L61-L98
794
jhipster/generator-jhipster
generators/cleanup.js
cleanupOldFiles
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`); } if (generator.isJhipsterVersionLessThan('5.0.0')) { generator.removeFile(`${ANGULAR_DIR}/app.route.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`); } if (generator.isJhipsterVersionLessThan('5.8.0')) { generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`); generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`); } }
javascript
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`); } if (generator.isJhipsterVersionLessThan('5.0.0')) { generator.removeFile(`${ANGULAR_DIR}/app.route.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`); } if (generator.isJhipsterVersionLessThan('5.8.0')) { generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`); generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`); } }
[ "function", "cleanupOldFiles", "(", "generator", ")", "{", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'3.2.0'", ")", ")", "{", "// removeFile and removeFolder methods should be called here for files and folders to cleanup", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "}", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'5.0.0'", ")", ")", "{", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "}", "if", "(", "generator", ".", "isJhipsterVersionLessThan", "(", "'5.8.0'", ")", ")", "{", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "ANGULAR_DIR", "}", "`", ")", ";", "generator", ".", "removeFile", "(", "`", "${", "CLIENT_TEST_SRC_DIR", "}", "`", ")", ";", "}", "}" ]
Removes files that where generated in previous JHipster versions and therefore need to be removed. WARNING this only removes files created by the main generator. Each sub-generator should clean-up its own files: see the `cleanup` method in entity/index.js for cleaning up entities. @param {any} generator - reference to generator
[ "Removes", "files", "that", "where", "generated", "in", "previous", "JHipster", "versions", "and", "therefore", "need", "to", "be", "removed", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/cleanup.js#L41-L78
795
jhipster/generator-jhipster
generators/utils.js
rewriteFile
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
javascript
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
[ "function", "rewriteFile", "(", "args", ",", "generator", ")", "{", "args", ".", "path", "=", "args", ".", "path", "||", "process", ".", "cwd", "(", ")", ";", "const", "fullPath", "=", "path", ".", "join", "(", "args", ".", "path", ",", "args", ".", "file", ")", ";", "args", ".", "haystack", "=", "generator", ".", "fs", ".", "read", "(", "fullPath", ")", ";", "const", "body", "=", "rewrite", "(", "args", ")", ";", "generator", ".", "fs", ".", "write", "(", "fullPath", ",", "body", ")", ";", "}" ]
Rewrite file with passed arguments @param {object} args argument object (containing path, file, haystack, etc properties) @param {object} generator reference to the generator
[ "Rewrite", "file", "with", "passed", "arguments" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L57-L64
796
jhipster/generator-jhipster
generators/utils.js
rewrite
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex = -1; lines.forEach((line, i) => { if (line.includes(args.needle)) { otherwiseLineIndex = i; } }); let spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } let spaceStr = ''; // eslint-disable-next-line no-cond-assign while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n')); return lines.join('\n'); }
javascript
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex = -1; lines.forEach((line, i) => { if (line.includes(args.needle)) { otherwiseLineIndex = i; } }); let spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } let spaceStr = ''; // eslint-disable-next-line no-cond-assign while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n')); return lines.join('\n'); }
[ "function", "rewrite", "(", "args", ")", "{", "// check if splicable is already in the body text", "const", "re", "=", "new", "RegExp", "(", "args", ".", "splicable", ".", "map", "(", "line", "=>", "`", "\\\\", "${", "escapeRegExp", "(", "line", ")", "}", "`", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "if", "(", "re", ".", "test", "(", "args", ".", "haystack", ")", ")", "{", "return", "args", ".", "haystack", ";", "}", "const", "lines", "=", "args", ".", "haystack", ".", "split", "(", "'\\n'", ")", ";", "let", "otherwiseLineIndex", "=", "-", "1", ";", "lines", ".", "forEach", "(", "(", "line", ",", "i", ")", "=>", "{", "if", "(", "line", ".", "includes", "(", "args", ".", "needle", ")", ")", "{", "otherwiseLineIndex", "=", "i", ";", "}", "}", ")", ";", "let", "spaces", "=", "0", ";", "while", "(", "lines", "[", "otherwiseLineIndex", "]", ".", "charAt", "(", "spaces", ")", "===", "' '", ")", "{", "spaces", "+=", "1", ";", "}", "let", "spaceStr", "=", "''", ";", "// eslint-disable-next-line no-cond-assign", "while", "(", "(", "spaces", "-=", "1", ")", ">=", "0", ")", "{", "spaceStr", "+=", "' '", ";", "}", "lines", ".", "splice", "(", "otherwiseLineIndex", ",", "0", ",", "args", ".", "splicable", ".", "map", "(", "line", "=>", "spaceStr", "+", "line", ")", ".", "join", "(", "'\\n'", ")", ")", ";", "return", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Rewrite using the passed argument object. @param {object} args arguments object (containing splicable, haystack, needle properties) to be used @returns {*} re-written file
[ "Rewrite", "using", "the", "passed", "argument", "object", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L98-L130
797
jhipster/generator-jhipster
generators/utils.js
rewriteJSONFile
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
javascript
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
[ "function", "rewriteJSONFile", "(", "filePath", ",", "rewriteFile", ",", "generator", ")", "{", "const", "jsonObj", "=", "generator", ".", "fs", ".", "readJSON", "(", "filePath", ")", ";", "rewriteFile", "(", "jsonObj", ",", "generator", ")", ";", "generator", ".", "fs", ".", "writeJSON", "(", "filePath", ",", "jsonObj", ",", "null", ",", "2", ")", ";", "}" ]
Rewrite JSON file @param {string} filePath file path @param {function} rewriteFile rewriteFile function @param {object} generator reference to the generator
[ "Rewrite", "JSON", "file" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L152-L156
798
jhipster/generator-jhipster
generators/utils.js
copyWebResource
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); switch (type) { case 'html': body = replacePlaceholders(body, generator); break; case 'js': body = replaceTitle(body, generator); break; case 'jsx': body = replaceTranslation(body, generator); break; default: break; } generator.fs.write(dest, body); }); } }
javascript
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); switch (type) { case 'html': body = replacePlaceholders(body, generator); break; case 'js': body = replaceTitle(body, generator); break; case 'jsx': body = replaceTranslation(body, generator); break; default: break; } generator.fs.write(dest, body); }); } }
[ "function", "copyWebResource", "(", "source", ",", "dest", ",", "regex", ",", "type", ",", "generator", ",", "opt", "=", "{", "}", ",", "template", ")", "{", "if", "(", "generator", ".", "enableTranslation", ")", "{", "generator", ".", "template", "(", "source", ",", "dest", ",", "generator", ",", "opt", ")", ";", "}", "else", "{", "renderContent", "(", "source", ",", "generator", ",", "generator", ",", "opt", ",", "body", "=>", "{", "body", "=", "body", ".", "replace", "(", "regex", ",", "''", ")", ";", "switch", "(", "type", ")", "{", "case", "'html'", ":", "body", "=", "replacePlaceholders", "(", "body", ",", "generator", ")", ";", "break", ";", "case", "'js'", ":", "body", "=", "replaceTitle", "(", "body", ",", "generator", ")", ";", "break", ";", "case", "'jsx'", ":", "body", "=", "replaceTranslation", "(", "body", ",", "generator", ")", ";", "break", ";", "default", ":", "break", ";", "}", "generator", ".", "fs", ".", "write", "(", "dest", ",", "body", ")", ";", "}", ")", ";", "}", "}" ]
Copy web resources @param {string} source source @param {string} dest destination @param {regex} regex regex @param {string} type type of resource (html, js, etc) @param {object} generator reference to the generator @param {object} opt options @param {any} template template
[ "Copy", "web", "resources" ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L169-L191
799
jhipster/generator-jhipster
generators/utils.js
getJavadoc
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} * ${rows[i]}`; } javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} */`; return javadoc; }
javascript
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} * ${rows[i]}`; } javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} */`; return javadoc; }
[ "function", "getJavadoc", "(", "text", ",", "indentSize", ")", "{", "if", "(", "!", "text", ")", "{", "text", "=", "''", ";", "}", "if", "(", "text", ".", "includes", "(", "'\"'", ")", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\"'", ")", ";", "}", "let", "javadoc", "=", "`", "${", "_", ".", "repeat", "(", "' '", ",", "indentSize", ")", "}", "`", ";", "const", "rows", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "javadoc", "=", "`", "${", "javadoc", "}", "\\n", "${", "_", ".", "repeat", "(", "' '", ",", "indentSize", ")", "}", "${", "rows", "[", "i", "]", "}", "`", ";", "}", "javadoc", "=", "`", "${", "javadoc", "}", "\\n", "${", "_", ".", "repeat", "(", "' '", ",", "indentSize", ")", "}", "`", ";", "return", "javadoc", ";", "}" ]
Convert passed block of string to javadoc formatted string. @param {string} text text to convert to javadoc format @param {number} indentSize indent size @returns javadoc formatted string
[ "Convert", "passed", "block", "of", "string", "to", "javadoc", "formatted", "string", "." ]
f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff
https://github.com/jhipster/generator-jhipster/blob/f76fa8de0818ce6bda6c7b1455942e2a9b0ae3ff/generators/utils.js#L356-L370