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
2,500
adobe/brackets
src/extensions/default/CodeFolding/main.js
deinit
function deinit() { _isInitialized = false; KeyBindingManager.removeBinding(collapseKey); KeyBindingManager.removeBinding(expandKey); KeyBindingManager.removeBinding(collapseAllKey); KeyBindingManager.removeBinding(expandAllKey); KeyBindingManager.removeBinding(collapseAllKeyMac); KeyBindingManager.removeBinding(expandAllKeyMac); //remove menus Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuDivider(codeFoldingMenuDivider.id); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND_ALL); EditorManager.off(".CodeFolding"); DocumentManager.off(".CodeFolding"); ProjectManager.off(".CodeFolding"); // Remove gutter & revert collapsed sections in all currently open editors Editor.forEveryEditor(function (editor) { CodeMirror.commands.unfoldAll(editor._codeMirror); }); removeGutters(); }
javascript
function deinit() { _isInitialized = false; KeyBindingManager.removeBinding(collapseKey); KeyBindingManager.removeBinding(expandKey); KeyBindingManager.removeBinding(collapseAllKey); KeyBindingManager.removeBinding(expandAllKey); KeyBindingManager.removeBinding(collapseAllKeyMac); KeyBindingManager.removeBinding(expandAllKeyMac); //remove menus Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuDivider(codeFoldingMenuDivider.id); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND_ALL); EditorManager.off(".CodeFolding"); DocumentManager.off(".CodeFolding"); ProjectManager.off(".CodeFolding"); // Remove gutter & revert collapsed sections in all currently open editors Editor.forEveryEditor(function (editor) { CodeMirror.commands.unfoldAll(editor._codeMirror); }); removeGutters(); }
[ "function", "deinit", "(", ")", "{", "_isInitialized", "=", "false", ";", "KeyBindingManager", ".", "removeBinding", "(", "collapseKey", ")", ";", "KeyBindingManager", ".", "removeBinding", "(", "expandKey", ")", ";", "KeyBindingManager", ".", "removeBinding", "(", "collapseAllKey", ")", ";", "KeyBindingManager", ".", "removeBinding", "(", "expandAllKey", ")", ";", "KeyBindingManager", ".", "removeBinding", "(", "collapseAllKeyMac", ")", ";", "KeyBindingManager", ".", "removeBinding", "(", "expandAllKeyMac", ")", ";", "//remove menus", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "removeMenuDivider", "(", "codeFoldingMenuDivider", ".", "id", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "removeMenuItem", "(", "COLLAPSE", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "removeMenuItem", "(", "EXPAND", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "removeMenuItem", "(", "COLLAPSE_ALL", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "removeMenuItem", "(", "EXPAND_ALL", ")", ";", "EditorManager", ".", "off", "(", "\".CodeFolding\"", ")", ";", "DocumentManager", ".", "off", "(", "\".CodeFolding\"", ")", ";", "ProjectManager", ".", "off", "(", "\".CodeFolding\"", ")", ";", "// Remove gutter & revert collapsed sections in all currently open editors", "Editor", ".", "forEveryEditor", "(", "function", "(", "editor", ")", "{", "CodeMirror", ".", "commands", ".", "unfoldAll", "(", "editor", ".", "_codeMirror", ")", ";", "}", ")", ";", "removeGutters", "(", ")", ";", "}" ]
Remove code-folding functionality
[ "Remove", "code", "-", "folding", "functionality" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/CodeFolding/main.js#L358-L384
2,501
adobe/brackets
src/extensions/default/CodeFolding/main.js
init
function init() { _isInitialized = true; foldCode.init(); foldGutter.init(); // Many CodeMirror modes specify which fold helper should be used for that language. For a few that // don't, we register helpers explicitly here. We also register a global helper for generic indent-based // folding, which cuts across all languages if enabled via preference. CodeMirror.registerGlobalHelper("fold", "selectionFold", function (mode, cm) { return prefs.getSetting("makeSelectionsFoldable"); }, selectionFold); CodeMirror.registerGlobalHelper("fold", "indent", function (mode, cm) { return prefs.getSetting("alwaysUseIndentFold"); }, indentFold); CodeMirror.registerHelper("fold", "handlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlhandlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlmixed", handlebarsFold); EditorManager.on("activeEditorChange.CodeFolding", onActiveEditorChanged); DocumentManager.on("documentRefreshed.CodeFolding", function (event, doc) { restoreLineFolds(doc._masterEditor); }); ProjectManager.on("beforeProjectClose.CodeFolding beforeAppClose.CodeFolding", saveBeforeClose); //create menus codeFoldingMenuDivider = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuDivider(); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND); //register keybindings KeyBindingManager.addBinding(COLLAPSE_ALL, [ {key: collapseAllKey}, {key: collapseAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(EXPAND_ALL, [ {key: expandAllKey}, {key: expandAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(COLLAPSE, collapseKey); KeyBindingManager.addBinding(EXPAND, expandKey); // Add gutters & restore saved expand/collapse state in all currently open editors Editor.registerGutter(GUTTER_NAME, CODE_FOLDING_GUTTER_PRIORITY); Editor.forEveryEditor(function (editor) { enableFoldingInEditor(editor); }); }
javascript
function init() { _isInitialized = true; foldCode.init(); foldGutter.init(); // Many CodeMirror modes specify which fold helper should be used for that language. For a few that // don't, we register helpers explicitly here. We also register a global helper for generic indent-based // folding, which cuts across all languages if enabled via preference. CodeMirror.registerGlobalHelper("fold", "selectionFold", function (mode, cm) { return prefs.getSetting("makeSelectionsFoldable"); }, selectionFold); CodeMirror.registerGlobalHelper("fold", "indent", function (mode, cm) { return prefs.getSetting("alwaysUseIndentFold"); }, indentFold); CodeMirror.registerHelper("fold", "handlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlhandlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlmixed", handlebarsFold); EditorManager.on("activeEditorChange.CodeFolding", onActiveEditorChanged); DocumentManager.on("documentRefreshed.CodeFolding", function (event, doc) { restoreLineFolds(doc._masterEditor); }); ProjectManager.on("beforeProjectClose.CodeFolding beforeAppClose.CodeFolding", saveBeforeClose); //create menus codeFoldingMenuDivider = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuDivider(); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND); //register keybindings KeyBindingManager.addBinding(COLLAPSE_ALL, [ {key: collapseAllKey}, {key: collapseAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(EXPAND_ALL, [ {key: expandAllKey}, {key: expandAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(COLLAPSE, collapseKey); KeyBindingManager.addBinding(EXPAND, expandKey); // Add gutters & restore saved expand/collapse state in all currently open editors Editor.registerGutter(GUTTER_NAME, CODE_FOLDING_GUTTER_PRIORITY); Editor.forEveryEditor(function (editor) { enableFoldingInEditor(editor); }); }
[ "function", "init", "(", ")", "{", "_isInitialized", "=", "true", ";", "foldCode", ".", "init", "(", ")", ";", "foldGutter", ".", "init", "(", ")", ";", "// Many CodeMirror modes specify which fold helper should be used for that language. For a few that", "// don't, we register helpers explicitly here. We also register a global helper for generic indent-based", "// folding, which cuts across all languages if enabled via preference.", "CodeMirror", ".", "registerGlobalHelper", "(", "\"fold\"", ",", "\"selectionFold\"", ",", "function", "(", "mode", ",", "cm", ")", "{", "return", "prefs", ".", "getSetting", "(", "\"makeSelectionsFoldable\"", ")", ";", "}", ",", "selectionFold", ")", ";", "CodeMirror", ".", "registerGlobalHelper", "(", "\"fold\"", ",", "\"indent\"", ",", "function", "(", "mode", ",", "cm", ")", "{", "return", "prefs", ".", "getSetting", "(", "\"alwaysUseIndentFold\"", ")", ";", "}", ",", "indentFold", ")", ";", "CodeMirror", ".", "registerHelper", "(", "\"fold\"", ",", "\"handlebars\"", ",", "handlebarsFold", ")", ";", "CodeMirror", ".", "registerHelper", "(", "\"fold\"", ",", "\"htmlhandlebars\"", ",", "handlebarsFold", ")", ";", "CodeMirror", ".", "registerHelper", "(", "\"fold\"", ",", "\"htmlmixed\"", ",", "handlebarsFold", ")", ";", "EditorManager", ".", "on", "(", "\"activeEditorChange.CodeFolding\"", ",", "onActiveEditorChanged", ")", ";", "DocumentManager", ".", "on", "(", "\"documentRefreshed.CodeFolding\"", ",", "function", "(", "event", ",", "doc", ")", "{", "restoreLineFolds", "(", "doc", ".", "_masterEditor", ")", ";", "}", ")", ";", "ProjectManager", ".", "on", "(", "\"beforeProjectClose.CodeFolding beforeAppClose.CodeFolding\"", ",", "saveBeforeClose", ")", ";", "//create menus", "codeFoldingMenuDivider", "=", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "addMenuDivider", "(", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "addMenuItem", "(", "COLLAPSE_ALL", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "addMenuItem", "(", "EXPAND_ALL", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "addMenuItem", "(", "COLLAPSE", ")", ";", "Menus", ".", "getMenu", "(", "Menus", ".", "AppMenuBar", ".", "VIEW_MENU", ")", ".", "addMenuItem", "(", "EXPAND", ")", ";", "//register keybindings", "KeyBindingManager", ".", "addBinding", "(", "COLLAPSE_ALL", ",", "[", "{", "key", ":", "collapseAllKey", "}", ",", "{", "key", ":", "collapseAllKeyMac", ",", "platform", ":", "\"mac\"", "}", "]", ")", ";", "KeyBindingManager", ".", "addBinding", "(", "EXPAND_ALL", ",", "[", "{", "key", ":", "expandAllKey", "}", ",", "{", "key", ":", "expandAllKeyMac", ",", "platform", ":", "\"mac\"", "}", "]", ")", ";", "KeyBindingManager", ".", "addBinding", "(", "COLLAPSE", ",", "collapseKey", ")", ";", "KeyBindingManager", ".", "addBinding", "(", "EXPAND", ",", "expandKey", ")", ";", "// Add gutters & restore saved expand/collapse state in all currently open editors", "Editor", ".", "registerGutter", "(", "GUTTER_NAME", ",", "CODE_FOLDING_GUTTER_PRIORITY", ")", ";", "Editor", ".", "forEveryEditor", "(", "function", "(", "editor", ")", "{", "enableFoldingInEditor", "(", "editor", ")", ";", "}", ")", ";", "}" ]
Enable code-folding functionality
[ "Enable", "code", "-", "folding", "functionality" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/CodeFolding/main.js#L389-L435
2,502
adobe/brackets
src/extensions/default/CodeFolding/main.js
watchPrefsForChanges
function watchPrefsForChanges() { prefs.prefsObject.on("change", function (e, data) { if (data.ids.indexOf("enabled") > -1) { // Check if enabled state mismatches whether code-folding is actually initialized (can't assume // since preference change events can occur when the value hasn't really changed) var isEnabled = prefs.getSetting("enabled"); if (isEnabled && !_isInitialized) { init(); } else if (!isEnabled && _isInitialized) { deinit(); } } }); }
javascript
function watchPrefsForChanges() { prefs.prefsObject.on("change", function (e, data) { if (data.ids.indexOf("enabled") > -1) { // Check if enabled state mismatches whether code-folding is actually initialized (can't assume // since preference change events can occur when the value hasn't really changed) var isEnabled = prefs.getSetting("enabled"); if (isEnabled && !_isInitialized) { init(); } else if (!isEnabled && _isInitialized) { deinit(); } } }); }
[ "function", "watchPrefsForChanges", "(", ")", "{", "prefs", ".", "prefsObject", ".", "on", "(", "\"change\"", ",", "function", "(", "e", ",", "data", ")", "{", "if", "(", "data", ".", "ids", ".", "indexOf", "(", "\"enabled\"", ")", ">", "-", "1", ")", "{", "// Check if enabled state mismatches whether code-folding is actually initialized (can't assume", "// since preference change events can occur when the value hasn't really changed)", "var", "isEnabled", "=", "prefs", ".", "getSetting", "(", "\"enabled\"", ")", ";", "if", "(", "isEnabled", "&&", "!", "_isInitialized", ")", "{", "init", "(", ")", ";", "}", "else", "if", "(", "!", "isEnabled", "&&", "_isInitialized", ")", "{", "deinit", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Register change listener for the preferences file.
[ "Register", "change", "listener", "for", "the", "preferences", "file", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/CodeFolding/main.js#L440-L453
2,503
adobe/brackets
src/filesystem/impls/appshell/node/FileWatcherDomain.js
init
function init(domainManager) { if (!domainManager.hasDomain("fileWatcher")) { domainManager.registerDomain("fileWatcher", {major: 0, minor: 1}); } domainManager.registerCommand( "fileWatcher", "watchPath", watcherManager.watchPath, false, "Start watching a file or directory", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to watch" }, { name: "ignored", type: "array", description: "list of path to ignore" }] ); domainManager.registerCommand( "fileWatcher", "unwatchPath", watcherManager.unwatchPath, false, "Stop watching a single file or a directory and it's descendants", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to unwatch" }] ); domainManager.registerCommand( "fileWatcher", "unwatchAll", watcherManager.unwatchAll, false, "Stop watching all files and directories" ); domainManager.registerEvent( "fileWatcher", "change", [ {name: "event", type: "string"}, {name: "parentDirPath", type: "string"}, {name: "entryName", type: "string"}, {name: "statsObj", type: "object"} ] ); watcherManager.setDomainManager(domainManager); watcherManager.setWatcherImpl(watcherImpl); }
javascript
function init(domainManager) { if (!domainManager.hasDomain("fileWatcher")) { domainManager.registerDomain("fileWatcher", {major: 0, minor: 1}); } domainManager.registerCommand( "fileWatcher", "watchPath", watcherManager.watchPath, false, "Start watching a file or directory", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to watch" }, { name: "ignored", type: "array", description: "list of path to ignore" }] ); domainManager.registerCommand( "fileWatcher", "unwatchPath", watcherManager.unwatchPath, false, "Stop watching a single file or a directory and it's descendants", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to unwatch" }] ); domainManager.registerCommand( "fileWatcher", "unwatchAll", watcherManager.unwatchAll, false, "Stop watching all files and directories" ); domainManager.registerEvent( "fileWatcher", "change", [ {name: "event", type: "string"}, {name: "parentDirPath", type: "string"}, {name: "entryName", type: "string"}, {name: "statsObj", type: "object"} ] ); watcherManager.setDomainManager(domainManager); watcherManager.setWatcherImpl(watcherImpl); }
[ "function", "init", "(", "domainManager", ")", "{", "if", "(", "!", "domainManager", ".", "hasDomain", "(", "\"fileWatcher\"", ")", ")", "{", "domainManager", ".", "registerDomain", "(", "\"fileWatcher\"", ",", "{", "major", ":", "0", ",", "minor", ":", "1", "}", ")", ";", "}", "domainManager", ".", "registerCommand", "(", "\"fileWatcher\"", ",", "\"watchPath\"", ",", "watcherManager", ".", "watchPath", ",", "false", ",", "\"Start watching a file or directory\"", ",", "[", "{", "name", ":", "\"path\"", ",", "type", ":", "\"string\"", ",", "description", ":", "\"absolute filesystem path of the file or directory to watch\"", "}", ",", "{", "name", ":", "\"ignored\"", ",", "type", ":", "\"array\"", ",", "description", ":", "\"list of path to ignore\"", "}", "]", ")", ";", "domainManager", ".", "registerCommand", "(", "\"fileWatcher\"", ",", "\"unwatchPath\"", ",", "watcherManager", ".", "unwatchPath", ",", "false", ",", "\"Stop watching a single file or a directory and it's descendants\"", ",", "[", "{", "name", ":", "\"path\"", ",", "type", ":", "\"string\"", ",", "description", ":", "\"absolute filesystem path of the file or directory to unwatch\"", "}", "]", ")", ";", "domainManager", ".", "registerCommand", "(", "\"fileWatcher\"", ",", "\"unwatchAll\"", ",", "watcherManager", ".", "unwatchAll", ",", "false", ",", "\"Stop watching all files and directories\"", ")", ";", "domainManager", ".", "registerEvent", "(", "\"fileWatcher\"", ",", "\"change\"", ",", "[", "{", "name", ":", "\"event\"", ",", "type", ":", "\"string\"", "}", ",", "{", "name", ":", "\"parentDirPath\"", ",", "type", ":", "\"string\"", "}", ",", "{", "name", ":", "\"entryName\"", ",", "type", ":", "\"string\"", "}", ",", "{", "name", ":", "\"statsObj\"", ",", "type", ":", "\"object\"", "}", "]", ")", ";", "watcherManager", ".", "setDomainManager", "(", "domainManager", ")", ";", "watcherManager", ".", "setWatcherImpl", "(", "watcherImpl", ")", ";", "}" ]
Initialize the "fileWatcher" domain. The fileWatcher domain handles watching and un-watching directories.
[ "Initialize", "the", "fileWatcher", "domain", ".", "The", "fileWatcher", "domain", "handles", "watching", "and", "un", "-", "watching", "directories", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/filesystem/impls/appshell/node/FileWatcherDomain.js#L42-L96
2,504
adobe/brackets
src/extensions/default/AutoUpdate/StateHandler.js
_write
function _write(filePath, json) { var result = $.Deferred(), _file = FileSystem.getFileForPath(filePath); if (_file) { var content = JSON.stringify(json); FileUtils.writeText(_file, content, true) .done(function () { result.resolve(); }) .fail(function (err) { result.reject(); }); } else { result.reject(); } return result.promise(); }
javascript
function _write(filePath, json) { var result = $.Deferred(), _file = FileSystem.getFileForPath(filePath); if (_file) { var content = JSON.stringify(json); FileUtils.writeText(_file, content, true) .done(function () { result.resolve(); }) .fail(function (err) { result.reject(); }); } else { result.reject(); } return result.promise(); }
[ "function", "_write", "(", "filePath", ",", "json", ")", "{", "var", "result", "=", "$", ".", "Deferred", "(", ")", ",", "_file", "=", "FileSystem", ".", "getFileForPath", "(", "filePath", ")", ";", "if", "(", "_file", ")", "{", "var", "content", "=", "JSON", ".", "stringify", "(", "json", ")", ";", "FileUtils", ".", "writeText", "(", "_file", ",", "content", ",", "true", ")", ".", "done", "(", "function", "(", ")", "{", "result", ".", "resolve", "(", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "result", ".", "reject", "(", ")", ";", "}", ")", ";", "}", "else", "{", "result", ".", "reject", "(", ")", ";", "}", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Performs the write of JSON object to a file. @param {string} filepath - path to JSON file @param {object} json - JSON object to write @returns {$.Deferred} - a jquery deferred promise, that is resolved with the write success or failure
[ "Performs", "the", "write", "of", "JSON", "object", "to", "a", "file", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/StateHandler.js#L169-L189
2,505
facebook/relay
packages/relay-compiler/util/dedupeJSONStringify.js
collectDuplicates
function collectDuplicates(value) { if (value == null || typeof value !== 'object') { return; } const metadata = metadataForVal.get(value); // Only consider duplicates with hashes longer than 2 (excludes [] and {}). if (metadata && metadata.value !== value && metadata.hash.length > 2) { metadata.isDuplicate = true; return; } if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { collectDuplicates(value[i]); } } else { for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { collectDuplicates(value[k]); } } } }
javascript
function collectDuplicates(value) { if (value == null || typeof value !== 'object') { return; } const metadata = metadataForVal.get(value); // Only consider duplicates with hashes longer than 2 (excludes [] and {}). if (metadata && metadata.value !== value && metadata.hash.length > 2) { metadata.isDuplicate = true; return; } if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { collectDuplicates(value[i]); } } else { for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { collectDuplicates(value[k]); } } } }
[ "function", "collectDuplicates", "(", "value", ")", "{", "if", "(", "value", "==", "null", "||", "typeof", "value", "!==", "'object'", ")", "{", "return", ";", "}", "const", "metadata", "=", "metadataForVal", ".", "get", "(", "value", ")", ";", "// Only consider duplicates with hashes longer than 2 (excludes [] and {}).", "if", "(", "metadata", "&&", "metadata", ".", "value", "!==", "value", "&&", "metadata", ".", "hash", ".", "length", ">", "2", ")", "{", "metadata", ".", "isDuplicate", "=", "true", ";", "return", ";", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "collectDuplicates", "(", "value", "[", "i", "]", ")", ";", "}", "}", "else", "{", "for", "(", "const", "k", "in", "value", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "k", ")", "&&", "value", "[", "k", "]", "!==", "undefined", ")", "{", "collectDuplicates", "(", "value", "[", "k", "]", ")", ";", "}", "}", "}", "}" ]
Using top-down recursion, linearly scan the JSON tree to determine which values should be deduplicated.
[ "Using", "top", "-", "down", "recursion", "linearly", "scan", "the", "JSON", "tree", "to", "determine", "which", "values", "should", "be", "deduplicated", "." ]
7fb9be5182b9650637d7b92ead9a42713ac30aa4
https://github.com/facebook/relay/blob/7fb9be5182b9650637d7b92ead9a42713ac30aa4/packages/relay-compiler/util/dedupeJSONStringify.js#L66-L87
2,506
facebook/relay
packages/relay-compiler/util/dedupeJSONStringify.js
printJSCode
function printJSCode(isDupedVar, depth, value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } // Only use variable references at depth beyond the top level. if (depth !== '') { const metadata = metadataForVal.get(value); if (metadata && metadata.isDuplicate) { if (!metadata.varName) { const refCode = printJSCode(true, '', value); metadata.varName = 'v' + varDefs.length; varDefs.push(metadata.varName + ' = ' + refCode); } return '(' + metadata.varName + '/*: any*/)'; } } let str; let isEmpty = true; const depth2 = depth + ' '; if (Array.isArray(value)) { // Empty arrays can only have one inferred flow type and then conflict if // used in different places, this is unsound if we would write to them but // this whole module is based on the idea of a read only JSON tree. if (isDupedVar && value.length === 0) { return '([]/*: any*/)'; } str = '['; for (let i = 0; i < value.length; i++) { str += (isEmpty ? '\n' : ',\n') + depth2 + printJSCode(isDupedVar, depth2, value[i]); isEmpty = false; } str += isEmpty ? ']' : `\n${depth}]`; } else { str = '{'; for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { str += (isEmpty ? '\n' : ',\n') + depth2 + JSON.stringify(k) + ': ' + printJSCode(isDupedVar, depth2, value[k]); isEmpty = false; } } str += isEmpty ? '}' : `\n${depth}}`; } return str; }
javascript
function printJSCode(isDupedVar, depth, value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } // Only use variable references at depth beyond the top level. if (depth !== '') { const metadata = metadataForVal.get(value); if (metadata && metadata.isDuplicate) { if (!metadata.varName) { const refCode = printJSCode(true, '', value); metadata.varName = 'v' + varDefs.length; varDefs.push(metadata.varName + ' = ' + refCode); } return '(' + metadata.varName + '/*: any*/)'; } } let str; let isEmpty = true; const depth2 = depth + ' '; if (Array.isArray(value)) { // Empty arrays can only have one inferred flow type and then conflict if // used in different places, this is unsound if we would write to them but // this whole module is based on the idea of a read only JSON tree. if (isDupedVar && value.length === 0) { return '([]/*: any*/)'; } str = '['; for (let i = 0; i < value.length; i++) { str += (isEmpty ? '\n' : ',\n') + depth2 + printJSCode(isDupedVar, depth2, value[i]); isEmpty = false; } str += isEmpty ? ']' : `\n${depth}]`; } else { str = '{'; for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { str += (isEmpty ? '\n' : ',\n') + depth2 + JSON.stringify(k) + ': ' + printJSCode(isDupedVar, depth2, value[k]); isEmpty = false; } } str += isEmpty ? '}' : `\n${depth}}`; } return str; }
[ "function", "printJSCode", "(", "isDupedVar", ",", "depth", ",", "value", ")", "{", "if", "(", "value", "==", "null", "||", "typeof", "value", "!==", "'object'", ")", "{", "return", "JSON", ".", "stringify", "(", "value", ")", ";", "}", "// Only use variable references at depth beyond the top level.", "if", "(", "depth", "!==", "''", ")", "{", "const", "metadata", "=", "metadataForVal", ".", "get", "(", "value", ")", ";", "if", "(", "metadata", "&&", "metadata", ".", "isDuplicate", ")", "{", "if", "(", "!", "metadata", ".", "varName", ")", "{", "const", "refCode", "=", "printJSCode", "(", "true", ",", "''", ",", "value", ")", ";", "metadata", ".", "varName", "=", "'v'", "+", "varDefs", ".", "length", ";", "varDefs", ".", "push", "(", "metadata", ".", "varName", "+", "' = '", "+", "refCode", ")", ";", "}", "return", "'('", "+", "metadata", ".", "varName", "+", "'/*: any*/)'", ";", "}", "}", "let", "str", ";", "let", "isEmpty", "=", "true", ";", "const", "depth2", "=", "depth", "+", "' '", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "// Empty arrays can only have one inferred flow type and then conflict if", "// used in different places, this is unsound if we would write to them but", "// this whole module is based on the idea of a read only JSON tree.", "if", "(", "isDupedVar", "&&", "value", ".", "length", "===", "0", ")", "{", "return", "'([]/*: any*/)'", ";", "}", "str", "=", "'['", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "str", "+=", "(", "isEmpty", "?", "'\\n'", ":", "',\\n'", ")", "+", "depth2", "+", "printJSCode", "(", "isDupedVar", ",", "depth2", ",", "value", "[", "i", "]", ")", ";", "isEmpty", "=", "false", ";", "}", "str", "+=", "isEmpty", "?", "']'", ":", "`", "\\n", "${", "depth", "}", "`", ";", "}", "else", "{", "str", "=", "'{'", ";", "for", "(", "const", "k", "in", "value", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "k", ")", "&&", "value", "[", "k", "]", "!==", "undefined", ")", "{", "str", "+=", "(", "isEmpty", "?", "'\\n'", ":", "',\\n'", ")", "+", "depth2", "+", "JSON", ".", "stringify", "(", "k", ")", "+", "': '", "+", "printJSCode", "(", "isDupedVar", ",", "depth2", ",", "value", "[", "k", "]", ")", ";", "isEmpty", "=", "false", ";", "}", "}", "str", "+=", "isEmpty", "?", "'}'", ":", "`", "\\n", "${", "depth", "}", "`", ";", "}", "return", "str", ";", "}" ]
Stringify JS, replacing duplicates with variable references.
[ "Stringify", "JS", "replacing", "duplicates", "with", "variable", "references", "." ]
7fb9be5182b9650637d7b92ead9a42713ac30aa4
https://github.com/facebook/relay/blob/7fb9be5182b9650637d7b92ead9a42713ac30aa4/packages/relay-compiler/util/dedupeJSONStringify.js#L90-L141
2,507
facebook/relay
scripts/rewrite-modules.js
mapModule
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV === 'test') { return; } return './' + path.basename(module); }
javascript
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV === 'test') { return; } return './' + path.basename(module); }
[ "function", "mapModule", "(", "state", ",", "module", ")", "{", "var", "moduleMap", "=", "state", ".", "opts", ".", "map", "||", "{", "}", ";", "if", "(", "moduleMap", ".", "hasOwnProperty", "(", "module", ")", ")", "{", "return", "moduleMap", "[", "module", "]", ";", "}", "// Jest understands the haste module system, so leave modules intact.", "if", "(", "process", ".", "env", ".", "NODE_ENV", "===", "'test'", ")", "{", "return", ";", "}", "return", "'./'", "+", "path", ".", "basename", "(", "module", ")", ";", "}" ]
This file is a fork from fbjs's transform of the same name. It has been modified to also apply to import statements, and to account for relative file names in require statements. Rewrites module string literals according to the `map` and `prefix` options. This allows other npm packages to be published and used directly without being a part of the same build.
[ "This", "file", "is", "a", "fork", "from", "fbjs", "s", "transform", "of", "the", "same", "name", ".", "It", "has", "been", "modified", "to", "also", "apply", "to", "import", "statements", "and", "to", "account", "for", "relative", "file", "names", "in", "require", "statements", ".", "Rewrites", "module", "string", "literals", "according", "to", "the", "map", "and", "prefix", "options", ".", "This", "allows", "other", "npm", "packages", "to", "be", "published", "and", "used", "directly", "without", "being", "a", "part", "of", "the", "same", "build", "." ]
7fb9be5182b9650637d7b92ead9a42713ac30aa4
https://github.com/facebook/relay/blob/7fb9be5182b9650637d7b92ead9a42713ac30aa4/scripts/rewrite-modules.js#L25-L35
2,508
lovell/sharp
lib/utility.js
cache
function cache (options) { if (is.bool(options)) { if (options) { // Default cache settings of 50MB, 20 files, 100 items return sharp.cache(50, 20, 100); } else { return sharp.cache(0, 0, 0); } } else if (is.object(options)) { return sharp.cache(options.memory, options.files, options.items); } else { return sharp.cache(); } }
javascript
function cache (options) { if (is.bool(options)) { if (options) { // Default cache settings of 50MB, 20 files, 100 items return sharp.cache(50, 20, 100); } else { return sharp.cache(0, 0, 0); } } else if (is.object(options)) { return sharp.cache(options.memory, options.files, options.items); } else { return sharp.cache(); } }
[ "function", "cache", "(", "options", ")", "{", "if", "(", "is", ".", "bool", "(", "options", ")", ")", "{", "if", "(", "options", ")", "{", "// Default cache settings of 50MB, 20 files, 100 items", "return", "sharp", ".", "cache", "(", "50", ",", "20", ",", "100", ")", ";", "}", "else", "{", "return", "sharp", ".", "cache", "(", "0", ",", "0", ",", "0", ")", ";", "}", "}", "else", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "return", "sharp", ".", "cache", "(", "options", ".", "memory", ",", "options", ".", "files", ",", "options", ".", "items", ")", ";", "}", "else", "{", "return", "sharp", ".", "cache", "(", ")", ";", "}", "}" ]
Gets or, when options are provided, sets the limits of _libvips'_ operation cache. Existing entries in the cache will be trimmed after any change in limits. This method always returns cache statistics, useful for determining how much working memory is required for a particular task. @example const stats = sharp.cache(); @example sharp.cache( { items: 200 } ); sharp.cache( { files: 0 } ); sharp.cache(false); @param {Object|Boolean} [options=true] - Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching @param {Number} [options.memory=50] - is the maximum memory in MB to use for this cache @param {Number} [options.files=20] - is the maximum number of files to hold open @param {Number} [options.items=100] - is the maximum number of operations to cache @returns {Object}
[ "Gets", "or", "when", "options", "are", "provided", "sets", "the", "limits", "of", "_libvips", "_", "operation", "cache", ".", "Existing", "entries", "in", "the", "cache", "will", "be", "trimmed", "after", "any", "change", "in", "limits", ".", "This", "method", "always", "returns", "cache", "statistics", "useful", "for", "determining", "how", "much", "working", "memory", "is", "required", "for", "a", "particular", "task", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/utility.js#L25-L38
2,509
lovell/sharp
lib/channel.js
extractChannel
function extractChannel (channel) { if (channel === 'red') { channel = 0; } else if (channel === 'green') { channel = 1; } else if (channel === 'blue') { channel = 2; } if (is.integer(channel) && is.inRange(channel, 0, 4)) { this.options.extractChannel = channel; } else { throw new Error('Cannot extract invalid channel ' + channel); } return this; }
javascript
function extractChannel (channel) { if (channel === 'red') { channel = 0; } else if (channel === 'green') { channel = 1; } else if (channel === 'blue') { channel = 2; } if (is.integer(channel) && is.inRange(channel, 0, 4)) { this.options.extractChannel = channel; } else { throw new Error('Cannot extract invalid channel ' + channel); } return this; }
[ "function", "extractChannel", "(", "channel", ")", "{", "if", "(", "channel", "===", "'red'", ")", "{", "channel", "=", "0", ";", "}", "else", "if", "(", "channel", "===", "'green'", ")", "{", "channel", "=", "1", ";", "}", "else", "if", "(", "channel", "===", "'blue'", ")", "{", "channel", "=", "2", ";", "}", "if", "(", "is", ".", "integer", "(", "channel", ")", "&&", "is", ".", "inRange", "(", "channel", ",", "0", ",", "4", ")", ")", "{", "this", ".", "options", ".", "extractChannel", "=", "channel", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Cannot extract invalid channel '", "+", "channel", ")", ";", "}", "return", "this", ";", "}" ]
Extract a single channel from a multi-channel image. @example sharp(input) .extractChannel('green') .toFile('input_green.jpg', function(err, info) { // info.channels === 1 // input_green.jpg contains the green channel of the input image }); @param {Number|String} channel - zero-indexed band number to extract, or `red`, `green` or `blue` as alternative to `0`, `1` or `2` respectively. @returns {Sharp} @throws {Error} Invalid channel
[ "Extract", "a", "single", "channel", "from", "a", "multi", "-", "channel", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/channel.js#L64-L78
2,510
lovell/sharp
lib/input.js
_write
function _write (chunk, encoding, callback) { /* istanbul ignore else */ if (Array.isArray(this.options.input.buffer)) { /* istanbul ignore else */ if (is.buffer(chunk)) { if (this.options.input.buffer.length === 0) { const that = this; this.on('finish', function () { that.streamInFinished = true; }); } this.options.input.buffer.push(chunk); callback(); } else { callback(new Error('Non-Buffer data on Writable Stream')); } } else { callback(new Error('Unexpected data on Writable Stream')); } }
javascript
function _write (chunk, encoding, callback) { /* istanbul ignore else */ if (Array.isArray(this.options.input.buffer)) { /* istanbul ignore else */ if (is.buffer(chunk)) { if (this.options.input.buffer.length === 0) { const that = this; this.on('finish', function () { that.streamInFinished = true; }); } this.options.input.buffer.push(chunk); callback(); } else { callback(new Error('Non-Buffer data on Writable Stream')); } } else { callback(new Error('Unexpected data on Writable Stream')); } }
[ "function", "_write", "(", "chunk", ",", "encoding", ",", "callback", ")", "{", "/* istanbul ignore else */", "if", "(", "Array", ".", "isArray", "(", "this", ".", "options", ".", "input", ".", "buffer", ")", ")", "{", "/* istanbul ignore else */", "if", "(", "is", ".", "buffer", "(", "chunk", ")", ")", "{", "if", "(", "this", ".", "options", ".", "input", ".", "buffer", ".", "length", "===", "0", ")", "{", "const", "that", "=", "this", ";", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "that", ".", "streamInFinished", "=", "true", ";", "}", ")", ";", "}", "this", ".", "options", ".", "input", ".", "buffer", ".", "push", "(", "chunk", ")", ";", "callback", "(", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "'Non-Buffer data on Writable Stream'", ")", ")", ";", "}", "}", "else", "{", "callback", "(", "new", "Error", "(", "'Unexpected data on Writable Stream'", ")", ")", ";", "}", "}" ]
Handle incoming Buffer chunk on Writable Stream. @private @param {Buffer} chunk @param {String} encoding - unused @param {Function} callback
[ "Handle", "incoming", "Buffer", "chunk", "on", "Writable", "Stream", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/input.js#L112-L131
2,511
lovell/sharp
lib/input.js
_flattenBufferIn
function _flattenBufferIn () { if (this._isStreamInput()) { this.options.input.buffer = Buffer.concat(this.options.input.buffer); } }
javascript
function _flattenBufferIn () { if (this._isStreamInput()) { this.options.input.buffer = Buffer.concat(this.options.input.buffer); } }
[ "function", "_flattenBufferIn", "(", ")", "{", "if", "(", "this", ".", "_isStreamInput", "(", ")", ")", "{", "this", ".", "options", ".", "input", ".", "buffer", "=", "Buffer", ".", "concat", "(", "this", ".", "options", ".", "input", ".", "buffer", ")", ";", "}", "}" ]
Flattens the array of chunks accumulated in input.buffer. @private
[ "Flattens", "the", "array", "of", "chunks", "accumulated", "in", "input", ".", "buffer", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/input.js#L137-L141
2,512
lovell/sharp
lib/input.js
clone
function clone () { const that = this; // Clone existing options const clone = this.constructor.call(); clone.options = Object.assign({}, this.options); // Pass 'finish' event to clone for Stream-based input if (this._isStreamInput()) { this.on('finish', function () { // Clone inherits input data that._flattenBufferIn(); clone.options.bufferIn = that.options.bufferIn; clone.emit('finish'); }); } return clone; }
javascript
function clone () { const that = this; // Clone existing options const clone = this.constructor.call(); clone.options = Object.assign({}, this.options); // Pass 'finish' event to clone for Stream-based input if (this._isStreamInput()) { this.on('finish', function () { // Clone inherits input data that._flattenBufferIn(); clone.options.bufferIn = that.options.bufferIn; clone.emit('finish'); }); } return clone; }
[ "function", "clone", "(", ")", "{", "const", "that", "=", "this", ";", "// Clone existing options", "const", "clone", "=", "this", ".", "constructor", ".", "call", "(", ")", ";", "clone", ".", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "this", ".", "options", ")", ";", "// Pass 'finish' event to clone for Stream-based input", "if", "(", "this", ".", "_isStreamInput", "(", ")", ")", "{", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "// Clone inherits input data", "that", ".", "_flattenBufferIn", "(", ")", ";", "clone", ".", "options", ".", "bufferIn", "=", "that", ".", "options", ".", "bufferIn", ";", "clone", ".", "emit", "(", "'finish'", ")", ";", "}", ")", ";", "}", "return", "clone", ";", "}" ]
Take a "snapshot" of the Sharp instance, returning a new instance. Cloned instances inherit the input of their parent instance. This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. @example const pipeline = sharp().rotate(); pipeline.clone().resize(800, 600).pipe(firstWritableStream); pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream); readableStream.pipe(pipeline); // firstWritableStream receives auto-rotated, resized readableStream // secondWritableStream receives auto-rotated, extracted region of readableStream @returns {Sharp}
[ "Take", "a", "snapshot", "of", "the", "Sharp", "instance", "returning", "a", "new", "instance", ".", "Cloned", "instances", "inherit", "the", "input", "of", "their", "parent", "instance", ".", "This", "allows", "multiple", "output", "Streams", "and", "therefore", "multiple", "processing", "pipelines", "to", "share", "a", "single", "input", "Stream", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/input.js#L167-L182
2,513
lovell/sharp
lib/input.js
stats
function stats (callback) { const that = this; if (is.fn(callback)) { if (this._isStreamInput()) { this.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, callback); }); } else { sharp.stats(this.options, callback); } return this; } else { if (this._isStreamInput()) { return new Promise(function (resolve, reject) { that.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); }); } else { return new Promise(function (resolve, reject) { sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); } } }
javascript
function stats (callback) { const that = this; if (is.fn(callback)) { if (this._isStreamInput()) { this.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, callback); }); } else { sharp.stats(this.options, callback); } return this; } else { if (this._isStreamInput()) { return new Promise(function (resolve, reject) { that.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); }); } else { return new Promise(function (resolve, reject) { sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); } } }
[ "function", "stats", "(", "callback", ")", "{", "const", "that", "=", "this", ";", "if", "(", "is", ".", "fn", "(", "callback", ")", ")", "{", "if", "(", "this", ".", "_isStreamInput", "(", ")", ")", "{", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "that", ".", "_flattenBufferIn", "(", ")", ";", "sharp", ".", "stats", "(", "that", ".", "options", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "sharp", ".", "stats", "(", "this", ".", "options", ",", "callback", ")", ";", "}", "return", "this", ";", "}", "else", "{", "if", "(", "this", ".", "_isStreamInput", "(", ")", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "that", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "that", ".", "_flattenBufferIn", "(", ")", ";", "sharp", ".", "stats", "(", "that", ".", "options", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "stats", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "sharp", ".", "stats", "(", "that", ".", "options", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "stats", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", "}" ]
Access to pixel-derived image statistics for every channel in the image. A `Promise` is returned when `callback` is not provided. - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains - `min` (minimum value in the channel) - `max` (maximum value in the channel) - `sum` (sum of all values in a channel) - `squaresSum` (sum of squared values in a channel) - `mean` (mean of the values in a channel) - `stdev` (standard deviation for the values in a channel) - `minX` (x-coordinate of one of the pixel where the minimum lies) - `minY` (y-coordinate of one of the pixel where the minimum lies) - `maxX` (x-coordinate of one of the pixel where the maximum lies) - `maxY` (y-coordinate of one of the pixel where the maximum lies) - `isOpaque`: Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) @example const image = sharp(inputJpg); image .stats() .then(function(stats) { // stats contains the channel-wise statistics array and the isOpaque value }); @param {Function} [callback] - called with the arguments `(err, stats)` @returns {Promise<Object>}
[ "Access", "to", "pixel", "-", "derived", "image", "statistics", "for", "every", "channel", "in", "the", "image", ".", "A", "Promise", "is", "returned", "when", "callback", "is", "not", "provided", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/input.js#L294-L332
2,514
lovell/sharp
lib/output.js
toFile
function toFile (fileOut, callback) { if (!fileOut || fileOut.length === 0) { const errOutputInvalid = new Error('Missing output file path'); if (is.fn(callback)) { callback(errOutputInvalid); } else { return Promise.reject(errOutputInvalid); } } else { if (this.options.input.file === fileOut) { const errOutputIsInput = new Error('Cannot use same file for input and output'); if (is.fn(callback)) { callback(errOutputIsInput); } else { return Promise.reject(errOutputIsInput); } } else { this.options.fileOut = fileOut; return this._pipeline(callback); } } return this; }
javascript
function toFile (fileOut, callback) { if (!fileOut || fileOut.length === 0) { const errOutputInvalid = new Error('Missing output file path'); if (is.fn(callback)) { callback(errOutputInvalid); } else { return Promise.reject(errOutputInvalid); } } else { if (this.options.input.file === fileOut) { const errOutputIsInput = new Error('Cannot use same file for input and output'); if (is.fn(callback)) { callback(errOutputIsInput); } else { return Promise.reject(errOutputIsInput); } } else { this.options.fileOut = fileOut; return this._pipeline(callback); } } return this; }
[ "function", "toFile", "(", "fileOut", ",", "callback", ")", "{", "if", "(", "!", "fileOut", "||", "fileOut", ".", "length", "===", "0", ")", "{", "const", "errOutputInvalid", "=", "new", "Error", "(", "'Missing output file path'", ")", ";", "if", "(", "is", ".", "fn", "(", "callback", ")", ")", "{", "callback", "(", "errOutputInvalid", ")", ";", "}", "else", "{", "return", "Promise", ".", "reject", "(", "errOutputInvalid", ")", ";", "}", "}", "else", "{", "if", "(", "this", ".", "options", ".", "input", ".", "file", "===", "fileOut", ")", "{", "const", "errOutputIsInput", "=", "new", "Error", "(", "'Cannot use same file for input and output'", ")", ";", "if", "(", "is", ".", "fn", "(", "callback", ")", ")", "{", "callback", "(", "errOutputIsInput", ")", ";", "}", "else", "{", "return", "Promise", ".", "reject", "(", "errOutputIsInput", ")", ";", "}", "}", "else", "{", "this", ".", "options", ".", "fileOut", "=", "fileOut", ";", "return", "this", ".", "_pipeline", "(", "callback", ")", ";", "}", "}", "return", "this", ";", "}" ]
Write output image data to a file. If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, TIFF, DZI, and libvips' V format supported. Note that raw pixel data is only supported for buffer output. A `Promise` is returned when `callback` is not provided. @example sharp(input) .toFile('output.png', (err, info) => { ... }); @example sharp(input) .toFile('output.png') .then(info => { ... }) .catch(err => { ... }); @param {String} fileOut - the path to write the image data to. @param {Function} [callback] - called on completion with two arguments `(err, info)`. `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. @returns {Promise<Object>} - when no callback is provided @throws {Error} Invalid parameters
[ "Write", "output", "image", "data", "to", "a", "file", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L33-L55
2,515
lovell/sharp
lib/output.js
toBuffer
function toBuffer (options, callback) { if (is.object(options)) { if (is.bool(options.resolveWithObject)) { this.options.resolveWithObject = options.resolveWithObject; } } return this._pipeline(is.fn(options) ? options : callback); }
javascript
function toBuffer (options, callback) { if (is.object(options)) { if (is.bool(options.resolveWithObject)) { this.options.resolveWithObject = options.resolveWithObject; } } return this._pipeline(is.fn(options) ? options : callback); }
[ "function", "toBuffer", "(", "options", ",", "callback", ")", "{", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "if", "(", "is", ".", "bool", "(", "options", ".", "resolveWithObject", ")", ")", "{", "this", ".", "options", ".", "resolveWithObject", "=", "options", ".", "resolveWithObject", ";", "}", "}", "return", "this", ".", "_pipeline", "(", "is", ".", "fn", "(", "options", ")", "?", "options", ":", "callback", ")", ";", "}" ]
Write output to a Buffer. JPEG, PNG, WebP, TIFF and RAW output are supported. By default, the format will match the input image, except GIF and SVG input which become PNG output. `callback`, if present, gets three arguments `(err, data, info)` where: - `err` is an error, if any. - `data` is the output image data. - `info` contains the output image `format`, `size` (bytes), `width`, `height`, `channels` and `premultiplied` (indicating if premultiplication was used). When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. A `Promise` is returned when `callback` is not provided. @example sharp(input) .toBuffer((err, data, info) => { ... }); @example sharp(input) .toBuffer() .then(data => { ... }) .catch(err => { ... }); @example sharp(input) .toBuffer({ resolveWithObject: true }) .then(({ data, info }) => { ... }) .catch(err => { ... }); @param {Object} [options] @param {Boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. @param {Function} [callback] @returns {Promise<Buffer>} - when no callback is provided
[ "Write", "output", "to", "a", "Buffer", ".", "JPEG", "PNG", "WebP", "TIFF", "and", "RAW", "output", "are", "supported", ".", "By", "default", "the", "format", "will", "match", "the", "input", "image", "except", "GIF", "and", "SVG", "input", "which", "become", "PNG", "output", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L92-L99
2,516
lovell/sharp
lib/output.js
jpeg
function jpeg (options) { if (is.object(options)) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.jpegQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.defined(options.progressive)) { this._setBooleanOption('jpegProgressive', options.progressive); } if (is.defined(options.chromaSubsampling)) { if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { this.options.jpegChromaSubsampling = options.chromaSubsampling; } else { throw new Error('Invalid chromaSubsampling (4:2:0, 4:4:4) ' + options.chromaSubsampling); } } const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; if (is.defined(trellisQuantisation)) { this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); } if (is.defined(options.overshootDeringing)) { this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); } const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; if (is.defined(optimiseScans)) { this._setBooleanOption('jpegOptimiseScans', optimiseScans); if (optimiseScans) { this.options.jpegProgressive = true; } } const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; if (is.defined(optimiseCoding)) { this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); } const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; if (is.defined(quantisationTable)) { if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { this.options.jpegQuantisationTable = quantisationTable; } else { throw new Error('Invalid quantisation table (integer, 0-8) ' + quantisationTable); } } } return this._updateFormatOut('jpeg', options); }
javascript
function jpeg (options) { if (is.object(options)) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.jpegQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.defined(options.progressive)) { this._setBooleanOption('jpegProgressive', options.progressive); } if (is.defined(options.chromaSubsampling)) { if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { this.options.jpegChromaSubsampling = options.chromaSubsampling; } else { throw new Error('Invalid chromaSubsampling (4:2:0, 4:4:4) ' + options.chromaSubsampling); } } const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; if (is.defined(trellisQuantisation)) { this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); } if (is.defined(options.overshootDeringing)) { this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); } const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; if (is.defined(optimiseScans)) { this._setBooleanOption('jpegOptimiseScans', optimiseScans); if (optimiseScans) { this.options.jpegProgressive = true; } } const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; if (is.defined(optimiseCoding)) { this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); } const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; if (is.defined(quantisationTable)) { if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { this.options.jpegQuantisationTable = quantisationTable; } else { throw new Error('Invalid quantisation table (integer, 0-8) ' + quantisationTable); } } } return this._updateFormatOut('jpeg', options); }
[ "function", "jpeg", "(", "options", ")", "{", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "if", "(", "is", ".", "defined", "(", "options", ".", "quality", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "quality", ")", "&&", "is", ".", "inRange", "(", "options", ".", "quality", ",", "1", ",", "100", ")", ")", "{", "this", ".", "options", ".", "jpegQuality", "=", "options", ".", "quality", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid quality (integer, 1-100) '", "+", "options", ".", "quality", ")", ";", "}", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "progressive", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'jpegProgressive'", ",", "options", ".", "progressive", ")", ";", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "chromaSubsampling", ")", ")", "{", "if", "(", "is", ".", "string", "(", "options", ".", "chromaSubsampling", ")", "&&", "is", ".", "inArray", "(", "options", ".", "chromaSubsampling", ",", "[", "'4:2:0'", ",", "'4:4:4'", "]", ")", ")", "{", "this", ".", "options", ".", "jpegChromaSubsampling", "=", "options", ".", "chromaSubsampling", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid chromaSubsampling (4:2:0, 4:4:4) '", "+", "options", ".", "chromaSubsampling", ")", ";", "}", "}", "const", "trellisQuantisation", "=", "is", ".", "bool", "(", "options", ".", "trellisQuantization", ")", "?", "options", ".", "trellisQuantization", ":", "options", ".", "trellisQuantisation", ";", "if", "(", "is", ".", "defined", "(", "trellisQuantisation", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'jpegTrellisQuantisation'", ",", "trellisQuantisation", ")", ";", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "overshootDeringing", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'jpegOvershootDeringing'", ",", "options", ".", "overshootDeringing", ")", ";", "}", "const", "optimiseScans", "=", "is", ".", "bool", "(", "options", ".", "optimizeScans", ")", "?", "options", ".", "optimizeScans", ":", "options", ".", "optimiseScans", ";", "if", "(", "is", ".", "defined", "(", "optimiseScans", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'jpegOptimiseScans'", ",", "optimiseScans", ")", ";", "if", "(", "optimiseScans", ")", "{", "this", ".", "options", ".", "jpegProgressive", "=", "true", ";", "}", "}", "const", "optimiseCoding", "=", "is", ".", "bool", "(", "options", ".", "optimizeCoding", ")", "?", "options", ".", "optimizeCoding", ":", "options", ".", "optimiseCoding", ";", "if", "(", "is", ".", "defined", "(", "optimiseCoding", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'jpegOptimiseCoding'", ",", "optimiseCoding", ")", ";", "}", "const", "quantisationTable", "=", "is", ".", "number", "(", "options", ".", "quantizationTable", ")", "?", "options", ".", "quantizationTable", ":", "options", ".", "quantisationTable", ";", "if", "(", "is", ".", "defined", "(", "quantisationTable", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "quantisationTable", ")", "&&", "is", ".", "inRange", "(", "quantisationTable", ",", "0", ",", "8", ")", ")", "{", "this", ".", "options", ".", "jpegQuantisationTable", "=", "quantisationTable", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid quantisation table (integer, 0-8) '", "+", "quantisationTable", ")", ";", "}", "}", "}", "return", "this", ".", "_updateFormatOut", "(", "'jpeg'", ",", "options", ")", ";", "}" ]
Use these JPEG options for output image. @example // Convert any input to very high quality JPEG output const data = await sharp(input) .jpeg({ quality: 100, chromaSubsampling: '4:4:4' }) .toBuffer(); @param {Object} [options] - output options @param {Number} [options.quality=80] - quality, integer 1-100 @param {Boolean} [options.progressive=false] - use progressive (interlace) scan @param {String} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling when quality <= 90 @param {Boolean} [options.trellisQuantisation=false] - apply trellis quantisation, requires libvips compiled with support for mozjpeg @param {Boolean} [options.overshootDeringing=false] - apply overshoot deringing, requires libvips compiled with support for mozjpeg @param {Boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive, requires libvips compiled with support for mozjpeg @param {Boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans @param {Boolean} [options.optimiseCoding=true] - optimise Huffman coding tables @param {Boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding @param {Number} [options.quantisationTable=0] - quantization table to use, integer 0-8, requires libvips compiled with support for mozjpeg @param {Number} [options.quantizationTable=0] - alternative spelling of quantisationTable @param {Boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format @returns {Sharp} @throws {Error} Invalid options
[ "Use", "these", "JPEG", "options", "for", "output", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L159-L206
2,517
lovell/sharp
lib/output.js
png
function png (options) { if (is.object(options)) { if (is.defined(options.progressive)) { this._setBooleanOption('pngProgressive', options.progressive); } if (is.defined(options.compressionLevel)) { if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { this.options.pngCompressionLevel = options.compressionLevel; } else { throw new Error('Invalid compressionLevel (integer, 0-9) ' + options.compressionLevel); } } if (is.defined(options.adaptiveFiltering)) { this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); } if (is.defined(options.palette)) { this._setBooleanOption('pngPalette', options.palette); if (this.options.pngPalette) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { this.options.pngQuality = options.quality; } else { throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); } } const colours = options.colours || options.colors; if (is.defined(colours)) { if (is.integer(colours) && is.inRange(colours, 2, 256)) { this.options.pngColours = colours; } else { throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); } } if (is.defined(options.dither)) { if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { this.options.pngDither = options.dither; } else { throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); } } } } } return this._updateFormatOut('png', options); }
javascript
function png (options) { if (is.object(options)) { if (is.defined(options.progressive)) { this._setBooleanOption('pngProgressive', options.progressive); } if (is.defined(options.compressionLevel)) { if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { this.options.pngCompressionLevel = options.compressionLevel; } else { throw new Error('Invalid compressionLevel (integer, 0-9) ' + options.compressionLevel); } } if (is.defined(options.adaptiveFiltering)) { this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); } if (is.defined(options.palette)) { this._setBooleanOption('pngPalette', options.palette); if (this.options.pngPalette) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { this.options.pngQuality = options.quality; } else { throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); } } const colours = options.colours || options.colors; if (is.defined(colours)) { if (is.integer(colours) && is.inRange(colours, 2, 256)) { this.options.pngColours = colours; } else { throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); } } if (is.defined(options.dither)) { if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { this.options.pngDither = options.dither; } else { throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); } } } } } return this._updateFormatOut('png', options); }
[ "function", "png", "(", "options", ")", "{", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "if", "(", "is", ".", "defined", "(", "options", ".", "progressive", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'pngProgressive'", ",", "options", ".", "progressive", ")", ";", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "compressionLevel", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "compressionLevel", ")", "&&", "is", ".", "inRange", "(", "options", ".", "compressionLevel", ",", "0", ",", "9", ")", ")", "{", "this", ".", "options", ".", "pngCompressionLevel", "=", "options", ".", "compressionLevel", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid compressionLevel (integer, 0-9) '", "+", "options", ".", "compressionLevel", ")", ";", "}", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "adaptiveFiltering", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'pngAdaptiveFiltering'", ",", "options", ".", "adaptiveFiltering", ")", ";", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "palette", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'pngPalette'", ",", "options", ".", "palette", ")", ";", "if", "(", "this", ".", "options", ".", "pngPalette", ")", "{", "if", "(", "is", ".", "defined", "(", "options", ".", "quality", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "quality", ")", "&&", "is", ".", "inRange", "(", "options", ".", "quality", ",", "0", ",", "100", ")", ")", "{", "this", ".", "options", ".", "pngQuality", "=", "options", ".", "quality", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'quality'", ",", "'integer between 0 and 100'", ",", "options", ".", "quality", ")", ";", "}", "}", "const", "colours", "=", "options", ".", "colours", "||", "options", ".", "colors", ";", "if", "(", "is", ".", "defined", "(", "colours", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "colours", ")", "&&", "is", ".", "inRange", "(", "colours", ",", "2", ",", "256", ")", ")", "{", "this", ".", "options", ".", "pngColours", "=", "colours", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'colours'", ",", "'integer between 2 and 256'", ",", "colours", ")", ";", "}", "}", "if", "(", "is", ".", "defined", "(", "options", ".", "dither", ")", ")", "{", "if", "(", "is", ".", "number", "(", "options", ".", "dither", ")", "&&", "is", ".", "inRange", "(", "options", ".", "dither", ",", "0", ",", "1", ")", ")", "{", "this", ".", "options", ".", "pngDither", "=", "options", ".", "dither", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'dither'", ",", "'number between 0.0 and 1.0'", ",", "options", ".", "dither", ")", ";", "}", "}", "}", "}", "}", "return", "this", ".", "_updateFormatOut", "(", "'png'", ",", "options", ")", ";", "}" ]
Use these PNG options for output image. PNG output is always full colour at 8 or 16 bits per pixel. Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. @example // Convert any input to PNG output const data = await sharp(input) .png() .toBuffer(); @param {Object} [options] @param {Boolean} [options.progressive=false] - use progressive (interlace) scan @param {Number} [options.compressionLevel=9] - zlib compression level, 0-9 @param {Boolean} [options.adaptiveFiltering=false] - use adaptive row filtering @param {Boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support, requires libvips compiled with support for libimagequant @param {Number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, requires libvips compiled with support for libimagequant @param {Number} [options.colours=256] - maximum number of palette entries, requires libvips compiled with support for libimagequant @param {Number} [options.colors=256] - alternative spelling of `options.colours`, requires libvips compiled with support for libimagequant @param {Number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, requires libvips compiled with support for libimagequant @param {Boolean} [options.force=true] - force PNG output, otherwise attempt to use input format @returns {Sharp} @throws {Error} Invalid options
[ "Use", "these", "PNG", "options", "for", "output", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L233-L277
2,518
lovell/sharp
lib/output.js
webp
function webp (options) { if (is.object(options) && is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.webpQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.object(options) && is.defined(options.alphaQuality)) { if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { this.options.webpAlphaQuality = options.alphaQuality; } else { throw new Error('Invalid webp alpha quality (integer, 0-100) ' + options.alphaQuality); } } if (is.object(options) && is.defined(options.lossless)) { this._setBooleanOption('webpLossless', options.lossless); } if (is.object(options) && is.defined(options.nearLossless)) { this._setBooleanOption('webpNearLossless', options.nearLossless); } return this._updateFormatOut('webp', options); }
javascript
function webp (options) { if (is.object(options) && is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.webpQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.object(options) && is.defined(options.alphaQuality)) { if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { this.options.webpAlphaQuality = options.alphaQuality; } else { throw new Error('Invalid webp alpha quality (integer, 0-100) ' + options.alphaQuality); } } if (is.object(options) && is.defined(options.lossless)) { this._setBooleanOption('webpLossless', options.lossless); } if (is.object(options) && is.defined(options.nearLossless)) { this._setBooleanOption('webpNearLossless', options.nearLossless); } return this._updateFormatOut('webp', options); }
[ "function", "webp", "(", "options", ")", "{", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "is", ".", "defined", "(", "options", ".", "quality", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "quality", ")", "&&", "is", ".", "inRange", "(", "options", ".", "quality", ",", "1", ",", "100", ")", ")", "{", "this", ".", "options", ".", "webpQuality", "=", "options", ".", "quality", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid quality (integer, 1-100) '", "+", "options", ".", "quality", ")", ";", "}", "}", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "is", ".", "defined", "(", "options", ".", "alphaQuality", ")", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "alphaQuality", ")", "&&", "is", ".", "inRange", "(", "options", ".", "alphaQuality", ",", "0", ",", "100", ")", ")", "{", "this", ".", "options", ".", "webpAlphaQuality", "=", "options", ".", "alphaQuality", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid webp alpha quality (integer, 0-100) '", "+", "options", ".", "alphaQuality", ")", ";", "}", "}", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "is", ".", "defined", "(", "options", ".", "lossless", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'webpLossless'", ",", "options", ".", "lossless", ")", ";", "}", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "is", ".", "defined", "(", "options", ".", "nearLossless", ")", ")", "{", "this", ".", "_setBooleanOption", "(", "'webpNearLossless'", ",", "options", ".", "nearLossless", ")", ";", "}", "return", "this", ".", "_updateFormatOut", "(", "'webp'", ",", "options", ")", ";", "}" ]
Use these WebP options for output image. @example // Convert any input to lossless WebP output const data = await sharp(input) .webp({ lossless: true }) .toBuffer(); @param {Object} [options] - output options @param {Number} [options.quality=80] - quality, integer 1-100 @param {Number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100 @param {Boolean} [options.lossless=false] - use lossless compression mode @param {Boolean} [options.nearLossless=false] - use near_lossless compression mode @param {Boolean} [options.force=true] - force WebP output, otherwise attempt to use input format @returns {Sharp} @throws {Error} Invalid options
[ "Use", "these", "WebP", "options", "for", "output", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L297-L319
2,519
lovell/sharp
lib/output.js
toFormat
function toFormat (format, options) { if (is.object(format) && is.string(format.id)) { format = format.id; } if (format === 'jpg') format = 'jpeg'; if (!is.inArray(format, ['jpeg', 'png', 'webp', 'tiff', 'raw'])) { throw new Error('Unsupported output format ' + format); } return this[format](options); }
javascript
function toFormat (format, options) { if (is.object(format) && is.string(format.id)) { format = format.id; } if (format === 'jpg') format = 'jpeg'; if (!is.inArray(format, ['jpeg', 'png', 'webp', 'tiff', 'raw'])) { throw new Error('Unsupported output format ' + format); } return this[format](options); }
[ "function", "toFormat", "(", "format", ",", "options", ")", "{", "if", "(", "is", ".", "object", "(", "format", ")", "&&", "is", ".", "string", "(", "format", ".", "id", ")", ")", "{", "format", "=", "format", ".", "id", ";", "}", "if", "(", "format", "===", "'jpg'", ")", "format", "=", "'jpeg'", ";", "if", "(", "!", "is", ".", "inArray", "(", "format", ",", "[", "'jpeg'", ",", "'png'", ",", "'webp'", ",", "'tiff'", ",", "'raw'", "]", ")", ")", "{", "throw", "new", "Error", "(", "'Unsupported output format '", "+", "format", ")", ";", "}", "return", "this", "[", "format", "]", "(", "options", ")", ";", "}" ]
Force output to a given format. @example // Convert any input to PNG output const data = await sharp(input) .toFormat('png') .toBuffer(); @param {(String|Object)} format - as a String or an Object with an 'id' attribute @param {Object} options - output options @returns {Sharp} @throws {Error} unsupported format or options
[ "Force", "output", "to", "a", "given", "format", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L461-L470
2,520
lovell/sharp
lib/output.js
_updateFormatOut
function _updateFormatOut (formatOut, options) { if (!(is.object(options) && options.force === false)) { this.options.formatOut = formatOut; } return this; }
javascript
function _updateFormatOut (formatOut, options) { if (!(is.object(options) && options.force === false)) { this.options.formatOut = formatOut; } return this; }
[ "function", "_updateFormatOut", "(", "formatOut", ",", "options", ")", "{", "if", "(", "!", "(", "is", ".", "object", "(", "options", ")", "&&", "options", ".", "force", "===", "false", ")", ")", "{", "this", ".", "options", ".", "formatOut", "=", "formatOut", ";", "}", "return", "this", ";", "}" ]
Update the output format unless options.force is false, in which case revert to input format. @private @param {String} formatOut @param {Object} [options] @param {Boolean} [options.force=true] - force output format, otherwise attempt to use input format @returns {Sharp}
[ "Update", "the", "output", "format", "unless", "options", ".", "force", "is", "false", "in", "which", "case", "revert", "to", "input", "format", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L575-L580
2,521
lovell/sharp
lib/output.js
_setBooleanOption
function _setBooleanOption (key, val) { if (is.bool(val)) { this.options[key] = val; } else { throw new Error('Invalid ' + key + ' (boolean) ' + val); } }
javascript
function _setBooleanOption (key, val) { if (is.bool(val)) { this.options[key] = val; } else { throw new Error('Invalid ' + key + ' (boolean) ' + val); } }
[ "function", "_setBooleanOption", "(", "key", ",", "val", ")", "{", "if", "(", "is", ".", "bool", "(", "val", ")", ")", "{", "this", ".", "options", "[", "key", "]", "=", "val", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid '", "+", "key", "+", "' (boolean) '", "+", "val", ")", ";", "}", "}" ]
Update a Boolean attribute of the this.options Object. @private @param {String} key @param {Boolean} val @throws {Error} Invalid key
[ "Update", "a", "Boolean", "attribute", "of", "the", "this", ".", "options", "Object", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/output.js#L589-L595
2,522
lovell/sharp
lib/colour.js
tint
function tint (rgb) { const colour = color(rgb); this.options.tintA = colour.a(); this.options.tintB = colour.b(); return this; }
javascript
function tint (rgb) { const colour = color(rgb); this.options.tintA = colour.a(); this.options.tintB = colour.b(); return this; }
[ "function", "tint", "(", "rgb", ")", "{", "const", "colour", "=", "color", "(", "rgb", ")", ";", "this", ".", "options", ".", "tintA", "=", "colour", ".", "a", "(", ")", ";", "this", ".", "options", ".", "tintB", "=", "colour", ".", "b", "(", ")", ";", "return", "this", ";", "}" ]
Tint the image using the provided chroma while preserving the image luminance. An alpha channel may be present and will be unchanged by the operation. @param {String|Object} rgb - parsed by the [color](https://www.npmjs.org/package/color) module to extract chroma values. @returns {Sharp} @throws {Error} Invalid parameter
[ "Tint", "the", "image", "using", "the", "provided", "chroma", "while", "preserving", "the", "image", "luminance", ".", "An", "alpha", "channel", "may", "be", "present", "and", "will", "be", "unchanged", "by", "the", "operation", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L26-L31
2,523
lovell/sharp
lib/colour.js
toColourspace
function toColourspace (colourspace) { if (!is.string(colourspace)) { throw new Error('Invalid output colourspace ' + colourspace); } this.options.colourspace = colourspace; return this; }
javascript
function toColourspace (colourspace) { if (!is.string(colourspace)) { throw new Error('Invalid output colourspace ' + colourspace); } this.options.colourspace = colourspace; return this; }
[ "function", "toColourspace", "(", "colourspace", ")", "{", "if", "(", "!", "is", ".", "string", "(", "colourspace", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid output colourspace '", "+", "colourspace", ")", ";", "}", "this", ".", "options", ".", "colourspace", "=", "colourspace", ";", "return", "this", ";", "}" ]
Set the output colourspace. By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. @param {String} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/master/libvips/iofuncs/enumtypes.c#L568) @returns {Sharp} @throws {Error} Invalid parameters
[ "Set", "the", "output", "colourspace", ".", "By", "default", "output", "image", "will", "be", "web", "-", "friendly", "sRGB", "with", "additional", "channels", "interpreted", "as", "alpha", "channels", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L64-L70
2,524
lovell/sharp
lib/colour.js
_setColourOption
function _setColourOption (key, val) { if (is.object(val) || is.string(val)) { const colour = color(val); this.options[key] = [ colour.red(), colour.green(), colour.blue(), Math.round(colour.alpha() * 255) ]; } }
javascript
function _setColourOption (key, val) { if (is.object(val) || is.string(val)) { const colour = color(val); this.options[key] = [ colour.red(), colour.green(), colour.blue(), Math.round(colour.alpha() * 255) ]; } }
[ "function", "_setColourOption", "(", "key", ",", "val", ")", "{", "if", "(", "is", ".", "object", "(", "val", ")", "||", "is", ".", "string", "(", "val", ")", ")", "{", "const", "colour", "=", "color", "(", "val", ")", ";", "this", ".", "options", "[", "key", "]", "=", "[", "colour", ".", "red", "(", ")", ",", "colour", ".", "green", "(", ")", ",", "colour", ".", "blue", "(", ")", ",", "Math", ".", "round", "(", "colour", ".", "alpha", "(", ")", "*", "255", ")", "]", ";", "}", "}" ]
Update a colour attribute of the this.options Object. @private @param {String} key @param {String|Object} val @throws {Error} Invalid key
[ "Update", "a", "colour", "attribute", "of", "the", "this", ".", "options", "Object", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/colour.js#L89-L99
2,525
lovell/sharp
lib/resize.js
extract
function extract (options) { const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; ['left', 'top', 'width', 'height'].forEach(function (name) { const value = options[name]; if (is.integer(value) && value >= 0) { this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; } else { throw new Error('Non-integer value for ' + name + ' of ' + value); } }, this); // Ensure existing rotation occurs before pre-resize extraction if (suffix === 'Pre' && ((this.options.angle % 360) !== 0 || this.options.useExifOrientation === true)) { this.options.rotateBeforePreExtract = true; } return this; }
javascript
function extract (options) { const suffix = this.options.width === -1 && this.options.height === -1 ? 'Pre' : 'Post'; ['left', 'top', 'width', 'height'].forEach(function (name) { const value = options[name]; if (is.integer(value) && value >= 0) { this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; } else { throw new Error('Non-integer value for ' + name + ' of ' + value); } }, this); // Ensure existing rotation occurs before pre-resize extraction if (suffix === 'Pre' && ((this.options.angle % 360) !== 0 || this.options.useExifOrientation === true)) { this.options.rotateBeforePreExtract = true; } return this; }
[ "function", "extract", "(", "options", ")", "{", "const", "suffix", "=", "this", ".", "options", ".", "width", "===", "-", "1", "&&", "this", ".", "options", ".", "height", "===", "-", "1", "?", "'Pre'", ":", "'Post'", ";", "[", "'left'", ",", "'top'", ",", "'width'", ",", "'height'", "]", ".", "forEach", "(", "function", "(", "name", ")", "{", "const", "value", "=", "options", "[", "name", "]", ";", "if", "(", "is", ".", "integer", "(", "value", ")", "&&", "value", ">=", "0", ")", "{", "this", ".", "options", "[", "name", "+", "(", "name", "===", "'left'", "||", "name", "===", "'top'", "?", "'Offset'", ":", "''", ")", "+", "suffix", "]", "=", "value", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Non-integer value for '", "+", "name", "+", "' of '", "+", "value", ")", ";", "}", "}", ",", "this", ")", ";", "// Ensure existing rotation occurs before pre-resize extraction", "if", "(", "suffix", "===", "'Pre'", "&&", "(", "(", "this", ".", "options", ".", "angle", "%", "360", ")", "!==", "0", "||", "this", ".", "options", ".", "useExifOrientation", "===", "true", ")", ")", "{", "this", ".", "options", ".", "rotateBeforePreExtract", "=", "true", ";", "}", "return", "this", ";", "}" ]
Extract a region of the image. - Use `extract` before `resize` for pre-resize extraction. - Use `extract` after `resize` for post-resize extraction. - Use `extract` before and after for both. @example sharp(input) .extract({ left: left, top: top, width: width, height: height }) .toFile(output, function(err) { // Extract a region of the input image, saving in the same format. }); @example sharp(input) .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) .resize(width, height) .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) .toFile(output, function(err) { // Extract a region, resize, then extract from the resized image }); @param {Object} options - describes the region to extract using integral pixel values @param {Number} options.left - zero-indexed offset from left edge @param {Number} options.top - zero-indexed offset from top edge @param {Number} options.width - width of region to extract @param {Number} options.height - height of region to extract @returns {Sharp} @throws {Error} Invalid parameters
[ "Extract", "a", "region", "of", "the", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/resize.js#L345-L360
2,526
lovell/sharp
lib/resize.js
trim
function trim (threshold) { if (!is.defined(threshold)) { this.options.trimThreshold = 10; } else if (is.number(threshold) && threshold > 0) { this.options.trimThreshold = threshold; } else { throw is.invalidParameterError('threshold', 'number greater than zero', threshold); } return this; }
javascript
function trim (threshold) { if (!is.defined(threshold)) { this.options.trimThreshold = 10; } else if (is.number(threshold) && threshold > 0) { this.options.trimThreshold = threshold; } else { throw is.invalidParameterError('threshold', 'number greater than zero', threshold); } return this; }
[ "function", "trim", "(", "threshold", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "trimThreshold", "=", "10", ";", "}", "else", "if", "(", "is", ".", "number", "(", "threshold", ")", "&&", "threshold", ">", "0", ")", "{", "this", ".", "options", ".", "trimThreshold", "=", "threshold", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'threshold'", ",", "'number greater than zero'", ",", "threshold", ")", ";", "}", "return", "this", ";", "}" ]
Trim "boring" pixels from all edges that contain values similar to the top-left pixel. The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. @param {Number} [threshold=10] the allowed difference from the top-left pixel, a number greater than zero. @returns {Sharp} @throws {Error} Invalid parameters
[ "Trim", "boring", "pixels", "from", "all", "edges", "that", "contain", "values", "similar", "to", "the", "top", "-", "left", "pixel", ".", "The", "info", "response", "Object", "will", "contain", "trimOffsetLeft", "and", "trimOffsetTop", "properties", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/resize.js#L369-L378
2,527
lovell/sharp
lib/operation.js
rotate
function rotate (angle, options) { if (!is.defined(angle)) { this.options.useExifOrientation = true; } else if (is.integer(angle) && !(angle % 90)) { this.options.angle = angle; } else if (is.number(angle)) { this.options.rotationAngle = angle; if (is.object(options) && options.background) { const backgroundColour = color(options.background); this.options.rotationBackground = [ backgroundColour.red(), backgroundColour.green(), backgroundColour.blue(), Math.round(backgroundColour.alpha() * 255) ]; } } else { throw new Error('Unsupported angle: must be a number.'); } return this; }
javascript
function rotate (angle, options) { if (!is.defined(angle)) { this.options.useExifOrientation = true; } else if (is.integer(angle) && !(angle % 90)) { this.options.angle = angle; } else if (is.number(angle)) { this.options.rotationAngle = angle; if (is.object(options) && options.background) { const backgroundColour = color(options.background); this.options.rotationBackground = [ backgroundColour.red(), backgroundColour.green(), backgroundColour.blue(), Math.round(backgroundColour.alpha() * 255) ]; } } else { throw new Error('Unsupported angle: must be a number.'); } return this; }
[ "function", "rotate", "(", "angle", ",", "options", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "angle", ")", ")", "{", "this", ".", "options", ".", "useExifOrientation", "=", "true", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "angle", ")", "&&", "!", "(", "angle", "%", "90", ")", ")", "{", "this", ".", "options", ".", "angle", "=", "angle", ";", "}", "else", "if", "(", "is", ".", "number", "(", "angle", ")", ")", "{", "this", ".", "options", ".", "rotationAngle", "=", "angle", ";", "if", "(", "is", ".", "object", "(", "options", ")", "&&", "options", ".", "background", ")", "{", "const", "backgroundColour", "=", "color", "(", "options", ".", "background", ")", ";", "this", ".", "options", ".", "rotationBackground", "=", "[", "backgroundColour", ".", "red", "(", ")", ",", "backgroundColour", ".", "green", "(", ")", ",", "backgroundColour", ".", "blue", "(", ")", ",", "Math", ".", "round", "(", "backgroundColour", ".", "alpha", "(", ")", "*", "255", ")", "]", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Unsupported angle: must be a number.'", ")", ";", "}", "return", "this", ";", "}" ]
Rotate the output image by either an explicit angle or auto-orient based on the EXIF `Orientation` tag. If an angle is provided, it is converted to a valid positive degree rotation. For example, `-450` will produce a 270deg rotation. When rotating by an angle other than a multiple of 90, the background colour can be provided with the `background` option. If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. The use of `rotate` implies the removal of the EXIF `Orientation` tag, if any. Method order is important when both rotating and extracting regions, for example `rotate(x).extract(y)` will produce a different result to `extract(y).rotate(x)`. @example const pipeline = sharp() .rotate() .resize(null, 200) .toBuffer(function (err, outputBuffer, info) { // outputBuffer contains 200px high JPEG image data, // auto-rotated using EXIF Orientation tag // info.width and info.height contain the dimensions of the resized image }); readableStream.pipe(pipeline); @param {Number} [angle=auto] angle of rotation. @param {Object} [options] - if present, is an Object with optional attributes. @param {String|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. @returns {Sharp} @throws {Error} Invalid parameters
[ "Rotate", "the", "output", "image", "by", "either", "an", "explicit", "angle", "or", "auto", "-", "orient", "based", "on", "the", "EXIF", "Orientation", "tag", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L41-L61
2,528
lovell/sharp
lib/operation.js
sharpen
function sharpen (sigma, flat, jagged) { if (!is.defined(sigma)) { // No arguments: default to mild sharpen this.options.sharpenSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild sharpen? this.options.sharpenSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { // Numeric argument: specific sigma this.options.sharpenSigma = sigma; // Control over flat areas if (is.defined(flat)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) { this.options.sharpenFlat = flat; } else { throw new Error('Invalid sharpen level for flat areas (0.0 - 10000.0) ' + flat); } } // Control over jagged areas if (is.defined(jagged)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { this.options.sharpenJagged = jagged; } else { throw new Error('Invalid sharpen level for jagged areas (0.0 - 10000.0) ' + jagged); } } } else { throw new Error('Invalid sharpen sigma (0.01 - 10000) ' + sigma); } return this; }
javascript
function sharpen (sigma, flat, jagged) { if (!is.defined(sigma)) { // No arguments: default to mild sharpen this.options.sharpenSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild sharpen? this.options.sharpenSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.01, 10000)) { // Numeric argument: specific sigma this.options.sharpenSigma = sigma; // Control over flat areas if (is.defined(flat)) { if (is.number(flat) && is.inRange(flat, 0, 10000)) { this.options.sharpenFlat = flat; } else { throw new Error('Invalid sharpen level for flat areas (0.0 - 10000.0) ' + flat); } } // Control over jagged areas if (is.defined(jagged)) { if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { this.options.sharpenJagged = jagged; } else { throw new Error('Invalid sharpen level for jagged areas (0.0 - 10000.0) ' + jagged); } } } else { throw new Error('Invalid sharpen sigma (0.01 - 10000) ' + sigma); } return this; }
[ "function", "sharpen", "(", "sigma", ",", "flat", ",", "jagged", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "sigma", ")", ")", "{", "// No arguments: default to mild sharpen", "this", ".", "options", ".", "sharpenSigma", "=", "-", "1", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "sigma", ")", ")", "{", "// Boolean argument: apply mild sharpen?", "this", ".", "options", ".", "sharpenSigma", "=", "sigma", "?", "-", "1", ":", "0", ";", "}", "else", "if", "(", "is", ".", "number", "(", "sigma", ")", "&&", "is", ".", "inRange", "(", "sigma", ",", "0.01", ",", "10000", ")", ")", "{", "// Numeric argument: specific sigma", "this", ".", "options", ".", "sharpenSigma", "=", "sigma", ";", "// Control over flat areas", "if", "(", "is", ".", "defined", "(", "flat", ")", ")", "{", "if", "(", "is", ".", "number", "(", "flat", ")", "&&", "is", ".", "inRange", "(", "flat", ",", "0", ",", "10000", ")", ")", "{", "this", ".", "options", ".", "sharpenFlat", "=", "flat", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen level for flat areas (0.0 - 10000.0) '", "+", "flat", ")", ";", "}", "}", "// Control over jagged areas", "if", "(", "is", ".", "defined", "(", "jagged", ")", ")", "{", "if", "(", "is", ".", "number", "(", "jagged", ")", "&&", "is", ".", "inRange", "(", "jagged", ",", "0", ",", "10000", ")", ")", "{", "this", ".", "options", ".", "sharpenJagged", "=", "jagged", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen level for jagged areas (0.0 - 10000.0) '", "+", "jagged", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid sharpen sigma (0.01 - 10000) '", "+", "sigma", ")", ";", "}", "return", "this", ";", "}" ]
Sharpen the image. When used without parameters, performs a fast, mild sharpen of the output image. When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. Separate control over the level of sharpening in "flat" and "jagged" areas is available. @param {Number} [sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. @param {Number} [flat=1.0] - the level of sharpening to apply to "flat" areas. @param {Number} [jagged=2.0] - the level of sharpening to apply to "jagged" areas. @returns {Sharp} @throws {Error} Invalid parameters
[ "Sharpen", "the", "image", ".", "When", "used", "without", "parameters", "performs", "a", "fast", "mild", "sharpen", "of", "the", "output", "image", ".", "When", "a", "sigma", "is", "provided", "performs", "a", "slower", "more", "accurate", "sharpen", "of", "the", "L", "channel", "in", "the", "LAB", "colour", "space", ".", "Separate", "control", "over", "the", "level", "of", "sharpening", "in", "flat", "and", "jagged", "areas", "is", "available", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L97-L127
2,529
lovell/sharp
lib/operation.js
median
function median (size) { if (!is.defined(size)) { // No arguments: default to 3x3 this.options.medianSize = 3; } else if (is.integer(size) && is.inRange(size, 1, 1000)) { // Numeric argument: specific sigma this.options.medianSize = size; } else { throw new Error('Invalid median size ' + size); } return this; }
javascript
function median (size) { if (!is.defined(size)) { // No arguments: default to 3x3 this.options.medianSize = 3; } else if (is.integer(size) && is.inRange(size, 1, 1000)) { // Numeric argument: specific sigma this.options.medianSize = size; } else { throw new Error('Invalid median size ' + size); } return this; }
[ "function", "median", "(", "size", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "size", ")", ")", "{", "// No arguments: default to 3x3", "this", ".", "options", ".", "medianSize", "=", "3", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "size", ")", "&&", "is", ".", "inRange", "(", "size", ",", "1", ",", "1000", ")", ")", "{", "// Numeric argument: specific sigma", "this", ".", "options", ".", "medianSize", "=", "size", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid median size '", "+", "size", ")", ";", "}", "return", "this", ";", "}" ]
Apply median filter. When used without parameters the default window is 3x3. @param {Number} [size=3] square mask size: size x size @returns {Sharp} @throws {Error} Invalid parameters
[ "Apply", "median", "filter", ".", "When", "used", "without", "parameters", "the", "default", "window", "is", "3x3", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L136-L147
2,530
lovell/sharp
lib/operation.js
blur
function blur (sigma) { if (!is.defined(sigma)) { // No arguments: default to mild blur this.options.blurSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild blur? this.options.blurSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { // Numeric argument: specific sigma this.options.blurSigma = sigma; } else { throw new Error('Invalid blur sigma (0.3 - 1000.0) ' + sigma); } return this; }
javascript
function blur (sigma) { if (!is.defined(sigma)) { // No arguments: default to mild blur this.options.blurSigma = -1; } else if (is.bool(sigma)) { // Boolean argument: apply mild blur? this.options.blurSigma = sigma ? -1 : 0; } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { // Numeric argument: specific sigma this.options.blurSigma = sigma; } else { throw new Error('Invalid blur sigma (0.3 - 1000.0) ' + sigma); } return this; }
[ "function", "blur", "(", "sigma", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "sigma", ")", ")", "{", "// No arguments: default to mild blur", "this", ".", "options", ".", "blurSigma", "=", "-", "1", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "sigma", ")", ")", "{", "// Boolean argument: apply mild blur?", "this", ".", "options", ".", "blurSigma", "=", "sigma", "?", "-", "1", ":", "0", ";", "}", "else", "if", "(", "is", ".", "number", "(", "sigma", ")", "&&", "is", ".", "inRange", "(", "sigma", ",", "0.3", ",", "1000", ")", ")", "{", "// Numeric argument: specific sigma", "this", ".", "options", ".", "blurSigma", "=", "sigma", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid blur sigma (0.3 - 1000.0) '", "+", "sigma", ")", ";", "}", "return", "this", ";", "}" ]
Blur the image. When used without parameters, performs a fast, mild blur of the output image. When a `sigma` is provided, performs a slower, more accurate Gaussian blur. @param {Number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. @returns {Sharp} @throws {Error} Invalid parameters
[ "Blur", "the", "image", ".", "When", "used", "without", "parameters", "performs", "a", "fast", "mild", "blur", "of", "the", "output", "image", ".", "When", "a", "sigma", "is", "provided", "performs", "a", "slower", "more", "accurate", "Gaussian", "blur", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L157-L171
2,531
lovell/sharp
lib/operation.js
flatten
function flatten (options) { this.options.flatten = is.bool(options) ? options : true; if (is.object(options)) { this._setColourOption('flattenBackground', options.background); } return this; }
javascript
function flatten (options) { this.options.flatten = is.bool(options) ? options : true; if (is.object(options)) { this._setColourOption('flattenBackground', options.background); } return this; }
[ "function", "flatten", "(", "options", ")", "{", "this", ".", "options", ".", "flatten", "=", "is", ".", "bool", "(", "options", ")", "?", "options", ":", "true", ";", "if", "(", "is", ".", "object", "(", "options", ")", ")", "{", "this", ".", "_setColourOption", "(", "'flattenBackground'", ",", "options", ".", "background", ")", ";", "}", "return", "this", ";", "}" ]
Merge alpha transparency channel, if any, with a background. @param {Object} [options] @param {String|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. @returns {Sharp}
[ "Merge", "alpha", "transparency", "channel", "if", "any", "with", "a", "background", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L179-L185
2,532
lovell/sharp
lib/operation.js
convolve
function convolve (kernel) { if (!is.object(kernel) || !Array.isArray(kernel.kernel) || !is.integer(kernel.width) || !is.integer(kernel.height) || !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || kernel.height * kernel.width !== kernel.kernel.length ) { // must pass in a kernel throw new Error('Invalid convolution kernel'); } // Default scale is sum of kernel values if (!is.integer(kernel.scale)) { kernel.scale = kernel.kernel.reduce(function (a, b) { return a + b; }, 0); } // Clip scale to a minimum value of 1 if (kernel.scale < 1) { kernel.scale = 1; } if (!is.integer(kernel.offset)) { kernel.offset = 0; } this.options.convKernel = kernel; return this; }
javascript
function convolve (kernel) { if (!is.object(kernel) || !Array.isArray(kernel.kernel) || !is.integer(kernel.width) || !is.integer(kernel.height) || !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || kernel.height * kernel.width !== kernel.kernel.length ) { // must pass in a kernel throw new Error('Invalid convolution kernel'); } // Default scale is sum of kernel values if (!is.integer(kernel.scale)) { kernel.scale = kernel.kernel.reduce(function (a, b) { return a + b; }, 0); } // Clip scale to a minimum value of 1 if (kernel.scale < 1) { kernel.scale = 1; } if (!is.integer(kernel.offset)) { kernel.offset = 0; } this.options.convKernel = kernel; return this; }
[ "function", "convolve", "(", "kernel", ")", "{", "if", "(", "!", "is", ".", "object", "(", "kernel", ")", "||", "!", "Array", ".", "isArray", "(", "kernel", ".", "kernel", ")", "||", "!", "is", ".", "integer", "(", "kernel", ".", "width", ")", "||", "!", "is", ".", "integer", "(", "kernel", ".", "height", ")", "||", "!", "is", ".", "inRange", "(", "kernel", ".", "width", ",", "3", ",", "1001", ")", "||", "!", "is", ".", "inRange", "(", "kernel", ".", "height", ",", "3", ",", "1001", ")", "||", "kernel", ".", "height", "*", "kernel", ".", "width", "!==", "kernel", ".", "kernel", ".", "length", ")", "{", "// must pass in a kernel", "throw", "new", "Error", "(", "'Invalid convolution kernel'", ")", ";", "}", "// Default scale is sum of kernel values", "if", "(", "!", "is", ".", "integer", "(", "kernel", ".", "scale", ")", ")", "{", "kernel", ".", "scale", "=", "kernel", ".", "kernel", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "+", "b", ";", "}", ",", "0", ")", ";", "}", "// Clip scale to a minimum value of 1", "if", "(", "kernel", ".", "scale", "<", "1", ")", "{", "kernel", ".", "scale", "=", "1", ";", "}", "if", "(", "!", "is", ".", "integer", "(", "kernel", ".", "offset", ")", ")", "{", "kernel", ".", "offset", "=", "0", ";", "}", "this", ".", "options", ".", "convKernel", "=", "kernel", ";", "return", "this", ";", "}" ]
Convolve the image with the specified kernel. @example sharp(input) .convolve({ width: 3, height: 3, kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] }) .raw() .toBuffer(function(err, data, info) { // data contains the raw pixel data representing the convolution // of the input image with the horizontal Sobel operator }); @param {Object} kernel @param {Number} kernel.width - width of the kernel in pixels. @param {Number} kernel.height - width of the kernel in pixels. @param {Array<Number>} kernel.kernel - Array of length `width*height` containing the kernel values. @param {Number} [kernel.scale=sum] - the scale of the kernel in pixels. @param {Number} [kernel.offset=0] - the offset of the kernel in pixels. @returns {Sharp} @throws {Error} Invalid parameters
[ "Convolve", "the", "image", "with", "the", "specified", "kernel", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L275-L299
2,533
lovell/sharp
lib/operation.js
threshold
function threshold (threshold, options) { if (!is.defined(threshold)) { this.options.threshold = 128; } else if (is.bool(threshold)) { this.options.threshold = threshold ? 128 : 0; } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { this.options.threshold = threshold; } else { throw new Error('Invalid threshold (0 to 255) ' + threshold); } if (!is.object(options) || options.greyscale === true || options.grayscale === true) { this.options.thresholdGrayscale = true; } else { this.options.thresholdGrayscale = false; } return this; }
javascript
function threshold (threshold, options) { if (!is.defined(threshold)) { this.options.threshold = 128; } else if (is.bool(threshold)) { this.options.threshold = threshold ? 128 : 0; } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { this.options.threshold = threshold; } else { throw new Error('Invalid threshold (0 to 255) ' + threshold); } if (!is.object(options) || options.greyscale === true || options.grayscale === true) { this.options.thresholdGrayscale = true; } else { this.options.thresholdGrayscale = false; } return this; }
[ "function", "threshold", "(", "threshold", ",", "options", ")", "{", "if", "(", "!", "is", ".", "defined", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "128", ";", "}", "else", "if", "(", "is", ".", "bool", "(", "threshold", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "threshold", "?", "128", ":", "0", ";", "}", "else", "if", "(", "is", ".", "integer", "(", "threshold", ")", "&&", "is", ".", "inRange", "(", "threshold", ",", "0", ",", "255", ")", ")", "{", "this", ".", "options", ".", "threshold", "=", "threshold", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid threshold (0 to 255) '", "+", "threshold", ")", ";", "}", "if", "(", "!", "is", ".", "object", "(", "options", ")", "||", "options", ".", "greyscale", "===", "true", "||", "options", ".", "grayscale", "===", "true", ")", "{", "this", ".", "options", ".", "thresholdGrayscale", "=", "true", ";", "}", "else", "{", "this", ".", "options", ".", "thresholdGrayscale", "=", "false", ";", "}", "return", "this", ";", "}" ]
Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. @param {Number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. @param {Object} [options] @param {Boolean} [options.greyscale=true] - convert to single channel greyscale. @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale. @returns {Sharp} @throws {Error} Invalid parameters
[ "Any", "pixel", "value", "greather", "than", "or", "equal", "to", "the", "threshold", "value", "will", "be", "set", "to", "255", "otherwise", "it", "will", "be", "set", "to", "0", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L310-L326
2,534
lovell/sharp
lib/operation.js
boolean
function boolean (operand, operator, options) { this.options.boolean = this._createInputDescriptor(operand, options); if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { this.options.booleanOp = operator; } else { throw new Error('Invalid boolean operator ' + operator); } return this; }
javascript
function boolean (operand, operator, options) { this.options.boolean = this._createInputDescriptor(operand, options); if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { this.options.booleanOp = operator; } else { throw new Error('Invalid boolean operator ' + operator); } return this; }
[ "function", "boolean", "(", "operand", ",", "operator", ",", "options", ")", "{", "this", ".", "options", ".", "boolean", "=", "this", ".", "_createInputDescriptor", "(", "operand", ",", "options", ")", ";", "if", "(", "is", ".", "string", "(", "operator", ")", "&&", "is", ".", "inArray", "(", "operator", ",", "[", "'and'", ",", "'or'", ",", "'eor'", "]", ")", ")", "{", "this", ".", "options", ".", "booleanOp", "=", "operator", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid boolean operator '", "+", "operator", ")", ";", "}", "return", "this", ";", "}" ]
Perform a bitwise boolean operation with operand image. This operation creates an output image where each pixel is the result of the selected bitwise boolean `operation` between the corresponding pixels of the input images. @param {Buffer|String} operand - Buffer containing image data or String containing the path to an image file. @param {String} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. @param {Object} [options] @param {Object} [options.raw] - describes operand when using raw pixel data. @param {Number} [options.raw.width] @param {Number} [options.raw.height] @param {Number} [options.raw.channels] @returns {Sharp} @throws {Error} Invalid parameters
[ "Perform", "a", "bitwise", "boolean", "operation", "with", "operand", "image", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L344-L352
2,535
lovell/sharp
lib/operation.js
recomb
function recomb (inputMatrix) { if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || inputMatrix[0].length !== 3 || inputMatrix[1].length !== 3 || inputMatrix[2].length !== 3 ) { // must pass in a kernel throw new Error('Invalid Recomb Matrix'); } this.options.recombMatrix = [ inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] ].map(Number); return this; }
javascript
function recomb (inputMatrix) { if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || inputMatrix[0].length !== 3 || inputMatrix[1].length !== 3 || inputMatrix[2].length !== 3 ) { // must pass in a kernel throw new Error('Invalid Recomb Matrix'); } this.options.recombMatrix = [ inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] ].map(Number); return this; }
[ "function", "recomb", "(", "inputMatrix", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "inputMatrix", ")", "||", "inputMatrix", ".", "length", "!==", "3", "||", "inputMatrix", "[", "0", "]", ".", "length", "!==", "3", "||", "inputMatrix", "[", "1", "]", ".", "length", "!==", "3", "||", "inputMatrix", "[", "2", "]", ".", "length", "!==", "3", ")", "{", "// must pass in a kernel", "throw", "new", "Error", "(", "'Invalid Recomb Matrix'", ")", ";", "}", "this", ".", "options", ".", "recombMatrix", "=", "[", "inputMatrix", "[", "0", "]", "[", "0", "]", ",", "inputMatrix", "[", "0", "]", "[", "1", "]", ",", "inputMatrix", "[", "0", "]", "[", "2", "]", ",", "inputMatrix", "[", "1", "]", "[", "0", "]", ",", "inputMatrix", "[", "1", "]", "[", "1", "]", ",", "inputMatrix", "[", "1", "]", "[", "2", "]", ",", "inputMatrix", "[", "2", "]", "[", "0", "]", ",", "inputMatrix", "[", "2", "]", "[", "1", "]", ",", "inputMatrix", "[", "2", "]", "[", "2", "]", "]", ".", "map", "(", "Number", ")", ";", "return", "this", ";", "}" ]
Recomb the image with the specified matrix. @example sharp(input) .recomb([ [0.3588, 0.7044, 0.1368], [0.2990, 0.5870, 0.1140], [0.2392, 0.4696, 0.0912], ]) .raw() .toBuffer(function(err, data, info) { // data contains the raw pixel data after applying the recomb // With this example input, a sepia filter has been applied }); @param {Array<Array<Number>>} 3x3 Recombination matrix @returns {Sharp} @throws {Error} Invalid parameters
[ "Recomb", "the", "image", "with", "the", "specified", "matrix", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L401-L416
2,536
lovell/sharp
lib/operation.js
modulate
function modulate (options) { if (!is.plainObject(options)) { throw is.invalidParameterError('options', 'plain object', options); } if ('brightness' in options) { if (is.number(options.brightness) && options.brightness >= 0) { this.options.brightness = options.brightness; } else { throw is.invalidParameterError('brightness', 'number above zero', options.brightness); } } if ('saturation' in options) { if (is.number(options.saturation) && options.saturation >= 0) { this.options.saturation = options.saturation; } else { throw is.invalidParameterError('saturation', 'number above zero', options.saturation); } } if ('hue' in options) { if (is.integer(options.hue)) { this.options.hue = options.hue % 360; } else { throw is.invalidParameterError('hue', 'number', options.hue); } } return this; }
javascript
function modulate (options) { if (!is.plainObject(options)) { throw is.invalidParameterError('options', 'plain object', options); } if ('brightness' in options) { if (is.number(options.brightness) && options.brightness >= 0) { this.options.brightness = options.brightness; } else { throw is.invalidParameterError('brightness', 'number above zero', options.brightness); } } if ('saturation' in options) { if (is.number(options.saturation) && options.saturation >= 0) { this.options.saturation = options.saturation; } else { throw is.invalidParameterError('saturation', 'number above zero', options.saturation); } } if ('hue' in options) { if (is.integer(options.hue)) { this.options.hue = options.hue % 360; } else { throw is.invalidParameterError('hue', 'number', options.hue); } } return this; }
[ "function", "modulate", "(", "options", ")", "{", "if", "(", "!", "is", ".", "plainObject", "(", "options", ")", ")", "{", "throw", "is", ".", "invalidParameterError", "(", "'options'", ",", "'plain object'", ",", "options", ")", ";", "}", "if", "(", "'brightness'", "in", "options", ")", "{", "if", "(", "is", ".", "number", "(", "options", ".", "brightness", ")", "&&", "options", ".", "brightness", ">=", "0", ")", "{", "this", ".", "options", ".", "brightness", "=", "options", ".", "brightness", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'brightness'", ",", "'number above zero'", ",", "options", ".", "brightness", ")", ";", "}", "}", "if", "(", "'saturation'", "in", "options", ")", "{", "if", "(", "is", ".", "number", "(", "options", ".", "saturation", ")", "&&", "options", ".", "saturation", ">=", "0", ")", "{", "this", ".", "options", ".", "saturation", "=", "options", ".", "saturation", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'saturation'", ",", "'number above zero'", ",", "options", ".", "saturation", ")", ";", "}", "}", "if", "(", "'hue'", "in", "options", ")", "{", "if", "(", "is", ".", "integer", "(", "options", ".", "hue", ")", ")", "{", "this", ".", "options", ".", "hue", "=", "options", ".", "hue", "%", "360", ";", "}", "else", "{", "throw", "is", ".", "invalidParameterError", "(", "'hue'", ",", "'number'", ",", "options", ".", "hue", ")", ";", "}", "}", "return", "this", ";", "}" ]
Transforms the image using brightness, saturation and hue rotation. @example sharp(input) .modulate({ brightness: 2 // increase lightness by a factor of 2 }); sharp(input) .modulate({ hue: 180 // hue-rotate by 180 degrees }); // decreate brightness and saturation while also hue-rotating by 90 degrees sharp(input) .modulate({ brightness: 0.5, saturation: 0.5, hue: 90 }); @param {Object} [options] @param {Number} [options.brightness] Brightness multiplier @param {Number} [options.saturation] Saturation multiplier @param {Number} [options.hue] Degrees for hue rotation @returns {Sharp}
[ "Transforms", "the", "image", "using", "brightness", "saturation", "and", "hue", "rotation", "." ]
05d76eeadfe54713606a615185b2da047923406b
https://github.com/lovell/sharp/blob/05d76eeadfe54713606a615185b2da047923406b/lib/operation.js#L446-L472
2,537
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
findWhereUnwrapped
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.getNodeInternal(), predicate)); }
javascript
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.getNodeInternal(), predicate)); }
[ "function", "findWhereUnwrapped", "(", "wrapper", ",", "predicate", ",", "filter", "=", "treeFilter", ")", "{", "return", "wrapper", ".", "flatMap", "(", "n", "=>", "filter", "(", "n", ".", "getNodeInternal", "(", ")", ",", "predicate", ")", ")", ";", "}" ]
Finds all nodes in the current wrapper nodes' render trees that match the provided predicate function. @param {ShallowWrapper} wrapper @param {Function} predicate @param {Function} filter @returns {ShallowWrapper}
[ "Finds", "all", "nodes", "in", "the", "current", "wrapper", "nodes", "render", "trees", "that", "match", "the", "provided", "predicate", "function", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L59-L61
2,538
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
filterWhereUnwrapped
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
javascript
function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean)); }
[ "function", "filterWhereUnwrapped", "(", "wrapper", ",", "predicate", ")", "{", "return", "wrapper", ".", "wrap", "(", "wrapper", ".", "getNodesInternal", "(", ")", ".", "filter", "(", "predicate", ")", ".", "filter", "(", "Boolean", ")", ")", ";", "}" ]
Returns a new wrapper instance with only the nodes of the current wrapper instance that match the provided predicate function. @param {ShallowWrapper} wrapper @param {Function} predicate @returns {ShallowWrapper}
[ "Returns", "a", "new", "wrapper", "instance", "with", "only", "the", "nodes", "of", "the", "current", "wrapper", "instance", "that", "match", "the", "provided", "predicate", "function", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L71-L73
2,539
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
validateOptions
function validateOptions(options) { const { lifecycleExperimental, disableLifecycleMethods, enableComponentDidUpdateOnSetState, supportPrevContextArgumentOfComponentDidUpdate, lifecycles, } = options; if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') { throw new Error('lifecycleExperimental must be either true or false if provided'); } if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') { throw new Error('disableLifecycleMethods must be either true or false if provided'); } if ( lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods ) { throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'); } if ( typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState ) { throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'); } if ( typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate ) { throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'); } }
javascript
function validateOptions(options) { const { lifecycleExperimental, disableLifecycleMethods, enableComponentDidUpdateOnSetState, supportPrevContextArgumentOfComponentDidUpdate, lifecycles, } = options; if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') { throw new Error('lifecycleExperimental must be either true or false if provided'); } if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') { throw new Error('disableLifecycleMethods must be either true or false if provided'); } if ( lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods ) { throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'); } if ( typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState ) { throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'); } if ( typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate ) { throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'); } }
[ "function", "validateOptions", "(", "options", ")", "{", "const", "{", "lifecycleExperimental", ",", "disableLifecycleMethods", ",", "enableComponentDidUpdateOnSetState", ",", "supportPrevContextArgumentOfComponentDidUpdate", ",", "lifecycles", ",", "}", "=", "options", ";", "if", "(", "typeof", "lifecycleExperimental", "!==", "'undefined'", "&&", "typeof", "lifecycleExperimental", "!==", "'boolean'", ")", "{", "throw", "new", "Error", "(", "'lifecycleExperimental must be either true or false if provided'", ")", ";", "}", "if", "(", "typeof", "disableLifecycleMethods", "!==", "'undefined'", "&&", "typeof", "disableLifecycleMethods", "!==", "'boolean'", ")", "{", "throw", "new", "Error", "(", "'disableLifecycleMethods must be either true or false if provided'", ")", ";", "}", "if", "(", "lifecycleExperimental", "!=", "null", "&&", "disableLifecycleMethods", "!=", "null", "&&", "lifecycleExperimental", "===", "disableLifecycleMethods", ")", "{", "throw", "new", "Error", "(", "'lifecycleExperimental and disableLifecycleMethods cannot be set to the same value'", ")", ";", "}", "if", "(", "typeof", "enableComponentDidUpdateOnSetState", "!==", "'undefined'", "&&", "lifecycles", ".", "componentDidUpdate", "&&", "lifecycles", ".", "componentDidUpdate", ".", "onSetState", "!==", "enableComponentDidUpdateOnSetState", ")", "{", "throw", "new", "TypeError", "(", "'the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility'", ")", ";", "}", "if", "(", "typeof", "supportPrevContextArgumentOfComponentDidUpdate", "!==", "'undefined'", "&&", "lifecycles", ".", "componentDidUpdate", "&&", "lifecycles", ".", "componentDidUpdate", ".", "prevContext", "!==", "supportPrevContextArgumentOfComponentDidUpdate", ")", "{", "throw", "new", "TypeError", "(", "'the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility'", ")", ";", "}", "}" ]
Ensure options passed to ShallowWrapper are valid. Throws otherwise. @param {Object} options
[ "Ensure", "options", "passed", "to", "ShallowWrapper", "are", "valid", ".", "Throws", "otherwise", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L79-L118
2,540
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
getContextFromWrappingComponent
function getContextFromWrappingComponent(wrapper, adapter) { const rootFinder = deepRender(wrapper, wrapper[ROOT_FINDER], adapter); if (!rootFinder) { throw new Error('`wrappingComponent` must render its children!'); } return { legacyContext: rootFinder[OPTIONS].context, providerValues: rootFinder[PROVIDER_VALUES], }; }
javascript
function getContextFromWrappingComponent(wrapper, adapter) { const rootFinder = deepRender(wrapper, wrapper[ROOT_FINDER], adapter); if (!rootFinder) { throw new Error('`wrappingComponent` must render its children!'); } return { legacyContext: rootFinder[OPTIONS].context, providerValues: rootFinder[PROVIDER_VALUES], }; }
[ "function", "getContextFromWrappingComponent", "(", "wrapper", ",", "adapter", ")", "{", "const", "rootFinder", "=", "deepRender", "(", "wrapper", ",", "wrapper", "[", "ROOT_FINDER", "]", ",", "adapter", ")", ";", "if", "(", "!", "rootFinder", ")", "{", "throw", "new", "Error", "(", "'`wrappingComponent` must render its children!'", ")", ";", "}", "return", "{", "legacyContext", ":", "rootFinder", "[", "OPTIONS", "]", ".", "context", ",", "providerValues", ":", "rootFinder", "[", "PROVIDER_VALUES", "]", ",", "}", ";", "}" ]
Deep-renders the `wrappingComponent` and returns the context that should be accessible to the primary wrapper. @param {WrappingComponentWrapper} wrapper The `WrappingComponentWrapper` for a `wrappingComponent` @param {Adapter} adapter An Enzyme adapter @returns {object} An object containing an object of legacy context values and a Map of `createContext()` Provider values.
[ "Deep", "-", "renders", "the", "wrappingComponent", "and", "returns", "the", "context", "that", "should", "be", "accessible", "to", "the", "primary", "wrapper", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L320-L329
2,541
airbnb/enzyme
packages/enzyme/src/ShallowWrapper.js
updatePrimaryRootContext
function updatePrimaryRootContext(wrappingComponent) { const adapter = getAdapter(wrappingComponent[OPTIONS]); const primaryWrapper = wrappingComponent[PRIMARY_WRAPPER]; const primaryRenderer = primaryWrapper[RENDERER]; const primaryNode = primaryRenderer.getNode(); const { legacyContext, providerValues, } = getContextFromWrappingComponent(wrappingComponent, adapter); const prevProviderValues = primaryWrapper[PROVIDER_VALUES]; primaryWrapper.setContext({ ...wrappingComponent[PRIMARY_WRAPPER][OPTIONS].context, ...legacyContext, }); primaryWrapper[PROVIDER_VALUES] = new Map([...prevProviderValues, ...providerValues]); if (typeof adapter.isContextConsumer === 'function' && adapter.isContextConsumer(primaryNode.type)) { const Consumer = primaryNode.type; // Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer` // method. const Provider = adapter.getProviderFromConsumer(Consumer); const newValue = providerValues.get(Provider); const oldValue = prevProviderValues.get(Provider); // Use referential comparison like React if (newValue !== oldValue) { primaryWrapper.rerender(); } } }
javascript
function updatePrimaryRootContext(wrappingComponent) { const adapter = getAdapter(wrappingComponent[OPTIONS]); const primaryWrapper = wrappingComponent[PRIMARY_WRAPPER]; const primaryRenderer = primaryWrapper[RENDERER]; const primaryNode = primaryRenderer.getNode(); const { legacyContext, providerValues, } = getContextFromWrappingComponent(wrappingComponent, adapter); const prevProviderValues = primaryWrapper[PROVIDER_VALUES]; primaryWrapper.setContext({ ...wrappingComponent[PRIMARY_WRAPPER][OPTIONS].context, ...legacyContext, }); primaryWrapper[PROVIDER_VALUES] = new Map([...prevProviderValues, ...providerValues]); if (typeof adapter.isContextConsumer === 'function' && adapter.isContextConsumer(primaryNode.type)) { const Consumer = primaryNode.type; // Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer` // method. const Provider = adapter.getProviderFromConsumer(Consumer); const newValue = providerValues.get(Provider); const oldValue = prevProviderValues.get(Provider); // Use referential comparison like React if (newValue !== oldValue) { primaryWrapper.rerender(); } } }
[ "function", "updatePrimaryRootContext", "(", "wrappingComponent", ")", "{", "const", "adapter", "=", "getAdapter", "(", "wrappingComponent", "[", "OPTIONS", "]", ")", ";", "const", "primaryWrapper", "=", "wrappingComponent", "[", "PRIMARY_WRAPPER", "]", ";", "const", "primaryRenderer", "=", "primaryWrapper", "[", "RENDERER", "]", ";", "const", "primaryNode", "=", "primaryRenderer", ".", "getNode", "(", ")", ";", "const", "{", "legacyContext", ",", "providerValues", ",", "}", "=", "getContextFromWrappingComponent", "(", "wrappingComponent", ",", "adapter", ")", ";", "const", "prevProviderValues", "=", "primaryWrapper", "[", "PROVIDER_VALUES", "]", ";", "primaryWrapper", ".", "setContext", "(", "{", "...", "wrappingComponent", "[", "PRIMARY_WRAPPER", "]", "[", "OPTIONS", "]", ".", "context", ",", "...", "legacyContext", ",", "}", ")", ";", "primaryWrapper", "[", "PROVIDER_VALUES", "]", "=", "new", "Map", "(", "[", "...", "prevProviderValues", ",", "...", "providerValues", "]", ")", ";", "if", "(", "typeof", "adapter", ".", "isContextConsumer", "===", "'function'", "&&", "adapter", ".", "isContextConsumer", "(", "primaryNode", ".", "type", ")", ")", "{", "const", "Consumer", "=", "primaryNode", ".", "type", ";", "// Adapters with an `isContextConsumer` method will definitely have a `getProviderFromConsumer`", "// method.", "const", "Provider", "=", "adapter", ".", "getProviderFromConsumer", "(", "Consumer", ")", ";", "const", "newValue", "=", "providerValues", ".", "get", "(", "Provider", ")", ";", "const", "oldValue", "=", "prevProviderValues", ".", "get", "(", "Provider", ")", ";", "// Use referential comparison like React", "if", "(", "newValue", "!==", "oldValue", ")", "{", "primaryWrapper", ".", "rerender", "(", ")", ";", "}", "}", "}" ]
Updates the context of the primary wrapper when the `wrappingComponent` re-renders.
[ "Updates", "the", "context", "of", "the", "primary", "wrapper", "when", "the", "wrappingComponent", "re", "-", "renders", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/ShallowWrapper.js#L1724-L1754
2,542
airbnb/enzyme
packages/enzyme/src/selectors.js
nodeMatchesToken
function nodeMatchesToken(node, token, root) { if (node === null || typeof node === 'string') { return false; } switch (token.type) { /** * Match every node * @example '*' matches every node */ case UNIVERSAL_SELECTOR: return true; /** * Match against the className prop * @example '.active' matches <div className='active' /> */ case CLASS_SELECTOR: return hasClassName(node, token.name); /** * Simple type matching * @example 'div' matches <div /> */ case TYPE_SELECTOR: return nodeHasType(node, token.name); /** * Match against the `id` prop * @example '#nav' matches <ul id="nav" /> */ case ID_SELECTOR: return nodeHasId(node, token.name); /** * Matches if an attribute is present, regardless * of its value * @example '[disabled]' matches <a disabled /> */ case ATTRIBUTE_PRESENCE: return matchAttributeSelector(node, token); /** * Matches if an attribute is present with the * provided value * @example '[data-foo=foo]' matches <div data-foo="foo" /> */ case ATTRIBUTE_VALUE: return matchAttributeSelector(node, token); case PSEUDO_ELEMENT: case PSEUDO_CLASS: return matchPseudoSelector(node, token, root); default: throw new Error(`Unknown token type: ${token.type}`); } }
javascript
function nodeMatchesToken(node, token, root) { if (node === null || typeof node === 'string') { return false; } switch (token.type) { /** * Match every node * @example '*' matches every node */ case UNIVERSAL_SELECTOR: return true; /** * Match against the className prop * @example '.active' matches <div className='active' /> */ case CLASS_SELECTOR: return hasClassName(node, token.name); /** * Simple type matching * @example 'div' matches <div /> */ case TYPE_SELECTOR: return nodeHasType(node, token.name); /** * Match against the `id` prop * @example '#nav' matches <ul id="nav" /> */ case ID_SELECTOR: return nodeHasId(node, token.name); /** * Matches if an attribute is present, regardless * of its value * @example '[disabled]' matches <a disabled /> */ case ATTRIBUTE_PRESENCE: return matchAttributeSelector(node, token); /** * Matches if an attribute is present with the * provided value * @example '[data-foo=foo]' matches <div data-foo="foo" /> */ case ATTRIBUTE_VALUE: return matchAttributeSelector(node, token); case PSEUDO_ELEMENT: case PSEUDO_CLASS: return matchPseudoSelector(node, token, root); default: throw new Error(`Unknown token type: ${token.type}`); } }
[ "function", "nodeMatchesToken", "(", "node", ",", "token", ",", "root", ")", "{", "if", "(", "node", "===", "null", "||", "typeof", "node", "===", "'string'", ")", "{", "return", "false", ";", "}", "switch", "(", "token", ".", "type", ")", "{", "/**\n * Match every node\n * @example '*' matches every node\n */", "case", "UNIVERSAL_SELECTOR", ":", "return", "true", ";", "/**\n * Match against the className prop\n * @example '.active' matches <div className='active' />\n */", "case", "CLASS_SELECTOR", ":", "return", "hasClassName", "(", "node", ",", "token", ".", "name", ")", ";", "/**\n * Simple type matching\n * @example 'div' matches <div />\n */", "case", "TYPE_SELECTOR", ":", "return", "nodeHasType", "(", "node", ",", "token", ".", "name", ")", ";", "/**\n * Match against the `id` prop\n * @example '#nav' matches <ul id=\"nav\" />\n */", "case", "ID_SELECTOR", ":", "return", "nodeHasId", "(", "node", ",", "token", ".", "name", ")", ";", "/**\n * Matches if an attribute is present, regardless\n * of its value\n * @example '[disabled]' matches <a disabled />\n */", "case", "ATTRIBUTE_PRESENCE", ":", "return", "matchAttributeSelector", "(", "node", ",", "token", ")", ";", "/**\n * Matches if an attribute is present with the\n * provided value\n * @example '[data-foo=foo]' matches <div data-foo=\"foo\" />\n */", "case", "ATTRIBUTE_VALUE", ":", "return", "matchAttributeSelector", "(", "node", ",", "token", ")", ";", "case", "PSEUDO_ELEMENT", ":", "case", "PSEUDO_CLASS", ":", "return", "matchPseudoSelector", "(", "node", ",", "token", ",", "root", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "token", ".", "type", "}", "`", ")", ";", "}", "}" ]
Takes a node and a token and determines if the node matches the predicate defined by the token. @param {Node} node @param {Token} token
[ "Takes", "a", "node", "and", "a", "token", "and", "determines", "if", "the", "node", "matches", "the", "predicate", "defined", "by", "the", "token", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L183-L232
2,543
airbnb/enzyme
packages/enzyme/src/selectors.js
buildPredicateFromToken
function buildPredicateFromToken(token, root) { return node => token.body.every(bodyToken => nodeMatchesToken(node, bodyToken, root)); }
javascript
function buildPredicateFromToken(token, root) { return node => token.body.every(bodyToken => nodeMatchesToken(node, bodyToken, root)); }
[ "function", "buildPredicateFromToken", "(", "token", ",", "root", ")", "{", "return", "node", "=>", "token", ".", "body", ".", "every", "(", "bodyToken", "=>", "nodeMatchesToken", "(", "node", ",", "bodyToken", ",", "root", ")", ")", ";", "}" ]
Returns a predicate function that checks if a node matches every token in the body of a selector token. @param {Token} token
[ "Returns", "a", "predicate", "function", "that", "checks", "if", "a", "node", "matches", "every", "token", "in", "the", "body", "of", "a", "selector", "token", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L240-L242
2,544
airbnb/enzyme
packages/enzyme/src/selectors.js
matchDescendant
function matchDescendant(nodes, predicate) { return uniqueReduce( (matches, node) => matches.concat(treeFilter(node, predicate)), flat(nodes.map(childrenOfNode)), ); }
javascript
function matchDescendant(nodes, predicate) { return uniqueReduce( (matches, node) => matches.concat(treeFilter(node, predicate)), flat(nodes.map(childrenOfNode)), ); }
[ "function", "matchDescendant", "(", "nodes", ",", "predicate", ")", "{", "return", "uniqueReduce", "(", "(", "matches", ",", "node", ")", "=>", "matches", ".", "concat", "(", "treeFilter", "(", "node", ",", "predicate", ")", ")", ",", "flat", "(", "nodes", ".", "map", "(", "childrenOfNode", ")", ")", ",", ")", ";", "}" ]
Matches all descendant nodes against a predicate, returning those that match. @param {Array<Node>} nodes @param {Function} predicate
[ "Matches", "all", "descendant", "nodes", "against", "a", "predicate", "returning", "those", "that", "match", "." ]
cd430eae95eba151f17e970ee77c18f09476de0e
https://github.com/airbnb/enzyme/blob/cd430eae95eba151f17e970ee77c18f09476de0e/packages/enzyme/src/selectors.js#L361-L366
2,545
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getEntry
function getEntry(knownHashes, url, revision) { // We're assuming that if the URL contains any of the known hashes // (either the short or full chunk hash or compilation hash) then it's // already revisioned, and we don't need additional out-of-band revisioning. if (!revision || knownHashes.some((hash) => url.includes(hash))) { return {url}; } return {revision, url}; }
javascript
function getEntry(knownHashes, url, revision) { // We're assuming that if the URL contains any of the known hashes // (either the short or full chunk hash or compilation hash) then it's // already revisioned, and we don't need additional out-of-band revisioning. if (!revision || knownHashes.some((hash) => url.includes(hash))) { return {url}; } return {revision, url}; }
[ "function", "getEntry", "(", "knownHashes", ",", "url", ",", "revision", ")", "{", "// We're assuming that if the URL contains any of the known hashes", "// (either the short or full chunk hash or compilation hash) then it's", "// already revisioned, and we don't need additional out-of-band revisioning.", "if", "(", "!", "revision", "||", "knownHashes", ".", "some", "(", "(", "hash", ")", "=>", "url", ".", "includes", "(", "hash", ")", ")", ")", "{", "return", "{", "url", "}", ";", "}", "return", "{", "revision", ",", "url", "}", ";", "}" ]
A single manifest entry that Workbox can precache. When possible, we leave out the revision information, which tells Workbox that the URL contains enough info to uniquely version the asset. @param {Array<string>} knownHashes All of the hashes that are associated with this webpack build. @param {string} url webpack asset url path @param {string} [revision] A revision hash for the entry @return {module:workbox-build.ManifestEntry} A single manifest entry @private
[ "A", "single", "manifest", "entry", "that", "Workbox", "can", "precache", ".", "When", "possible", "we", "leave", "out", "the", "revision", "information", "which", "tells", "Workbox", "that", "the", "URL", "contains", "enough", "info", "to", "uniquely", "version", "the", "asset", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L27-L35
2,546
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getKnownHashesFromAssets
function getKnownHashesFromAssets(assetMetadata) { const knownHashes = new Set(); for (const metadata of Object.values(assetMetadata)) { knownHashes.add(metadata.hash); } return knownHashes; }
javascript
function getKnownHashesFromAssets(assetMetadata) { const knownHashes = new Set(); for (const metadata of Object.values(assetMetadata)) { knownHashes.add(metadata.hash); } return knownHashes; }
[ "function", "getKnownHashesFromAssets", "(", "assetMetadata", ")", "{", "const", "knownHashes", "=", "new", "Set", "(", ")", ";", "for", "(", "const", "metadata", "of", "Object", ".", "values", "(", "assetMetadata", ")", ")", "{", "knownHashes", ".", "add", "(", "metadata", ".", "hash", ")", ";", "}", "return", "knownHashes", ";", "}" ]
Given an assetMetadata mapping, returns a Set of all of the hashes that are associated with at least one asset. @param {Object<string, Object>} assetMetadata Mapping of asset paths to chunk name and hash metadata. @return {Set} The known hashes associated with an asset. @private
[ "Given", "an", "assetMetadata", "mapping", "returns", "a", "Set", "of", "all", "of", "the", "hashes", "that", "are", "associated", "with", "at", "least", "one", "asset", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L139-L145
2,547
GoogleChrome/workbox
packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js
getManifestEntriesFromCompilation
function getManifestEntriesFromCompilation(compilation, config) { const blacklistedChunkNames = config.excludeChunks; const whitelistedChunkNames = config.chunks; const {assets, chunks} = compilation; const {publicPath} = compilation.options.output; const assetMetadata = generateMetadataForAssets(assets, chunks); const filteredAssetMetadata = filterAssets(assetMetadata, whitelistedChunkNames, blacklistedChunkNames); const knownHashes = [ compilation.hash, compilation.fullHash, ...getKnownHashesFromAssets(filteredAssetMetadata), ].filter((hash) => !!hash); const manifestEntries = []; for (const [file, metadata] of Object.entries(filteredAssetMetadata)) { // Filter based on test/include/exclude options set in the config, // following webpack's conventions. // This matches the behavior of, e.g., UglifyJS's webpack plugin. if (!ModuleFilenameHelpers.matchObject(config, file)) { continue; } const publicURL = resolveWebpackURL(publicPath, file); const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash); manifestEntries.push(manifestEntry); } return manifestEntries; }
javascript
function getManifestEntriesFromCompilation(compilation, config) { const blacklistedChunkNames = config.excludeChunks; const whitelistedChunkNames = config.chunks; const {assets, chunks} = compilation; const {publicPath} = compilation.options.output; const assetMetadata = generateMetadataForAssets(assets, chunks); const filteredAssetMetadata = filterAssets(assetMetadata, whitelistedChunkNames, blacklistedChunkNames); const knownHashes = [ compilation.hash, compilation.fullHash, ...getKnownHashesFromAssets(filteredAssetMetadata), ].filter((hash) => !!hash); const manifestEntries = []; for (const [file, metadata] of Object.entries(filteredAssetMetadata)) { // Filter based on test/include/exclude options set in the config, // following webpack's conventions. // This matches the behavior of, e.g., UglifyJS's webpack plugin. if (!ModuleFilenameHelpers.matchObject(config, file)) { continue; } const publicURL = resolveWebpackURL(publicPath, file); const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash); manifestEntries.push(manifestEntry); } return manifestEntries; }
[ "function", "getManifestEntriesFromCompilation", "(", "compilation", ",", "config", ")", "{", "const", "blacklistedChunkNames", "=", "config", ".", "excludeChunks", ";", "const", "whitelistedChunkNames", "=", "config", ".", "chunks", ";", "const", "{", "assets", ",", "chunks", "}", "=", "compilation", ";", "const", "{", "publicPath", "}", "=", "compilation", ".", "options", ".", "output", ";", "const", "assetMetadata", "=", "generateMetadataForAssets", "(", "assets", ",", "chunks", ")", ";", "const", "filteredAssetMetadata", "=", "filterAssets", "(", "assetMetadata", ",", "whitelistedChunkNames", ",", "blacklistedChunkNames", ")", ";", "const", "knownHashes", "=", "[", "compilation", ".", "hash", ",", "compilation", ".", "fullHash", ",", "...", "getKnownHashesFromAssets", "(", "filteredAssetMetadata", ")", ",", "]", ".", "filter", "(", "(", "hash", ")", "=>", "!", "!", "hash", ")", ";", "const", "manifestEntries", "=", "[", "]", ";", "for", "(", "const", "[", "file", ",", "metadata", "]", "of", "Object", ".", "entries", "(", "filteredAssetMetadata", ")", ")", "{", "// Filter based on test/include/exclude options set in the config,", "// following webpack's conventions.", "// This matches the behavior of, e.g., UglifyJS's webpack plugin.", "if", "(", "!", "ModuleFilenameHelpers", ".", "matchObject", "(", "config", ",", "file", ")", ")", "{", "continue", ";", "}", "const", "publicURL", "=", "resolveWebpackURL", "(", "publicPath", ",", "file", ")", ";", "const", "manifestEntry", "=", "getEntry", "(", "knownHashes", ",", "publicURL", ",", "metadata", ".", "hash", ")", ";", "manifestEntries", ".", "push", "(", "manifestEntry", ")", ";", "}", "return", "manifestEntries", ";", "}" ]
Generate an array of manifest entries using webpack's compilation data. @param {Object} compilation webpack compilation @param {Object} config @return {Array<workbox.build.ManifestEntry>} @private
[ "Generate", "an", "array", "of", "manifest", "entries", "using", "webpack", "s", "compilation", "data", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.js#L156-L186
2,548
GoogleChrome/workbox
packages/workbox-build/src/lib/runtime-caching-converter.js
getOptionsString
function getOptionsString(options = {}) { let plugins = []; if (options.plugins) { // Using libs because JSON.stringify won't handle functions. plugins = options.plugins.map(stringifyWithoutComments); delete options.plugins; } // Pull handler-specific config from the options object, since they are // not directly used to construct a Plugin instance. If set, need to be // passed as options to the handler constructor instead. const handlerOptionKeys = [ 'cacheName', 'networkTimeoutSeconds', 'fetchOptions', 'matchOptions', ]; const handlerOptions = {}; for (const key of handlerOptionKeys) { if (key in options) { handlerOptions[key] = options[key]; delete options[key]; } } const pluginsMapping = { backgroundSync: 'workbox.backgroundSync.Plugin', broadcastUpdate: 'workbox.broadcastUpdate.Plugin', expiration: 'workbox.expiration.Plugin', cacheableResponse: 'workbox.cacheableResponse.Plugin', }; for (const [pluginName, pluginConfig] of Object.entries(options)) { // Ensure that we have some valid configuration to pass to Plugin(). if (Object.keys(pluginConfig).length === 0) { continue; } const pluginString = pluginsMapping[pluginName]; if (!pluginString) { throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); } let pluginCode; switch (pluginName) { // Special case logic for plugins that have a required parameter, and then // an additional optional config parameter. case 'backgroundSync': { const name = pluginConfig.name; pluginCode = `new ${pluginString}(${JSON.stringify(name)}`; if ('options' in pluginConfig) { pluginCode += `, ${stringifyWithoutComments(pluginConfig.options)}`; } pluginCode += `)`; break; } case 'broadcastUpdate': { const channelName = pluginConfig.channelName; const opts = Object.assign({channelName}, pluginConfig.options); pluginCode = `new ${pluginString}(${stringifyWithoutComments(opts)})`; break; } // For plugins that just pass in an Object to the constructor, like // expiration and cacheableResponse default: { pluginCode = `new ${pluginString}(${stringifyWithoutComments( pluginConfig )})`; } } plugins.push(pluginCode); } if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { const optionsString = JSON.stringify(handlerOptions).slice(1, -1); return ol`{ ${optionsString ? optionsString + ',' : ''} plugins: [${plugins.join(', ')}] }`; } else { return ''; } }
javascript
function getOptionsString(options = {}) { let plugins = []; if (options.plugins) { // Using libs because JSON.stringify won't handle functions. plugins = options.plugins.map(stringifyWithoutComments); delete options.plugins; } // Pull handler-specific config from the options object, since they are // not directly used to construct a Plugin instance. If set, need to be // passed as options to the handler constructor instead. const handlerOptionKeys = [ 'cacheName', 'networkTimeoutSeconds', 'fetchOptions', 'matchOptions', ]; const handlerOptions = {}; for (const key of handlerOptionKeys) { if (key in options) { handlerOptions[key] = options[key]; delete options[key]; } } const pluginsMapping = { backgroundSync: 'workbox.backgroundSync.Plugin', broadcastUpdate: 'workbox.broadcastUpdate.Plugin', expiration: 'workbox.expiration.Plugin', cacheableResponse: 'workbox.cacheableResponse.Plugin', }; for (const [pluginName, pluginConfig] of Object.entries(options)) { // Ensure that we have some valid configuration to pass to Plugin(). if (Object.keys(pluginConfig).length === 0) { continue; } const pluginString = pluginsMapping[pluginName]; if (!pluginString) { throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); } let pluginCode; switch (pluginName) { // Special case logic for plugins that have a required parameter, and then // an additional optional config parameter. case 'backgroundSync': { const name = pluginConfig.name; pluginCode = `new ${pluginString}(${JSON.stringify(name)}`; if ('options' in pluginConfig) { pluginCode += `, ${stringifyWithoutComments(pluginConfig.options)}`; } pluginCode += `)`; break; } case 'broadcastUpdate': { const channelName = pluginConfig.channelName; const opts = Object.assign({channelName}, pluginConfig.options); pluginCode = `new ${pluginString}(${stringifyWithoutComments(opts)})`; break; } // For plugins that just pass in an Object to the constructor, like // expiration and cacheableResponse default: { pluginCode = `new ${pluginString}(${stringifyWithoutComments( pluginConfig )})`; } } plugins.push(pluginCode); } if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) { const optionsString = JSON.stringify(handlerOptions).slice(1, -1); return ol`{ ${optionsString ? optionsString + ',' : ''} plugins: [${plugins.join(', ')}] }`; } else { return ''; } }
[ "function", "getOptionsString", "(", "options", "=", "{", "}", ")", "{", "let", "plugins", "=", "[", "]", ";", "if", "(", "options", ".", "plugins", ")", "{", "// Using libs because JSON.stringify won't handle functions.", "plugins", "=", "options", ".", "plugins", ".", "map", "(", "stringifyWithoutComments", ")", ";", "delete", "options", ".", "plugins", ";", "}", "// Pull handler-specific config from the options object, since they are", "// not directly used to construct a Plugin instance. If set, need to be", "// passed as options to the handler constructor instead.", "const", "handlerOptionKeys", "=", "[", "'cacheName'", ",", "'networkTimeoutSeconds'", ",", "'fetchOptions'", ",", "'matchOptions'", ",", "]", ";", "const", "handlerOptions", "=", "{", "}", ";", "for", "(", "const", "key", "of", "handlerOptionKeys", ")", "{", "if", "(", "key", "in", "options", ")", "{", "handlerOptions", "[", "key", "]", "=", "options", "[", "key", "]", ";", "delete", "options", "[", "key", "]", ";", "}", "}", "const", "pluginsMapping", "=", "{", "backgroundSync", ":", "'workbox.backgroundSync.Plugin'", ",", "broadcastUpdate", ":", "'workbox.broadcastUpdate.Plugin'", ",", "expiration", ":", "'workbox.expiration.Plugin'", ",", "cacheableResponse", ":", "'workbox.cacheableResponse.Plugin'", ",", "}", ";", "for", "(", "const", "[", "pluginName", ",", "pluginConfig", "]", "of", "Object", ".", "entries", "(", "options", ")", ")", "{", "// Ensure that we have some valid configuration to pass to Plugin().", "if", "(", "Object", ".", "keys", "(", "pluginConfig", ")", ".", "length", "===", "0", ")", "{", "continue", ";", "}", "const", "pluginString", "=", "pluginsMapping", "[", "pluginName", "]", ";", "if", "(", "!", "pluginString", ")", "{", "throw", "new", "Error", "(", "`", "${", "errors", "[", "'bad-runtime-caching-config'", "]", "}", "${", "pluginName", "}", "`", ")", ";", "}", "let", "pluginCode", ";", "switch", "(", "pluginName", ")", "{", "// Special case logic for plugins that have a required parameter, and then", "// an additional optional config parameter.", "case", "'backgroundSync'", ":", "{", "const", "name", "=", "pluginConfig", ".", "name", ";", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "JSON", ".", "stringify", "(", "name", ")", "}", "`", ";", "if", "(", "'options'", "in", "pluginConfig", ")", "{", "pluginCode", "+=", "`", "${", "stringifyWithoutComments", "(", "pluginConfig", ".", "options", ")", "}", "`", ";", "}", "pluginCode", "+=", "`", "`", ";", "break", ";", "}", "case", "'broadcastUpdate'", ":", "{", "const", "channelName", "=", "pluginConfig", ".", "channelName", ";", "const", "opts", "=", "Object", ".", "assign", "(", "{", "channelName", "}", ",", "pluginConfig", ".", "options", ")", ";", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "stringifyWithoutComments", "(", "opts", ")", "}", "`", ";", "break", ";", "}", "// For plugins that just pass in an Object to the constructor, like", "// expiration and cacheableResponse", "default", ":", "{", "pluginCode", "=", "`", "${", "pluginString", "}", "${", "stringifyWithoutComments", "(", "pluginConfig", ")", "}", "`", ";", "}", "}", "plugins", ".", "push", "(", "pluginCode", ")", ";", "}", "if", "(", "Object", ".", "keys", "(", "handlerOptions", ")", ".", "length", ">", "0", "||", "plugins", ".", "length", ">", "0", ")", "{", "const", "optionsString", "=", "JSON", ".", "stringify", "(", "handlerOptions", ")", ".", "slice", "(", "1", ",", "-", "1", ")", ";", "return", "ol", "`", "${", "optionsString", "?", "optionsString", "+", "','", ":", "''", "}", "${", "plugins", ".", "join", "(", "', '", ")", "}", "`", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Given a set of options that configures `sw-toolbox`'s behavior, convert it into a string that would configure equivalent `workbox-sw` behavior. @param {Object} options See https://googlechromelabs.github.io/sw-toolbox/api.html#options @return {string} A JSON string representing the equivalent options. @private
[ "Given", "a", "set", "of", "options", "that", "configures", "sw", "-", "toolbox", "s", "behavior", "convert", "it", "into", "a", "string", "that", "would", "configure", "equivalent", "workbox", "-", "sw", "behavior", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/lib/runtime-caching-converter.js#L24-L111
2,549
GoogleChrome/workbox
packages/workbox-build/src/entry-points/generate-sw-string.js
generateSWString
async function generateSWString(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, generateSWStringSchema); const {manifestEntries, warnings} = await getFileManifestEntries(options); const swString = await populateSWTemplate(Object.assign({ manifestEntries, }, options)); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {swString, warnings}; }
javascript
async function generateSWString(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, generateSWStringSchema); const {manifestEntries, warnings} = await getFileManifestEntries(options); const swString = await populateSWTemplate(Object.assign({ manifestEntries, }, options)); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {swString, warnings}; }
[ "async", "function", "generateSWString", "(", "config", ")", "{", "// This check needs to be done before validation, since the deprecated options", "// will be renamed.", "const", "deprecationWarnings", "=", "checkForDeprecatedOptions", "(", "config", ")", ";", "const", "options", "=", "validate", "(", "config", ",", "generateSWStringSchema", ")", ";", "const", "{", "manifestEntries", ",", "warnings", "}", "=", "await", "getFileManifestEntries", "(", "options", ")", ";", "const", "swString", "=", "await", "populateSWTemplate", "(", "Object", ".", "assign", "(", "{", "manifestEntries", ",", "}", ",", "options", ")", ")", ";", "// Add in any deprecation warnings.", "warnings", ".", "push", "(", "...", "deprecationWarnings", ")", ";", "return", "{", "swString", ",", "warnings", "}", ";", "}" ]
This method generates a service worker based on the configuration options provided. @param {Object} config Please refer to the [configuration guide](https://developers.google.com/web/tools/workbox/modules/workbox-build#generateswstring_mode). @return {Promise<{swString: string, warnings: Array<string>}>} A promise that resolves once the service worker template is populated. The `swString` property contains a string representation of the full service worker code. Any non-fatal warning messages will be returned via `warnings`. @memberof module:workbox-build
[ "This", "method", "generates", "a", "service", "worker", "based", "on", "the", "configuration", "options", "provided", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/entry-points/generate-sw-string.js#L29-L46
2,550
GoogleChrome/workbox
packages/workbox-cli/src/app.js
runBuildCommand
async function runBuildCommand({command, config, watch}) { try { const {size, count, warnings} = await workboxBuild[command](config); for (const warning of warnings) { logger.warn(warning); } logger.log(`The service worker was written to ${config.swDest}\n` + `${count} files will be precached, totalling ${prettyBytes(size)}.`); if (watch) { logger.log(`\nWatching for changes...`); } } catch (error) { // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors if (typeof error.annotate === 'function') { throw new Error( `${errors['config-validation-failed']}\n${error.annotate()}`); } logger.error(errors['workbox-build-runtime-error']); throw error; } }
javascript
async function runBuildCommand({command, config, watch}) { try { const {size, count, warnings} = await workboxBuild[command](config); for (const warning of warnings) { logger.warn(warning); } logger.log(`The service worker was written to ${config.swDest}\n` + `${count} files will be precached, totalling ${prettyBytes(size)}.`); if (watch) { logger.log(`\nWatching for changes...`); } } catch (error) { // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors if (typeof error.annotate === 'function') { throw new Error( `${errors['config-validation-failed']}\n${error.annotate()}`); } logger.error(errors['workbox-build-runtime-error']); throw error; } }
[ "async", "function", "runBuildCommand", "(", "{", "command", ",", "config", ",", "watch", "}", ")", "{", "try", "{", "const", "{", "size", ",", "count", ",", "warnings", "}", "=", "await", "workboxBuild", "[", "command", "]", "(", "config", ")", ";", "for", "(", "const", "warning", "of", "warnings", ")", "{", "logger", ".", "warn", "(", "warning", ")", ";", "}", "logger", ".", "log", "(", "`", "${", "config", ".", "swDest", "}", "\\n", "`", "+", "`", "${", "count", "}", "${", "prettyBytes", "(", "size", ")", "}", "`", ")", ";", "if", "(", "watch", ")", "{", "logger", ".", "log", "(", "`", "\\n", "`", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "// See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors", "if", "(", "typeof", "error", ".", "annotate", "===", "'function'", ")", "{", "throw", "new", "Error", "(", "`", "${", "errors", "[", "'config-validation-failed'", "]", "}", "\\n", "${", "error", ".", "annotate", "(", ")", "}", "`", ")", ";", "}", "logger", ".", "error", "(", "errors", "[", "'workbox-build-runtime-error'", "]", ")", ";", "throw", "error", ";", "}", "}" ]
Runs the specified build command with the provided configuration. @param {Object} options
[ "Runs", "the", "specified", "build", "command", "with", "the", "provided", "configuration", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-cli/src/app.js#L27-L50
2,551
GoogleChrome/workbox
packages/workbox-build/src/entry-points/get-manifest.js
getManifest
async function getManifest(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, getManifestSchema); const {manifestEntries, count, size, warnings} = await getFileManifestEntries(options); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {manifestEntries, count, size, warnings}; }
javascript
async function getManifest(config) { // This check needs to be done before validation, since the deprecated options // will be renamed. const deprecationWarnings = checkForDeprecatedOptions(config); const options = validate(config, getManifestSchema); const {manifestEntries, count, size, warnings} = await getFileManifestEntries(options); // Add in any deprecation warnings. warnings.push(...deprecationWarnings); return {manifestEntries, count, size, warnings}; }
[ "async", "function", "getManifest", "(", "config", ")", "{", "// This check needs to be done before validation, since the deprecated options", "// will be renamed.", "const", "deprecationWarnings", "=", "checkForDeprecatedOptions", "(", "config", ")", ";", "const", "options", "=", "validate", "(", "config", ",", "getManifestSchema", ")", ";", "const", "{", "manifestEntries", ",", "count", ",", "size", ",", "warnings", "}", "=", "await", "getFileManifestEntries", "(", "options", ")", ";", "// Add in any deprecation warnings.", "warnings", ".", "push", "(", "...", "deprecationWarnings", ")", ";", "return", "{", "manifestEntries", ",", "count", ",", "size", ",", "warnings", "}", ";", "}" ]
This method returns a list of URLs to precache, referred to as a "precache manifest", along with details about the number of entries and their size, based on the options you provide. @param {Object} config Please refer to the [configuration guide](https://developers.google.com/web/tools/workbox/modules/workbox-build#getmanifest_mode). @return {Promise<{manifestEntries: Array<ManifestEntry>, count: number, size: number, warnings: Array<string>}>} A promise that resolves once the precache manifest is determined. The `size` property contains the aggregate size of all the precached entries, in bytes, the `count` property contains the total number of precached entries, and the `manifestEntries` property contains all the `ManifestEntry` items. Any non-fatal warning messages will be returned via `warnings`. @memberof module:workbox-build
[ "This", "method", "returns", "a", "list", "of", "URLs", "to", "precache", "referred", "to", "as", "a", "precache", "manifest", "along", "with", "details", "about", "the", "number", "of", "entries", "and", "their", "size", "based", "on", "the", "options", "you", "provide", "." ]
8379c51b6deaf52faed5879206fe84579cae41f0
https://github.com/GoogleChrome/workbox/blob/8379c51b6deaf52faed5879206fe84579cae41f0/packages/workbox-build/src/entry-points/get-manifest.js#L32-L46
2,552
tgriesser/knex
src/seed/Seeder.js
Seeder
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
javascript
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
[ "function", "Seeder", "(", "knex", ")", "{", "this", ".", "knex", "=", "knex", ";", "this", ".", "config", "=", "this", ".", "setConfig", "(", "knex", ".", "client", ".", "config", ".", "seeds", ")", ";", "}" ]
The new seeds we're performing, typically called from the `knex.seed` interface on the main `knex` object. Passes the `knex` instance performing the seeds.
[ "The", "new", "seeds", "we", "re", "performing", "typically", "called", "from", "the", "knex", ".", "seed", "interface", "on", "the", "main", "knex", "object", ".", "Passes", "the", "knex", "instance", "performing", "the", "seeds", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/seed/Seeder.js#L13-L16
2,553
tgriesser/knex
src/query/joinclause.js
JoinClause
function JoinClause(table, type, schema) { this.schema = schema; this.table = table; this.joinType = type; this.and = this; this.clauses = []; }
javascript
function JoinClause(table, type, schema) { this.schema = schema; this.table = table; this.joinType = type; this.and = this; this.clauses = []; }
[ "function", "JoinClause", "(", "table", ",", "type", ",", "schema", ")", "{", "this", ".", "schema", "=", "schema", ";", "this", ".", "table", "=", "table", ";", "this", ".", "joinType", "=", "type", ";", "this", ".", "and", "=", "this", ";", "this", ".", "clauses", "=", "[", "]", ";", "}" ]
The "JoinClause" is an object holding any necessary info about a join, including the type, and any associated tables & columns being joined.
[ "The", "JoinClause", "is", "an", "object", "holding", "any", "necessary", "info", "about", "a", "join", "including", "the", "type", "and", "any", "associated", "tables", "&", "columns", "being", "joined", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/query/joinclause.js#L9-L15
2,554
tgriesser/knex
src/migrate/MigrationGenerator.js
yyyymmddhhmmss
function yyyymmddhhmmss() { const d = new Date(); return ( d.getFullYear().toString() + padDate(d.getMonth() + 1) + padDate(d.getDate()) + padDate(d.getHours()) + padDate(d.getMinutes()) + padDate(d.getSeconds()) ); }
javascript
function yyyymmddhhmmss() { const d = new Date(); return ( d.getFullYear().toString() + padDate(d.getMonth() + 1) + padDate(d.getDate()) + padDate(d.getHours()) + padDate(d.getMinutes()) + padDate(d.getSeconds()) ); }
[ "function", "yyyymmddhhmmss", "(", ")", "{", "const", "d", "=", "new", "Date", "(", ")", ";", "return", "(", "d", ".", "getFullYear", "(", ")", ".", "toString", "(", ")", "+", "padDate", "(", "d", ".", "getMonth", "(", ")", "+", "1", ")", "+", "padDate", "(", "d", ".", "getDate", "(", ")", ")", "+", "padDate", "(", "d", ".", "getHours", "(", ")", ")", "+", "padDate", "(", "d", ".", "getMinutes", "(", ")", ")", "+", "padDate", "(", "d", ".", "getSeconds", "(", ")", ")", ")", ";", "}" ]
Get a date object in the correct format, without requiring a full out library like "moment.js".
[ "Get", "a", "date", "object", "in", "the", "correct", "format", "without", "requiring", "a", "full", "out", "library", "like", "moment", ".", "js", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/MigrationGenerator.js#L87-L97
2,555
tgriesser/knex
src/schema/builder.js
SchemaBuilder
function SchemaBuilder(client) { this.client = client; this._sequence = []; if (client.config) { this._debug = client.config.debug; saveAsyncStack(this, 4); } }
javascript
function SchemaBuilder(client) { this.client = client; this._sequence = []; if (client.config) { this._debug = client.config.debug; saveAsyncStack(this, 4); } }
[ "function", "SchemaBuilder", "(", "client", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "_sequence", "=", "[", "]", ";", "if", "(", "client", ".", "config", ")", "{", "this", ".", "_debug", "=", "client", ".", "config", ".", "debug", ";", "saveAsyncStack", "(", "this", ",", "4", ")", ";", "}", "}" ]
Constructor for the builder instance, typically called from `knex.builder`, accepting the current `knex` instance, and pulling out the `client` and `grammar` from the current knex instance.
[ "Constructor", "for", "the", "builder", "instance", "typically", "called", "from", "knex", ".", "builder", "accepting", "the", "current", "knex", "instance", "and", "pulling", "out", "the", "client", "and", "grammar", "from", "the", "current", "knex", "instance", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/schema/builder.js#L11-L19
2,556
tgriesser/knex
src/client.js
Client
function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
javascript
function Client(config = {}) { this.config = config; this.logger = new Logger(config); //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (this.dialect && !this.config.client) { this.logger.warn( `Using 'this.dialect' to identify the client is deprecated and support for it will be removed in the future. Please use configuration option 'client' instead.` ); } const dbClient = this.config.client || this.dialect; if (!dbClient) { throw new Error(`knex: Required configuration option 'client' is missing.`); } if (config.version) { this.version = config.version; } this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || (config.pool && config.pool.max !== 0)) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
[ "function", "Client", "(", "config", "=", "{", "}", ")", "{", "this", ".", "config", "=", "config", ";", "this", ".", "logger", "=", "new", "Logger", "(", "config", ")", ";", "//Client is a required field, so throw error if it's not supplied.", "//If 'this.dialect' is set, then this is a 'super()' call, in which case", "//'client' does not have to be set as it's already assigned on the client prototype.", "if", "(", "this", ".", "dialect", "&&", "!", "this", ".", "config", ".", "client", ")", "{", "this", ".", "logger", ".", "warn", "(", "`", "`", ")", ";", "}", "const", "dbClient", "=", "this", ".", "config", ".", "client", "||", "this", ".", "dialect", ";", "if", "(", "!", "dbClient", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "if", "(", "config", ".", "version", ")", "{", "this", ".", "version", "=", "config", ".", "version", ";", "}", "this", ".", "connectionSettings", "=", "cloneDeep", "(", "config", ".", "connection", "||", "{", "}", ")", ";", "if", "(", "this", ".", "driverName", "&&", "config", ".", "connection", ")", "{", "this", ".", "initializeDriver", "(", ")", ";", "if", "(", "!", "config", ".", "pool", "||", "(", "config", ".", "pool", "&&", "config", ".", "pool", ".", "max", "!==", "0", ")", ")", "{", "this", ".", "initializePool", "(", "config", ")", ";", "}", "}", "this", ".", "valueForUndefined", "=", "this", ".", "raw", "(", "'DEFAULT'", ")", ";", "if", "(", "config", ".", "useNullAsDefault", ")", "{", "this", ".", "valueForUndefined", "=", "null", ";", "}", "}" ]
The base client provides the general structure for a dialect specific client object.
[ "The", "base", "client", "provides", "the", "general", "structure", "for", "a", "dialect", "specific", "client", "object", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/client.js#L35-L68
2,557
tgriesser/knex
src/dialects/sqlite3/schema/ddl.js
SQLite3_DDL
function SQLite3_DDL(client, tableCompiler, pragma, connection) { this.client = client; this.tableCompiler = tableCompiler; this.pragma = pragma; this.tableNameRaw = this.tableCompiler.tableNameRaw; this.alteredName = uniqueId('_knex_temp_alter'); this.connection = connection; this.formatter = client && client.config && client.config.wrapIdentifier ? client.config.wrapIdentifier : (value) => value; }
javascript
function SQLite3_DDL(client, tableCompiler, pragma, connection) { this.client = client; this.tableCompiler = tableCompiler; this.pragma = pragma; this.tableNameRaw = this.tableCompiler.tableNameRaw; this.alteredName = uniqueId('_knex_temp_alter'); this.connection = connection; this.formatter = client && client.config && client.config.wrapIdentifier ? client.config.wrapIdentifier : (value) => value; }
[ "function", "SQLite3_DDL", "(", "client", ",", "tableCompiler", ",", "pragma", ",", "connection", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "tableCompiler", "=", "tableCompiler", ";", "this", ".", "pragma", "=", "pragma", ";", "this", ".", "tableNameRaw", "=", "this", ".", "tableCompiler", ".", "tableNameRaw", ";", "this", ".", "alteredName", "=", "uniqueId", "(", "'_knex_temp_alter'", ")", ";", "this", ".", "connection", "=", "connection", ";", "this", ".", "formatter", "=", "client", "&&", "client", ".", "config", "&&", "client", ".", "config", ".", "wrapIdentifier", "?", "client", ".", "config", ".", "wrapIdentifier", ":", "(", "value", ")", "=>", "value", ";", "}" ]
So altering the schema in SQLite3 is a major pain. We have our own object to deal with the renaming and altering the types for sqlite3 things.
[ "So", "altering", "the", "schema", "in", "SQLite3", "is", "a", "major", "pain", ".", "We", "have", "our", "own", "object", "to", "deal", "with", "the", "renaming", "and", "altering", "the", "types", "for", "sqlite3", "things", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/dialects/sqlite3/schema/ddl.js#L22-L33
2,558
tgriesser/knex
src/transaction.js
makeTransactor
function makeTransactor(trx, connection, trxClient) { const transactor = makeKnex(trxClient); transactor.withUserParams = () => { throw new Error( 'Cannot set user params on a transaction - it can only inherit params from main knex instance' ); }; transactor.isTransaction = true; transactor.userParams = trx.userParams || {}; transactor.transaction = function(container, options) { return trxClient.transaction(container, options, trx); }; transactor.savepoint = function(container, options) { return transactor.transaction(container, options); }; if (trx.client.transacting) { transactor.commit = (value) => trx.release(connection, value); transactor.rollback = (error) => trx.rollbackTo(connection, error); } else { transactor.commit = (value) => trx.commit(connection, value); transactor.rollback = (error) => trx.rollback(connection, error); } return transactor; }
javascript
function makeTransactor(trx, connection, trxClient) { const transactor = makeKnex(trxClient); transactor.withUserParams = () => { throw new Error( 'Cannot set user params on a transaction - it can only inherit params from main knex instance' ); }; transactor.isTransaction = true; transactor.userParams = trx.userParams || {}; transactor.transaction = function(container, options) { return trxClient.transaction(container, options, trx); }; transactor.savepoint = function(container, options) { return transactor.transaction(container, options); }; if (trx.client.transacting) { transactor.commit = (value) => trx.release(connection, value); transactor.rollback = (error) => trx.rollbackTo(connection, error); } else { transactor.commit = (value) => trx.commit(connection, value); transactor.rollback = (error) => trx.rollback(connection, error); } return transactor; }
[ "function", "makeTransactor", "(", "trx", ",", "connection", ",", "trxClient", ")", "{", "const", "transactor", "=", "makeKnex", "(", "trxClient", ")", ";", "transactor", ".", "withUserParams", "=", "(", ")", "=>", "{", "throw", "new", "Error", "(", "'Cannot set user params on a transaction - it can only inherit params from main knex instance'", ")", ";", "}", ";", "transactor", ".", "isTransaction", "=", "true", ";", "transactor", ".", "userParams", "=", "trx", ".", "userParams", "||", "{", "}", ";", "transactor", ".", "transaction", "=", "function", "(", "container", ",", "options", ")", "{", "return", "trxClient", ".", "transaction", "(", "container", ",", "options", ",", "trx", ")", ";", "}", ";", "transactor", ".", "savepoint", "=", "function", "(", "container", ",", "options", ")", "{", "return", "transactor", ".", "transaction", "(", "container", ",", "options", ")", ";", "}", ";", "if", "(", "trx", ".", "client", ".", "transacting", ")", "{", "transactor", ".", "commit", "=", "(", "value", ")", "=>", "trx", ".", "release", "(", "connection", ",", "value", ")", ";", "transactor", ".", "rollback", "=", "(", "error", ")", "=>", "trx", ".", "rollbackTo", "(", "connection", ",", "error", ")", ";", "}", "else", "{", "transactor", ".", "commit", "=", "(", "value", ")", "=>", "trx", ".", "commit", "(", "connection", ",", "value", ")", ";", "transactor", ".", "rollback", "=", "(", "error", ")", "=>", "trx", ".", "rollback", "(", "connection", ",", "error", ")", ";", "}", "return", "transactor", ";", "}" ]
The transactor is a full featured knex object, with a "commit", a "rollback" and a "savepoint" function. The "savepoint" is just sugar for creating a new transaction. If the rollback is run inside a savepoint, it rolls back to the last savepoint - otherwise it rolls back the transaction.
[ "The", "transactor", "is", "a", "full", "featured", "knex", "object", "with", "a", "commit", "a", "rollback", "and", "a", "savepoint", "function", ".", "The", "savepoint", "is", "just", "sugar", "for", "creating", "a", "new", "transaction", ".", "If", "the", "rollback", "is", "run", "inside", "a", "savepoint", "it", "rolls", "back", "to", "the", "last", "savepoint", "-", "otherwise", "it", "rolls", "back", "the", "transaction", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/transaction.js#L187-L215
2,559
tgriesser/knex
src/transaction.js
makeTxClient
function makeTxClient(trx, client, connection) { const trxClient = Object.create(client.constructor.prototype); trxClient.version = client.version; trxClient.config = client.config; trxClient.driver = client.driver; trxClient.connectionSettings = client.connectionSettings; trxClient.transacting = true; trxClient.valueForUndefined = client.valueForUndefined; trxClient.logger = client.logger; trxClient.on('query', function(arg) { trx.emit('query', arg); client.emit('query', arg); }); trxClient.on('query-error', function(err, obj) { trx.emit('query-error', err, obj); client.emit('query-error', err, obj); }); trxClient.on('query-response', function(response, obj, builder) { trx.emit('query-response', response, obj, builder); client.emit('query-response', response, obj, builder); }); const _query = trxClient.query; trxClient.query = function(conn, obj) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _query.call(trxClient, conn, obj); }); }; const _stream = trxClient.stream; trxClient.stream = function(conn, obj, stream, options) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _stream.call(trxClient, conn, obj, stream, options); }); }; trxClient.acquireConnection = function() { return Promise.resolve(connection); }; trxClient.releaseConnection = function() { return Promise.resolve(); }; return trxClient; }
javascript
function makeTxClient(trx, client, connection) { const trxClient = Object.create(client.constructor.prototype); trxClient.version = client.version; trxClient.config = client.config; trxClient.driver = client.driver; trxClient.connectionSettings = client.connectionSettings; trxClient.transacting = true; trxClient.valueForUndefined = client.valueForUndefined; trxClient.logger = client.logger; trxClient.on('query', function(arg) { trx.emit('query', arg); client.emit('query', arg); }); trxClient.on('query-error', function(err, obj) { trx.emit('query-error', err, obj); client.emit('query-error', err, obj); }); trxClient.on('query-response', function(response, obj, builder) { trx.emit('query-response', response, obj, builder); client.emit('query-response', response, obj, builder); }); const _query = trxClient.query; trxClient.query = function(conn, obj) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _query.call(trxClient, conn, obj); }); }; const _stream = trxClient.stream; trxClient.stream = function(conn, obj, stream, options) { const completed = trx.isCompleted(); return Promise.try(function() { if (conn !== connection) throw new Error('Invalid connection for transaction query.'); if (completed) completedError(trx, obj); return _stream.call(trxClient, conn, obj, stream, options); }); }; trxClient.acquireConnection = function() { return Promise.resolve(connection); }; trxClient.releaseConnection = function() { return Promise.resolve(); }; return trxClient; }
[ "function", "makeTxClient", "(", "trx", ",", "client", ",", "connection", ")", "{", "const", "trxClient", "=", "Object", ".", "create", "(", "client", ".", "constructor", ".", "prototype", ")", ";", "trxClient", ".", "version", "=", "client", ".", "version", ";", "trxClient", ".", "config", "=", "client", ".", "config", ";", "trxClient", ".", "driver", "=", "client", ".", "driver", ";", "trxClient", ".", "connectionSettings", "=", "client", ".", "connectionSettings", ";", "trxClient", ".", "transacting", "=", "true", ";", "trxClient", ".", "valueForUndefined", "=", "client", ".", "valueForUndefined", ";", "trxClient", ".", "logger", "=", "client", ".", "logger", ";", "trxClient", ".", "on", "(", "'query'", ",", "function", "(", "arg", ")", "{", "trx", ".", "emit", "(", "'query'", ",", "arg", ")", ";", "client", ".", "emit", "(", "'query'", ",", "arg", ")", ";", "}", ")", ";", "trxClient", ".", "on", "(", "'query-error'", ",", "function", "(", "err", ",", "obj", ")", "{", "trx", ".", "emit", "(", "'query-error'", ",", "err", ",", "obj", ")", ";", "client", ".", "emit", "(", "'query-error'", ",", "err", ",", "obj", ")", ";", "}", ")", ";", "trxClient", ".", "on", "(", "'query-response'", ",", "function", "(", "response", ",", "obj", ",", "builder", ")", "{", "trx", ".", "emit", "(", "'query-response'", ",", "response", ",", "obj", ",", "builder", ")", ";", "client", ".", "emit", "(", "'query-response'", ",", "response", ",", "obj", ",", "builder", ")", ";", "}", ")", ";", "const", "_query", "=", "trxClient", ".", "query", ";", "trxClient", ".", "query", "=", "function", "(", "conn", ",", "obj", ")", "{", "const", "completed", "=", "trx", ".", "isCompleted", "(", ")", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "if", "(", "conn", "!==", "connection", ")", "throw", "new", "Error", "(", "'Invalid connection for transaction query.'", ")", ";", "if", "(", "completed", ")", "completedError", "(", "trx", ",", "obj", ")", ";", "return", "_query", ".", "call", "(", "trxClient", ",", "conn", ",", "obj", ")", ";", "}", ")", ";", "}", ";", "const", "_stream", "=", "trxClient", ".", "stream", ";", "trxClient", ".", "stream", "=", "function", "(", "conn", ",", "obj", ",", "stream", ",", "options", ")", "{", "const", "completed", "=", "trx", ".", "isCompleted", "(", ")", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "if", "(", "conn", "!==", "connection", ")", "throw", "new", "Error", "(", "'Invalid connection for transaction query.'", ")", ";", "if", "(", "completed", ")", "completedError", "(", "trx", ",", "obj", ")", ";", "return", "_stream", ".", "call", "(", "trxClient", ",", "conn", ",", "obj", ",", "stream", ",", "options", ")", ";", "}", ")", ";", "}", ";", "trxClient", ".", "acquireConnection", "=", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "connection", ")", ";", "}", ";", "trxClient", ".", "releaseConnection", "=", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ";", "return", "trxClient", ";", "}" ]
We need to make a client object which always acquires the same connection and does not release back into the pool.
[ "We", "need", "to", "make", "a", "client", "object", "which", "always", "acquires", "the", "same", "connection", "and", "does", "not", "release", "back", "into", "the", "pool", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/transaction.js#L219-L272
2,560
tgriesser/knex
src/migrate/table-resolver.js
getTable
function getTable(trxOrKnex, tableName, schemaName) { return schemaName ? trxOrKnex(tableName).withSchema(schemaName) : trxOrKnex(tableName); }
javascript
function getTable(trxOrKnex, tableName, schemaName) { return schemaName ? trxOrKnex(tableName).withSchema(schemaName) : trxOrKnex(tableName); }
[ "function", "getTable", "(", "trxOrKnex", ",", "tableName", ",", "schemaName", ")", "{", "return", "schemaName", "?", "trxOrKnex", "(", "tableName", ")", ".", "withSchema", "(", "schemaName", ")", ":", "trxOrKnex", "(", "tableName", ")", ";", "}" ]
Get schema-aware query builder for a given table and schema name
[ "Get", "schema", "-", "aware", "query", "builder", "for", "a", "given", "table", "and", "schema", "name" ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/table-resolver.js#L7-L11
2,561
tgriesser/knex
src/migrate/Migrator.js
validateMigrationList
function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } }
javascript
function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } }
[ "function", "validateMigrationList", "(", "migrationSource", ",", "migrations", ")", "{", "const", "all", "=", "migrations", "[", "0", "]", ";", "const", "completed", "=", "migrations", "[", "1", "]", ";", "const", "diff", "=", "getMissingMigrations", "(", "migrationSource", ",", "completed", ",", "all", ")", ";", "if", "(", "!", "isEmpty", "(", "diff", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "diff", ".", "join", "(", "', '", ")", "}", "`", ")", ";", "}", "}" ]
Validates that migrations are present in the appropriate directories.
[ "Validates", "that", "migrations", "are", "present", "in", "the", "appropriate", "directories", "." ]
6a4fecfe7822442ee5c43d924958eadfe6e17a93
https://github.com/tgriesser/knex/blob/6a4fecfe7822442ee5c43d924958eadfe6e17a93/src/migrate/Migrator.js#L459-L470
2,562
nodejs/node-gyp
lib/configure.js
findAccessibleSync
function findAccessibleSync (logprefix, dir, candidates) { for (var next = 0; next < candidates.length; next++) { var candidate = path.resolve(dir, candidates[next]) try { var fd = fs.openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } fs.closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined }
javascript
function findAccessibleSync (logprefix, dir, candidates) { for (var next = 0; next < candidates.length; next++) { var candidate = path.resolve(dir, candidates[next]) try { var fd = fs.openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } fs.closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined }
[ "function", "findAccessibleSync", "(", "logprefix", ",", "dir", ",", "candidates", ")", "{", "for", "(", "var", "next", "=", "0", ";", "next", "<", "candidates", ".", "length", ";", "next", "++", ")", "{", "var", "candidate", "=", "path", ".", "resolve", "(", "dir", ",", "candidates", "[", "next", "]", ")", "try", "{", "var", "fd", "=", "fs", ".", "openSync", "(", "candidate", ",", "'r'", ")", "}", "catch", "(", "e", ")", "{", "// this candidate was not found or not readable, do nothing", "log", ".", "silly", "(", "logprefix", ",", "'Could not open %s: %s'", ",", "candidate", ",", "e", ".", "message", ")", "continue", "}", "fs", ".", "closeSync", "(", "fd", ")", "log", ".", "silly", "(", "logprefix", ",", "'Found readable %s'", ",", "candidate", ")", "return", "candidate", "}", "return", "undefined", "}" ]
Returns the first file or directory from an array of candidates that is readable by the current user, or undefined if none of the candidates are readable.
[ "Returns", "the", "first", "file", "or", "directory", "from", "an", "array", "of", "candidates", "that", "is", "readable", "by", "the", "current", "user", "or", "undefined", "if", "none", "of", "the", "candidates", "are", "readable", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L350-L366
2,563
nodejs/node-gyp
lib/configure.js
findPython
function findPython() { const SKIP=0, FAIL=1 const toCheck = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: this.checkCommand, arg: this.configPython, }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable PYTHON') return SKIP } this.addLog( 'checking Python explicitly set from environment variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: this.checkCommand, arg: this.env.PYTHON, }, { before: () => { this.addLog('checking if "python2" can be used') }, check: this.checkCommand, arg: 'python2', }, { before: () => { this.addLog('checking if "python" can be used') }, check: this.checkCommand, arg: 'python', }, { before: () => { if (!this.win) { // Everything after this is Windows specific return FAIL } this.addLog( 'checking if the py launcher can be used to find Python 2') }, check: this.checkPyLauncher, }, { before: () => { this.addLog( 'checking if Python 2 is installed in the default location') }, check: this.checkExecPath, arg: this.defaultLocation, }, ] function runChecks(err) { this.log.silly('runChecks: err = %j', err && err.stack || err) const check = toCheck.shift() if (!check) { return this.fail() } const before = check.before.apply(this) if (before === SKIP) { return runChecks.apply(this) } if (before === FAIL) { return this.fail() } const args = [ runChecks.bind(this) ] if (check.arg) { args.unshift(check.arg) } check.check.apply(this, args) } runChecks.apply(this) }
javascript
function findPython() { const SKIP=0, FAIL=1 const toCheck = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: this.checkCommand, arg: this.configPython, }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable PYTHON') return SKIP } this.addLog( 'checking Python explicitly set from environment variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: this.checkCommand, arg: this.env.PYTHON, }, { before: () => { this.addLog('checking if "python2" can be used') }, check: this.checkCommand, arg: 'python2', }, { before: () => { this.addLog('checking if "python" can be used') }, check: this.checkCommand, arg: 'python', }, { before: () => { if (!this.win) { // Everything after this is Windows specific return FAIL } this.addLog( 'checking if the py launcher can be used to find Python 2') }, check: this.checkPyLauncher, }, { before: () => { this.addLog( 'checking if Python 2 is installed in the default location') }, check: this.checkExecPath, arg: this.defaultLocation, }, ] function runChecks(err) { this.log.silly('runChecks: err = %j', err && err.stack || err) const check = toCheck.shift() if (!check) { return this.fail() } const before = check.before.apply(this) if (before === SKIP) { return runChecks.apply(this) } if (before === FAIL) { return this.fail() } const args = [ runChecks.bind(this) ] if (check.arg) { args.unshift(check.arg) } check.check.apply(this, args) } runChecks.apply(this) }
[ "function", "findPython", "(", ")", "{", "const", "SKIP", "=", "0", ",", "FAIL", "=", "1", "const", "toCheck", "=", "[", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "configPython", ")", "{", "this", ".", "addLog", "(", "'Python is not set from command line or npm configuration'", ")", "return", "SKIP", "}", "this", ".", "addLog", "(", "'checking Python explicitly set from command line or '", "+", "'npm configuration'", ")", "this", ".", "addLog", "(", "'- \"--python=\" or \"npm config get python\" is '", "+", "`", "${", "this", ".", "configPython", "}", "`", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "this", ".", "configPython", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "env", ".", "PYTHON", ")", "{", "this", ".", "addLog", "(", "'Python is not set from environment variable PYTHON'", ")", "return", "SKIP", "}", "this", ".", "addLog", "(", "'checking Python explicitly set from environment variable PYTHON'", ")", "this", ".", "addLog", "(", "`", "${", "this", ".", "env", ".", "PYTHON", "}", "`", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "this", ".", "env", ".", "PYTHON", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if \"python2\" can be used'", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "'python2'", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if \"python\" can be used'", ")", "}", ",", "check", ":", "this", ".", "checkCommand", ",", "arg", ":", "'python'", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "if", "(", "!", "this", ".", "win", ")", "{", "// Everything after this is Windows specific", "return", "FAIL", "}", "this", ".", "addLog", "(", "'checking if the py launcher can be used to find Python 2'", ")", "}", ",", "check", ":", "this", ".", "checkPyLauncher", ",", "}", ",", "{", "before", ":", "(", ")", "=>", "{", "this", ".", "addLog", "(", "'checking if Python 2 is installed in the default location'", ")", "}", ",", "check", ":", "this", ".", "checkExecPath", ",", "arg", ":", "this", ".", "defaultLocation", ",", "}", ",", "]", "function", "runChecks", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'runChecks: err = %j'", ",", "err", "&&", "err", ".", "stack", "||", "err", ")", "const", "check", "=", "toCheck", ".", "shift", "(", ")", "if", "(", "!", "check", ")", "{", "return", "this", ".", "fail", "(", ")", "}", "const", "before", "=", "check", ".", "before", ".", "apply", "(", "this", ")", "if", "(", "before", "===", "SKIP", ")", "{", "return", "runChecks", ".", "apply", "(", "this", ")", "}", "if", "(", "before", "===", "FAIL", ")", "{", "return", "this", ".", "fail", "(", ")", "}", "const", "args", "=", "[", "runChecks", ".", "bind", "(", "this", ")", "]", "if", "(", "check", ".", "arg", ")", "{", "args", ".", "unshift", "(", "check", ".", "arg", ")", "}", "check", ".", "check", ".", "apply", "(", "this", ",", "args", ")", "}", "runChecks", ".", "apply", "(", "this", ")", "}" ]
Find Python by trying a sequence of possibilities. Ignore errors, keep trying until Python is found.
[ "Find", "Python", "by", "trying", "a", "sequence", "of", "possibilities", ".", "Ignore", "errors", "keep", "trying", "until", "Python", "is", "found", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L398-L484
2,564
nodejs/node-gyp
lib/configure.js
checkExecPath
function checkExecPath (execPath, errorCallback) { this.log.verbose(`- executing "${execPath}" to get version`) this.run(execPath, this.argsVersion, false, function (err, version) { // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable if (err) { this.addLog(`- "${execPath}" could not be run`) return errorCallback(err) } this.addLog(`- version is "${version}"`) const range = semver.Range(this.semverRange) var valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') return errorCallback(err) } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') return errorCallback(new Error( `Found unsupported Python version ${version}`)) } this.succeed(execPath, version) }.bind(this)) }
javascript
function checkExecPath (execPath, errorCallback) { this.log.verbose(`- executing "${execPath}" to get version`) this.run(execPath, this.argsVersion, false, function (err, version) { // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable if (err) { this.addLog(`- "${execPath}" could not be run`) return errorCallback(err) } this.addLog(`- version is "${version}"`) const range = semver.Range(this.semverRange) var valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') return errorCallback(err) } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') return errorCallback(new Error( `Found unsupported Python version ${version}`)) } this.succeed(execPath, version) }.bind(this)) }
[ "function", "checkExecPath", "(", "execPath", ",", "errorCallback", ")", "{", "this", ".", "log", ".", "verbose", "(", "`", "${", "execPath", "}", "`", ")", "this", ".", "run", "(", "execPath", ",", "this", ".", "argsVersion", ",", "false", ",", "function", "(", "err", ",", "version", ")", "{", "// Possible outcomes:", "// - Error: executable can not be run (likely meaning the command wasn't", "// a Python executable and the previous command produced gibberish)", "// - Gibberish: somehow the last command produced an executable path,", "// this will fail when verifying the version", "// - Version of the Python executable", "if", "(", "err", ")", "{", "this", ".", "addLog", "(", "`", "${", "execPath", "}", "`", ")", "return", "errorCallback", "(", "err", ")", "}", "this", ".", "addLog", "(", "`", "${", "version", "}", "`", ")", "const", "range", "=", "semver", ".", "Range", "(", "this", ".", "semverRange", ")", "var", "valid", "=", "false", "try", "{", "valid", "=", "range", ".", "test", "(", "version", ")", "}", "catch", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'range.test() threw:\\n%s'", ",", "err", ".", "stack", ")", "this", ".", "addLog", "(", "`", "${", "execPath", "}", "`", ")", "this", ".", "addLog", "(", "'- is it a Python executable?'", ")", "return", "errorCallback", "(", "err", ")", "}", "if", "(", "!", "valid", ")", "{", "this", ".", "addLog", "(", "`", "${", "version", "}", "${", "this", ".", "semverRange", "}", "`", ")", "this", ".", "addLog", "(", "'- THIS VERSION OF PYTHON IS NOT SUPPORTED'", ")", "return", "errorCallback", "(", "new", "Error", "(", "`", "${", "version", "}", "`", ")", ")", "}", "this", ".", "succeed", "(", "execPath", ",", "version", ")", "}", ".", "bind", "(", "this", ")", ")", "}" ]
Check if a Python executable is the correct version to use. Will exit the Python finder on success.
[ "Check", "if", "a", "Python", "executable", "is", "the", "correct", "version", "to", "use", ".", "Will", "exit", "the", "Python", "finder", "on", "success", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L544-L578
2,565
nodejs/node-gyp
lib/configure.js
run
function run(exec, args, shell, callback) { var env = extend({}, this.env) env.TERM = 'dumb' const opts = { env: env, shell: shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { this.execFile(exec, args, opts, execFileCallback.bind(this)) } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) return callback(err) } function execFileCallback(err, stdout, stderr) { this.log.silly('execFile result: err = %j', err && err.stack || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) if (err) { return callback(err) } const execPath = stdout.trim() callback(null, execPath) } }
javascript
function run(exec, args, shell, callback) { var env = extend({}, this.env) env.TERM = 'dumb' const opts = { env: env, shell: shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { this.execFile(exec, args, opts, execFileCallback.bind(this)) } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) return callback(err) } function execFileCallback(err, stdout, stderr) { this.log.silly('execFile result: err = %j', err && err.stack || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) if (err) { return callback(err) } const execPath = stdout.trim() callback(null, execPath) } }
[ "function", "run", "(", "exec", ",", "args", ",", "shell", ",", "callback", ")", "{", "var", "env", "=", "extend", "(", "{", "}", ",", "this", ".", "env", ")", "env", ".", "TERM", "=", "'dumb'", "const", "opts", "=", "{", "env", ":", "env", ",", "shell", ":", "shell", "}", "this", ".", "log", ".", "silly", "(", "'execFile: exec = %j'", ",", "exec", ")", "this", ".", "log", ".", "silly", "(", "'execFile: args = %j'", ",", "args", ")", "this", ".", "log", ".", "silly", "(", "'execFile: opts = %j'", ",", "opts", ")", "try", "{", "this", ".", "execFile", "(", "exec", ",", "args", ",", "opts", ",", "execFileCallback", ".", "bind", "(", "this", ")", ")", "}", "catch", "(", "err", ")", "{", "this", ".", "log", ".", "silly", "(", "'execFile: threw:\\n%s'", ",", "err", ".", "stack", ")", "return", "callback", "(", "err", ")", "}", "function", "execFileCallback", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "this", ".", "log", ".", "silly", "(", "'execFile result: err = %j'", ",", "err", "&&", "err", ".", "stack", "||", "err", ")", "this", ".", "log", ".", "silly", "(", "'execFile result: stdout = %j'", ",", "stdout", ")", "this", ".", "log", ".", "silly", "(", "'execFile result: stderr = %j'", ",", "stderr", ")", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "const", "execPath", "=", "stdout", ".", "trim", "(", ")", "callback", "(", "null", ",", "execPath", ")", "}", "}" ]
Run an executable or shell command, trimming the output.
[ "Run", "an", "executable", "or", "shell", "command", "trimming", "the", "output", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/configure.js#L581-L606
2,566
nodejs/node-gyp
lib/install.js
cb
function cb (err) { if (cb.done) return cb.done = true if (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong gyp.commands.remove([ release.versionDir ], function () { callback(err) }) } else { callback(null, release.version) } }
javascript
function cb (err) { if (cb.done) return cb.done = true if (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong gyp.commands.remove([ release.versionDir ], function () { callback(err) }) } else { callback(null, release.version) } }
[ "function", "cb", "(", "err", ")", "{", "if", "(", "cb", ".", "done", ")", "return", "cb", ".", "done", "=", "true", "if", "(", "err", ")", "{", "log", ".", "warn", "(", "'install'", ",", "'got an error, rolling back install'", ")", "// roll-back the install if anything went wrong", "gyp", ".", "commands", ".", "remove", "(", "[", "release", ".", "versionDir", "]", ",", "function", "(", ")", "{", "callback", "(", "err", ")", "}", ")", "}", "else", "{", "callback", "(", "null", ",", "release", ".", "version", ")", "}", "}" ]
ensure no double-callbacks happen
[ "ensure", "no", "double", "-", "callbacks", "happen" ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/install.js#L29-L41
2,567
nodejs/node-gyp
lib/install.js
afterTarball
function afterTarball () { if (badDownload) return if (extractCount === 0) { return cb(new Error('There was a fatal problem while downloading/extracting the tarball')) } log.verbose('tarball', 'done parsing tarball') var async = 0 if (win) { // need to download node.lib async++ downloadNodeLib(deref) } // write the "installVersion" file async++ var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) // Only download SHASUMS.txt if not using tarPath override if (!tarPath) { // download SHASUMS.txt async++ downloadShasums(deref) } if (async === 0) { // no async tasks required cb() } function deref (err) { if (err) return cb(err) async-- if (!async) { log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (var k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])) return } } cb() } } }
javascript
function afterTarball () { if (badDownload) return if (extractCount === 0) { return cb(new Error('There was a fatal problem while downloading/extracting the tarball')) } log.verbose('tarball', 'done parsing tarball') var async = 0 if (win) { // need to download node.lib async++ downloadNodeLib(deref) } // write the "installVersion" file async++ var installVersionPath = path.resolve(devDir, 'installVersion') fs.writeFile(installVersionPath, gyp.package.installVersion + '\n', deref) // Only download SHASUMS.txt if not using tarPath override if (!tarPath) { // download SHASUMS.txt async++ downloadShasums(deref) } if (async === 0) { // no async tasks required cb() } function deref (err) { if (err) return cb(err) async-- if (!async) { log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (var k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k])) return } } cb() } } }
[ "function", "afterTarball", "(", ")", "{", "if", "(", "badDownload", ")", "return", "if", "(", "extractCount", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "'There was a fatal problem while downloading/extracting the tarball'", ")", ")", "}", "log", ".", "verbose", "(", "'tarball'", ",", "'done parsing tarball'", ")", "var", "async", "=", "0", "if", "(", "win", ")", "{", "// need to download node.lib", "async", "++", "downloadNodeLib", "(", "deref", ")", "}", "// write the \"installVersion\" file", "async", "++", "var", "installVersionPath", "=", "path", ".", "resolve", "(", "devDir", ",", "'installVersion'", ")", "fs", ".", "writeFile", "(", "installVersionPath", ",", "gyp", ".", "package", ".", "installVersion", "+", "'\\n'", ",", "deref", ")", "// Only download SHASUMS.txt if not using tarPath override", "if", "(", "!", "tarPath", ")", "{", "// download SHASUMS.txt", "async", "++", "downloadShasums", "(", "deref", ")", "}", "if", "(", "async", "===", "0", ")", "{", "// no async tasks required", "cb", "(", ")", "}", "function", "deref", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "async", "--", "if", "(", "!", "async", ")", "{", "log", ".", "verbose", "(", "'download contents checksum'", ",", "JSON", ".", "stringify", "(", "contentShasums", ")", ")", "// check content shasums", "for", "(", "var", "k", "in", "contentShasums", ")", "{", "log", ".", "verbose", "(", "'validating download checksum for '", "+", "k", ",", "'(%s == %s)'", ",", "contentShasums", "[", "k", "]", ",", "expectShasums", "[", "k", "]", ")", "if", "(", "contentShasums", "[", "k", "]", "!==", "expectShasums", "[", "k", "]", ")", "{", "cb", "(", "new", "Error", "(", "k", "+", "' local checksum '", "+", "contentShasums", "[", "k", "]", "+", "' not match remote '", "+", "expectShasums", "[", "k", "]", ")", ")", "return", "}", "}", "cb", "(", ")", "}", "}", "}" ]
invoked after the tarball has finished being extracted
[ "invoked", "after", "the", "tarball", "has", "finished", "being", "extracted" ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/install.js#L215-L263
2,568
nodejs/node-gyp
lib/build.js
loadConfigGypi
function loadConfigGypi () { var configPath = path.resolve('build', 'config.gypi') fs.readFile(configPath, 'utf8', function (err, data) { if (err) { if (err.code == 'ENOENT') { callback(new Error('You must run `node-gyp configure` first!')) } else { callback(err) } return } config = JSON.parse(data.replace(/\#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) if (win) { findSolutionFile() } else { doWhich() } }) }
javascript
function loadConfigGypi () { var configPath = path.resolve('build', 'config.gypi') fs.readFile(configPath, 'utf8', function (err, data) { if (err) { if (err.code == 'ENOENT') { callback(new Error('You must run `node-gyp configure` first!')) } else { callback(err) } return } config = JSON.parse(data.replace(/\#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) if (win) { findSolutionFile() } else { doWhich() } }) }
[ "function", "loadConfigGypi", "(", ")", "{", "var", "configPath", "=", "path", ".", "resolve", "(", "'build'", ",", "'config.gypi'", ")", "fs", ".", "readFile", "(", "configPath", ",", "'utf8'", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "'ENOENT'", ")", "{", "callback", "(", "new", "Error", "(", "'You must run `node-gyp configure` first!'", ")", ")", "}", "else", "{", "callback", "(", "err", ")", "}", "return", "}", "config", "=", "JSON", ".", "parse", "(", "data", ".", "replace", "(", "/", "\\#.+\\n", "/", ",", "''", ")", ")", "// get the 'arch', 'buildType', and 'nodeDir' vars from the config", "buildType", "=", "config", ".", "target_defaults", ".", "default_configuration", "arch", "=", "config", ".", "variables", ".", "target_arch", "nodeDir", "=", "config", ".", "variables", ".", "nodedir", "if", "(", "'debug'", "in", "gyp", ".", "opts", ")", "{", "buildType", "=", "gyp", ".", "opts", ".", "debug", "?", "'Debug'", ":", "'Release'", "}", "if", "(", "!", "buildType", ")", "{", "buildType", "=", "'Release'", "}", "log", ".", "verbose", "(", "'build type'", ",", "buildType", ")", "log", ".", "verbose", "(", "'architecture'", ",", "arch", ")", "log", ".", "verbose", "(", "'node dev dir'", ",", "nodeDir", ")", "if", "(", "win", ")", "{", "findSolutionFile", "(", ")", "}", "else", "{", "doWhich", "(", ")", "}", "}", ")", "}" ]
Load the "config.gypi" file that was generated during "configure".
[ "Load", "the", "config", ".", "gypi", "file", "that", "was", "generated", "during", "configure", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L40-L75
2,569
nodejs/node-gyp
lib/build.js
findMsbuild
function findMsbuild () { log.verbose('could not find "msbuild.exe" in PATH - finding location in registry') var notfoundErr = 'Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?' var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s' if (process.arch !== 'ia32') cmd += ' /reg:32' exec(cmd, function (err, stdout) { if (err) { return callback(new Error(err.message + '\n' + notfoundErr)) } var reVers = /ToolsVersions\\([^\\]+)$/i , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i , msbuilds = [] , r , msbuildPath stdout.split('\r\n\r\n').forEach(function(l) { if (!l) return l = l.trim() if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) { var ver = parseFloat(r[1], 10) if (ver >= 3.5) { if (r = rePath.exec(l)) { msbuilds.push({ version: ver, path: r[1] }) } } } }) msbuilds.sort(function (x, y) { return (x.version < y.version ? -1 : 1) }) ;(function verifyMsbuild () { if (!msbuilds.length) return callback(new Error(notfoundErr)) msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe') fs.stat(msbuildPath, function (err) { if (err) { if (err.code == 'ENOENT') { if (msbuilds.length) { return verifyMsbuild() } else { callback(new Error(notfoundErr)) } } else { callback(err) } return } command = msbuildPath doBuild() }) })() }) }
javascript
function findMsbuild () { log.verbose('could not find "msbuild.exe" in PATH - finding location in registry') var notfoundErr = 'Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?' var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s' if (process.arch !== 'ia32') cmd += ' /reg:32' exec(cmd, function (err, stdout) { if (err) { return callback(new Error(err.message + '\n' + notfoundErr)) } var reVers = /ToolsVersions\\([^\\]+)$/i , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i , msbuilds = [] , r , msbuildPath stdout.split('\r\n\r\n').forEach(function(l) { if (!l) return l = l.trim() if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) { var ver = parseFloat(r[1], 10) if (ver >= 3.5) { if (r = rePath.exec(l)) { msbuilds.push({ version: ver, path: r[1] }) } } } }) msbuilds.sort(function (x, y) { return (x.version < y.version ? -1 : 1) }) ;(function verifyMsbuild () { if (!msbuilds.length) return callback(new Error(notfoundErr)) msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe') fs.stat(msbuildPath, function (err) { if (err) { if (err.code == 'ENOENT') { if (msbuilds.length) { return verifyMsbuild() } else { callback(new Error(notfoundErr)) } } else { callback(err) } return } command = msbuildPath doBuild() }) })() }) }
[ "function", "findMsbuild", "(", ")", "{", "log", ".", "verbose", "(", "'could not find \"msbuild.exe\" in PATH - finding location in registry'", ")", "var", "notfoundErr", "=", "'Can\\'t find \"msbuild.exe\". Do you have Microsoft Visual Studio C++ 2008+ installed?'", "var", "cmd", "=", "'reg query \"HKLM\\\\Software\\\\Microsoft\\\\MSBuild\\\\ToolsVersions\" /s'", "if", "(", "process", ".", "arch", "!==", "'ia32'", ")", "cmd", "+=", "' /reg:32'", "exec", "(", "cmd", ",", "function", "(", "err", ",", "stdout", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "new", "Error", "(", "err", ".", "message", "+", "'\\n'", "+", "notfoundErr", ")", ")", "}", "var", "reVers", "=", "/", "ToolsVersions\\\\([^\\\\]+)$", "/", "i", ",", "rePath", "=", "/", "\\r\\n[ \\t]+MSBuildToolsPath[ \\t]+REG_SZ[ \\t]+([^\\r]+)", "/", "i", ",", "msbuilds", "=", "[", "]", ",", "r", ",", "msbuildPath", "stdout", ".", "split", "(", "'\\r\\n\\r\\n'", ")", ".", "forEach", "(", "function", "(", "l", ")", "{", "if", "(", "!", "l", ")", "return", "l", "=", "l", ".", "trim", "(", ")", "if", "(", "r", "=", "reVers", ".", "exec", "(", "l", ".", "substring", "(", "0", ",", "l", ".", "indexOf", "(", "'\\r\\n'", ")", ")", ")", ")", "{", "var", "ver", "=", "parseFloat", "(", "r", "[", "1", "]", ",", "10", ")", "if", "(", "ver", ">=", "3.5", ")", "{", "if", "(", "r", "=", "rePath", ".", "exec", "(", "l", ")", ")", "{", "msbuilds", ".", "push", "(", "{", "version", ":", "ver", ",", "path", ":", "r", "[", "1", "]", "}", ")", "}", "}", "}", "}", ")", "msbuilds", ".", "sort", "(", "function", "(", "x", ",", "y", ")", "{", "return", "(", "x", ".", "version", "<", "y", ".", "version", "?", "-", "1", ":", "1", ")", "}", ")", ";", "(", "function", "verifyMsbuild", "(", ")", "{", "if", "(", "!", "msbuilds", ".", "length", ")", "return", "callback", "(", "new", "Error", "(", "notfoundErr", ")", ")", "msbuildPath", "=", "path", ".", "resolve", "(", "msbuilds", ".", "pop", "(", ")", ".", "path", ",", "'msbuild.exe'", ")", "fs", ".", "stat", "(", "msbuildPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "'ENOENT'", ")", "{", "if", "(", "msbuilds", ".", "length", ")", "{", "return", "verifyMsbuild", "(", ")", "}", "else", "{", "callback", "(", "new", "Error", "(", "notfoundErr", ")", ")", "}", "}", "else", "{", "callback", "(", "err", ")", "}", "return", "}", "command", "=", "msbuildPath", "doBuild", "(", ")", "}", ")", "}", ")", "(", ")", "}", ")", "}" ]
Search for the location of "msbuild.exe" file on Windows.
[ "Search", "for", "the", "location", "of", "msbuild", ".", "exe", "file", "on", "Windows", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L126-L180
2,570
nodejs/node-gyp
lib/build.js
doBuild
function doBuild () { // Enable Verbose build var verbose = log.levels[log.level] <= log.levels.verbose if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. var archLower = arch.toLowerCase() var p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? var hasSln = argv.some(function (arg) { return path.extname(arg) == '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } var proc = gyp.spawn(command, argv) proc.on('exit', onExit) }
javascript
function doBuild () { // Enable Verbose build var verbose = log.levels[log.level] <= log.levels.verbose if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. var archLower = arch.toLowerCase() var p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { var j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? var hasSln = argv.some(function (arg) { return path.extname(arg) == '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } var proc = gyp.spawn(command, argv) proc.on('exit', onExit) }
[ "function", "doBuild", "(", ")", "{", "// Enable Verbose build", "var", "verbose", "=", "log", ".", "levels", "[", "log", ".", "level", "]", "<=", "log", ".", "levels", ".", "verbose", "if", "(", "!", "win", "&&", "verbose", ")", "{", "argv", ".", "push", "(", "'V=1'", ")", "}", "if", "(", "win", "&&", "!", "verbose", ")", "{", "argv", ".", "push", "(", "'/clp:Verbosity=minimal'", ")", "}", "if", "(", "win", ")", "{", "// Turn off the Microsoft logo on Windows", "argv", ".", "push", "(", "'/nologo'", ")", "}", "// Specify the build type, Release by default", "if", "(", "win", ")", "{", "// Convert .gypi config target_arch to MSBuild /Platform", "// Since there are many ways to state '32-bit Intel', default to it.", "// N.B. msbuild's Condition string equality tests are case-insensitive.", "var", "archLower", "=", "arch", ".", "toLowerCase", "(", ")", "var", "p", "=", "archLower", "===", "'x64'", "?", "'x64'", ":", "(", "archLower", "===", "'arm'", "?", "'ARM'", ":", "(", "archLower", "===", "'arm64'", "?", "'ARM64'", ":", "'Win32'", ")", ")", "argv", ".", "push", "(", "'/p:Configuration='", "+", "buildType", "+", "';Platform='", "+", "p", ")", "if", "(", "jobs", ")", "{", "var", "j", "=", "parseInt", "(", "jobs", ",", "10", ")", "if", "(", "!", "isNaN", "(", "j", ")", "&&", "j", ">", "0", ")", "{", "argv", ".", "push", "(", "'/m:'", "+", "j", ")", "}", "else", "if", "(", "jobs", ".", "toUpperCase", "(", ")", "===", "'MAX'", ")", "{", "argv", ".", "push", "(", "'/m:'", "+", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ")", "}", "}", "}", "else", "{", "argv", ".", "push", "(", "'BUILDTYPE='", "+", "buildType", ")", "// Invoke the Makefile in the 'build' dir.", "argv", ".", "push", "(", "'-C'", ")", "argv", ".", "push", "(", "'build'", ")", "if", "(", "jobs", ")", "{", "var", "j", "=", "parseInt", "(", "jobs", ",", "10", ")", "if", "(", "!", "isNaN", "(", "j", ")", "&&", "j", ">", "0", ")", "{", "argv", ".", "push", "(", "'--jobs'", ")", "argv", ".", "push", "(", "j", ")", "}", "else", "if", "(", "jobs", ".", "toUpperCase", "(", ")", "===", "'MAX'", ")", "{", "argv", ".", "push", "(", "'--jobs'", ")", "argv", ".", "push", "(", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ")", "}", "}", "}", "if", "(", "win", ")", "{", "// did the user specify their own .sln file?", "var", "hasSln", "=", "argv", ".", "some", "(", "function", "(", "arg", ")", "{", "return", "path", ".", "extname", "(", "arg", ")", "==", "'.sln'", "}", ")", "if", "(", "!", "hasSln", ")", "{", "argv", ".", "unshift", "(", "gyp", ".", "opts", ".", "solution", "||", "guessedSolution", ")", "}", "}", "var", "proc", "=", "gyp", ".", "spawn", "(", "command", ",", "argv", ")", "proc", ".", "on", "(", "'exit'", ",", "onExit", ")", "}" ]
Actually spawn the process and compile the module.
[ "Actually", "spawn", "the", "process", "and", "compile", "the", "module", "." ]
721eb691cf15556cc2700eda0558d5bad5f84232
https://github.com/nodejs/node-gyp/blob/721eb691cf15556cc2700eda0558d5bad5f84232/lib/build.js#L186-L248
2,571
websockets/ws
lib/permessage-deflate.js
inflateOnData
function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); }
javascript
function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); }
[ "function", "inflateOnData", "(", "chunk", ")", "{", "this", "[", "kTotalLength", "]", "+=", "chunk", ".", "length", ";", "if", "(", "this", "[", "kPerMessageDeflate", "]", ".", "_maxPayload", "<", "1", "||", "this", "[", "kTotalLength", "]", "<=", "this", "[", "kPerMessageDeflate", "]", ".", "_maxPayload", ")", "{", "this", "[", "kBuffers", "]", ".", "push", "(", "chunk", ")", ";", "return", ";", "}", "this", "[", "kError", "]", "=", "new", "RangeError", "(", "'Max payload size exceeded'", ")", ";", "this", "[", "kError", "]", "[", "kStatusCode", "]", "=", "1009", ";", "this", ".", "removeListener", "(", "'data'", ",", "inflateOnData", ")", ";", "this", ".", "reset", "(", ")", ";", "}" ]
The listener of the `zlib.InflateRaw` stream `'data'` event. @param {Buffer} chunk A chunk of data @private
[ "The", "listener", "of", "the", "zlib", ".", "InflateRaw", "stream", "data", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/permessage-deflate.js#L473-L488
2,572
websockets/ws
lib/receiver.js
error
function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
javascript
function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; }
[ "function", "error", "(", "ErrorCtor", ",", "message", ",", "prefix", ",", "statusCode", ")", "{", "const", "err", "=", "new", "ErrorCtor", "(", "prefix", "?", "`", "${", "message", "}", "`", ":", "message", ")", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "error", ")", ";", "err", "[", "kStatusCode", "]", "=", "statusCode", ";", "return", "err", ";", "}" ]
Builds an error object. @param {(Error|RangeError)} ErrorCtor The error constructor @param {String} message The error message @param {Boolean} prefix Specifies whether or not to add a default prefix to `message` @param {Number} statusCode The status code @return {(Error|RangeError)} The error @private
[ "Builds", "an", "error", "object", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/receiver.js#L484-L492
2,573
websockets/ws
lib/buffer-util.js
concat
function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; }
javascript
function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; }
[ "function", "concat", "(", "list", ",", "totalLength", ")", "{", "if", "(", "list", ".", "length", "===", "0", ")", "return", "EMPTY_BUFFER", ";", "if", "(", "list", ".", "length", "===", "1", ")", "return", "list", "[", "0", "]", ";", "const", "target", "=", "Buffer", ".", "allocUnsafe", "(", "totalLength", ")", ";", "let", "offset", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "const", "buf", "=", "list", "[", "i", "]", ";", "buf", ".", "copy", "(", "target", ",", "offset", ")", ";", "offset", "+=", "buf", ".", "length", ";", "}", "return", "target", ";", "}" ]
Merges an array of buffers into a new buffer. @param {Buffer[]} list The array of buffers to concat @param {Number} totalLength The total length of buffers in the list @return {Buffer} The resulting buffer @public
[ "Merges", "an", "array", "of", "buffers", "into", "a", "new", "buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L13-L27
2,574
websockets/ws
lib/buffer-util.js
_mask
function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } }
javascript
function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } }
[ "function", "_mask", "(", "source", ",", "mask", ",", "output", ",", "offset", ",", "length", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "output", "[", "offset", "+", "i", "]", "=", "source", "[", "i", "]", "^", "mask", "[", "i", "&", "3", "]", ";", "}", "}" ]
Masks a buffer using the given mask. @param {Buffer} source The buffer to mask @param {Buffer} mask The mask to use @param {Buffer} output The buffer where to store the result @param {Number} offset The offset at which to start writing @param {Number} length The number of bytes to mask. @public
[ "Masks", "a", "buffer", "using", "the", "given", "mask", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L39-L43
2,575
websockets/ws
lib/buffer-util.js
_unmask
function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } }
javascript
function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } }
[ "function", "_unmask", "(", "buffer", ",", "mask", ")", "{", "// Required until https://github.com/nodejs/node/issues/9006 is resolved.", "const", "length", "=", "buffer", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "^=", "mask", "[", "i", "&", "3", "]", ";", "}", "}" ]
Unmasks a buffer using the given mask. @param {Buffer} buffer The buffer to unmask @param {Buffer} mask The mask to use @public
[ "Unmasks", "a", "buffer", "using", "the", "given", "mask", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L52-L58
2,576
websockets/ws
lib/buffer-util.js
toArrayBuffer
function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }
javascript
function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }
[ "function", "toArrayBuffer", "(", "buf", ")", "{", "if", "(", "buf", ".", "byteLength", "===", "buf", ".", "buffer", ".", "byteLength", ")", "{", "return", "buf", ".", "buffer", ";", "}", "return", "buf", ".", "buffer", ".", "slice", "(", "buf", ".", "byteOffset", ",", "buf", ".", "byteOffset", "+", "buf", ".", "byteLength", ")", ";", "}" ]
Converts a buffer to an `ArrayBuffer`. @param {Buffer} buf The buffer to convert @return {ArrayBuffer} Converted buffer @public
[ "Converts", "a", "buffer", "to", "an", "ArrayBuffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L67-L73
2,577
websockets/ws
lib/buffer-util.js
toBuffer
function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; }
javascript
function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; }
[ "function", "toBuffer", "(", "data", ")", "{", "toBuffer", ".", "readOnly", "=", "true", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "return", "data", ";", "let", "buf", ";", "if", "(", "data", "instanceof", "ArrayBuffer", ")", "{", "buf", "=", "Buffer", ".", "from", "(", "data", ")", ";", "}", "else", "if", "(", "ArrayBuffer", ".", "isView", "(", "data", ")", ")", "{", "buf", "=", "viewToBuffer", "(", "data", ")", ";", "}", "else", "{", "buf", "=", "Buffer", ".", "from", "(", "data", ")", ";", "toBuffer", ".", "readOnly", "=", "false", ";", "}", "return", "buf", ";", "}" ]
Converts `data` to a `Buffer`. @param {*} data The data to convert @return {Buffer} The buffer @throws {TypeError} @public
[ "Converts", "data", "to", "a", "Buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L83-L100
2,578
websockets/ws
lib/buffer-util.js
viewToBuffer
function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; }
javascript
function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; }
[ "function", "viewToBuffer", "(", "view", ")", "{", "const", "buf", "=", "Buffer", ".", "from", "(", "view", ".", "buffer", ")", ";", "if", "(", "view", ".", "byteLength", "!==", "view", ".", "buffer", ".", "byteLength", ")", "{", "return", "buf", ".", "slice", "(", "view", ".", "byteOffset", ",", "view", ".", "byteOffset", "+", "view", ".", "byteLength", ")", ";", "}", "return", "buf", ";", "}" ]
Converts an `ArrayBuffer` view into a buffer. @param {(DataView|TypedArray)} view The view to convert @return {Buffer} Converted view @private
[ "Converts", "an", "ArrayBuffer", "view", "into", "a", "buffer", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/buffer-util.js#L109-L117
2,579
websockets/ws
lib/websocket-server.js
abortHandshake
function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
javascript
function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || STATUS_CODES[code]; headers = { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); }
[ "function", "abortHandshake", "(", "socket", ",", "code", ",", "message", ",", "headers", ")", "{", "if", "(", "socket", ".", "writable", ")", "{", "message", "=", "message", "||", "STATUS_CODES", "[", "code", "]", ";", "headers", "=", "{", "Connection", ":", "'close'", ",", "'Content-type'", ":", "'text/html'", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "message", ")", ",", "...", "headers", "}", ";", "socket", ".", "write", "(", "`", "${", "code", "}", "${", "STATUS_CODES", "[", "code", "]", "}", "\\r", "\\n", "`", "+", "Object", ".", "keys", "(", "headers", ")", ".", "map", "(", "(", "h", ")", "=>", "`", "${", "h", "}", "${", "headers", "[", "h", "]", "}", "`", ")", ".", "join", "(", "'\\r\\n'", ")", "+", "'\\r\\n\\r\\n'", "+", "message", ")", ";", "}", "socket", ".", "removeListener", "(", "'error'", ",", "socketOnError", ")", ";", "socket", ".", "destroy", "(", ")", ";", "}" ]
Close the connection when preconditions are not fulfilled. @param {net.Socket} socket The socket of the upgrade request @param {Number} code The HTTP response status code @param {String} [message] The HTTP response body @param {Object} [headers] Additional HTTP response headers @private
[ "Close", "the", "connection", "when", "preconditions", "are", "not", "fulfilled", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket-server.js#L374-L396
2,580
websockets/ws
lib/extension.js
push
function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); }
javascript
function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); }
[ "function", "push", "(", "dest", ",", "name", ",", "elem", ")", "{", "if", "(", "dest", "[", "name", "]", "===", "undefined", ")", "dest", "[", "name", "]", "=", "[", "elem", "]", ";", "else", "dest", "[", "name", "]", ".", "push", "(", "elem", ")", ";", "}" ]
Adds an offer to the map of extension offers or a parameter to the map of parameters. @param {Object} dest The map of extension offers or parameters @param {String} name The extension or parameter name @param {(Object|Boolean|String)} elem The extension parameters or the parameter value @private
[ "Adds", "an", "offer", "to", "the", "map", "of", "extension", "offers", "or", "a", "parameter", "to", "the", "map", "of", "parameters", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/extension.js#L36-L39
2,581
websockets/ws
lib/extension.js
format
function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); }
javascript
function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); }
[ "function", "format", "(", "extensions", ")", "{", "return", "Object", ".", "keys", "(", "extensions", ")", ".", "map", "(", "(", "extension", ")", "=>", "{", "let", "configurations", "=", "extensions", "[", "extension", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "configurations", ")", ")", "configurations", "=", "[", "configurations", "]", ";", "return", "configurations", ".", "map", "(", "(", "params", ")", "=>", "{", "return", "[", "extension", "]", ".", "concat", "(", "Object", ".", "keys", "(", "params", ")", ".", "map", "(", "(", "k", ")", "=>", "{", "let", "values", "=", "params", "[", "k", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "values", ")", ")", "values", "=", "[", "values", "]", ";", "return", "values", ".", "map", "(", "(", "v", ")", "=>", "(", "v", "===", "true", "?", "k", ":", "`", "${", "k", "}", "${", "v", "}", "`", ")", ")", ".", "join", "(", "'; '", ")", ";", "}", ")", ")", ".", "join", "(", "'; '", ")", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}" ]
Builds the `Sec-WebSocket-Extensions` header field value. @param {Object} extensions The map of extensions and parameters to format @return {String} A string representing the given object @public
[ "Builds", "the", "Sec", "-", "WebSocket", "-", "Extensions", "header", "field", "value", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/extension.js#L199-L221
2,582
websockets/ws
lib/websocket.js
tlsConnect
function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); }
javascript
function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); }
[ "function", "tlsConnect", "(", "options", ")", "{", "options", ".", "path", "=", "undefined", ";", "options", ".", "servername", "=", "options", ".", "servername", "||", "options", ".", "host", ";", "return", "tls", ".", "connect", "(", "options", ")", ";", "}" ]
Create a `tls.TLSSocket` and initiate a connection. @param {Object} options Connection options @return {tls.TLSSocket} The newly created socket used to start the connection @private
[ "Create", "a", "tls", ".", "TLSSocket", "and", "initiate", "a", "connection", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L669-L673
2,583
websockets/ws
lib/websocket.js
abortHandshake
function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } }
javascript
function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } }
[ "function", "abortHandshake", "(", "websocket", ",", "stream", ",", "message", ")", "{", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "const", "err", "=", "new", "Error", "(", "message", ")", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "abortHandshake", ")", ";", "if", "(", "stream", ".", "setHeader", ")", "{", "stream", ".", "abort", "(", ")", ";", "stream", ".", "once", "(", "'abort'", ",", "websocket", ".", "emitClose", ".", "bind", "(", "websocket", ")", ")", ";", "websocket", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "stream", ".", "destroy", "(", "err", ")", ";", "stream", ".", "once", "(", "'error'", ",", "websocket", ".", "emit", ".", "bind", "(", "websocket", ",", "'error'", ")", ")", ";", "stream", ".", "once", "(", "'close'", ",", "websocket", ".", "emitClose", ".", "bind", "(", "websocket", ")", ")", ";", "}", "}" ]
Abort the handshake and emit an error. @param {WebSocket} websocket The WebSocket instance @param {(http.ClientRequest|net.Socket)} stream The request to abort or the socket to destroy @param {String} message The error message @private
[ "Abort", "the", "handshake", "and", "emit", "an", "error", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L684-L699
2,584
websockets/ws
lib/websocket.js
receiverOnConclude
function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); }
javascript
function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); }
[ "function", "receiverOnConclude", "(", "code", ",", "reason", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "_socket", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "websocket", ".", "_socket", ".", "resume", "(", ")", ";", "websocket", ".", "_closeFrameReceived", "=", "true", ";", "websocket", ".", "_closeMessage", "=", "reason", ";", "websocket", ".", "_closeCode", "=", "code", ";", "if", "(", "code", "===", "1005", ")", "websocket", ".", "close", "(", ")", ";", "else", "websocket", ".", "close", "(", "code", ",", "reason", ")", ";", "}" ]
The listener of the `Receiver` `'conclude'` event. @param {Number} code The status code @param {String} reason The reason for closing @private
[ "The", "listener", "of", "the", "Receiver", "conclude", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L740-L752
2,585
websockets/ws
lib/websocket.js
receiverOnError
function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); }
javascript
function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); }
[ "function", "receiverOnError", "(", "err", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "_socket", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "websocket", ".", "_closeCode", "=", "err", "[", "kStatusCode", "]", ";", "websocket", ".", "emit", "(", "'error'", ",", "err", ")", ";", "websocket", ".", "_socket", ".", "destroy", "(", ")", ";", "}" ]
The listener of the `Receiver` `'error'` event. @param {(RangeError|Error)} err The emitted error @private
[ "The", "listener", "of", "the", "Receiver", "error", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L769-L778
2,586
websockets/ws
lib/websocket.js
receiverOnPing
function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); }
javascript
function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); }
[ "function", "receiverOnPing", "(", "data", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "pong", "(", "data", ",", "!", "websocket", ".", "_isServer", ",", "NOOP", ")", ";", "websocket", ".", "emit", "(", "'ping'", ",", "data", ")", ";", "}" ]
The listener of the `Receiver` `'ping'` event. @param {Buffer} data The data included in the ping frame @private
[ "The", "listener", "of", "the", "Receiver", "ping", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L805-L810
2,587
websockets/ws
lib/websocket.js
socketOnClose
function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } }
javascript
function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } }
[ "function", "socketOnClose", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "this", ".", "removeListener", "(", "'close'", ",", "socketOnClose", ")", ";", "this", ".", "removeListener", "(", "'end'", ",", "socketOnEnd", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "//", "// The close frame might not have been received or the `'end'` event emitted,", "// for example, if the socket was destroyed due to an error. Ensure that the", "// `receiver` stream is closed after writing any remaining buffered data to", "// it. If the readable side of the socket is in flowing mode then there is no", "// buffered data as everything has been already written and `readable.read()`", "// will return `null`. If instead, the socket is paused, any possible buffered", "// data will be read as a single chunk and emitted synchronously in a single", "// `'data'` event.", "//", "websocket", ".", "_socket", ".", "read", "(", ")", ";", "websocket", ".", "_receiver", ".", "end", "(", ")", ";", "this", ".", "removeListener", "(", "'data'", ",", "socketOnData", ")", ";", "this", "[", "kWebSocket", "]", "=", "undefined", ";", "clearTimeout", "(", "websocket", ".", "_closeTimer", ")", ";", "if", "(", "websocket", ".", "_receiver", ".", "_writableState", ".", "finished", "||", "websocket", ".", "_receiver", ".", "_writableState", ".", "errorEmitted", ")", "{", "websocket", ".", "emitClose", "(", ")", ";", "}", "else", "{", "websocket", ".", "_receiver", ".", "on", "(", "'error'", ",", "receiverOnFinish", ")", ";", "websocket", ".", "_receiver", ".", "on", "(", "'finish'", ",", "receiverOnFinish", ")", ";", "}", "}" ]
The listener of the `net.Socket` `'close'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "close", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L827-L862
2,588
websockets/ws
lib/websocket.js
socketOnEnd
function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); }
javascript
function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); }
[ "function", "socketOnEnd", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "websocket", ".", "_receiver", ".", "end", "(", ")", ";", "this", ".", "end", "(", ")", ";", "}" ]
The listener of the `net.Socket` `'end'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "end", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L881-L887
2,589
websockets/ws
lib/websocket.js
socketOnError
function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); }
javascript
function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); }
[ "function", "socketOnError", "(", ")", "{", "const", "websocket", "=", "this", "[", "kWebSocket", "]", ";", "this", ".", "removeListener", "(", "'error'", ",", "socketOnError", ")", ";", "this", ".", "on", "(", "'error'", ",", "NOOP", ")", ";", "websocket", ".", "readyState", "=", "WebSocket", ".", "CLOSING", ";", "this", ".", "destroy", "(", ")", ";", "}" ]
The listener of the `net.Socket` `'error'` event. @private
[ "The", "listener", "of", "the", "net", ".", "Socket", "error", "event", "." ]
995c527c87d0d4833d8093c18dcfa2e4a41d9582
https://github.com/websockets/ws/blob/995c527c87d0d4833d8093c18dcfa2e4a41d9582/lib/websocket.js#L894-L902
2,590
summernote/summernote
src/js/base/core/lists.js
all
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
javascript
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
[ "function", "all", "(", "array", ",", "pred", ")", "{", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "!", "pred", "(", "array", "[", "idx", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
returns true if all of the values in the array pass the predicate truth test.
[ "returns", "true", "if", "all", "of", "the", "values", "in", "the", "array", "pass", "the", "predicate", "truth", "test", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L54-L61
2,591
summernote/summernote
src/js/base/core/lists.js
contains
function contains(array, item) { if (array && array.length && item) { return array.indexOf(item) !== -1; } return false; }
javascript
function contains(array, item) { if (array && array.length && item) { return array.indexOf(item) !== -1; } return false; }
[ "function", "contains", "(", "array", ",", "item", ")", "{", "if", "(", "array", "&&", "array", ".", "length", "&&", "item", ")", "{", "return", "array", ".", "indexOf", "(", "item", ")", "!==", "-", "1", ";", "}", "return", "false", ";", "}" ]
returns true if the value is present in the list.
[ "returns", "true", "if", "the", "value", "is", "present", "in", "the", "list", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L66-L71
2,592
summernote/summernote
src/js/base/core/lists.js
sum
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
javascript
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
[ "function", "sum", "(", "array", ",", "fn", ")", "{", "fn", "=", "fn", "||", "func", ".", "self", ";", "return", "array", ".", "reduce", "(", "function", "(", "memo", ",", "v", ")", "{", "return", "memo", "+", "fn", "(", "v", ")", ";", "}", ",", "0", ")", ";", "}" ]
get sum from a list @param {Array} array - array @param {Function} fn - iterator
[ "get", "sum", "from", "a", "list" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L79-L84
2,593
summernote/summernote
src/js/base/core/lists.js
from
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
javascript
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
[ "function", "from", "(", "collection", ")", "{", "const", "result", "=", "[", "]", ";", "const", "length", "=", "collection", ".", "length", ";", "let", "idx", "=", "-", "1", ";", "while", "(", "++", "idx", "<", "length", ")", "{", "result", "[", "idx", "]", "=", "collection", "[", "idx", "]", ";", "}", "return", "result", ";", "}" ]
returns a copy of the collection with array type. @param {Collection} collection - collection eg) node.childNodes, ...
[ "returns", "a", "copy", "of", "the", "collection", "with", "array", "type", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L90-L98
2,594
summernote/summernote
src/js/base/core/lists.js
compact
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
javascript
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
[ "function", "compact", "(", "array", ")", "{", "const", "aResult", "=", "[", "]", ";", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "array", "[", "idx", "]", ")", "{", "aResult", ".", "push", "(", "array", "[", "idx", "]", ")", ";", "}", "}", "return", "aResult", ";", "}" ]
returns a copy of the array with all false values removed @param {Array} array - array @param {Function} fn - predicate function for cluster rule
[ "returns", "a", "copy", "of", "the", "array", "with", "all", "false", "values", "removed" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L134-L140
2,595
summernote/summernote
src/js/base/core/lists.js
unique
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
javascript
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
[ "function", "unique", "(", "array", ")", "{", "const", "results", "=", "[", "]", ";", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "array", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "if", "(", "!", "contains", "(", "results", ",", "array", "[", "idx", "]", ")", ")", "{", "results", ".", "push", "(", "array", "[", "idx", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
produces a duplicate-free version of the array @param {Array} array
[ "produces", "a", "duplicate", "-", "free", "version", "of", "the", "array" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L147-L157
2,596
summernote/summernote
src/js/base/core/lists.js
prev
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
javascript
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
[ "function", "prev", "(", "array", ",", "item", ")", "{", "if", "(", "array", "&&", "array", ".", "length", "&&", "item", ")", "{", "const", "idx", "=", "array", ".", "indexOf", "(", "item", ")", ";", "return", "idx", "===", "-", "1", "?", "null", ":", "array", "[", "idx", "-", "1", "]", ";", "}", "return", "null", ";", "}" ]
returns prev item. @param {Array} array
[ "returns", "prev", "item", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/lists.js#L175-L181
2,597
summernote/summernote
src/js/base/core/dom.js
listDescendant
function listDescendant(node, pred) { const descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (let idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; }
javascript
function listDescendant(node, pred) { const descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (let idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; }
[ "function", "listDescendant", "(", "node", ",", "pred", ")", "{", "const", "descendants", "=", "[", "]", ";", "pred", "=", "pred", "||", "func", ".", "ok", ";", "// start DFS(depth first search) with node", "(", "function", "fnWalk", "(", "current", ")", "{", "if", "(", "node", "!==", "current", "&&", "pred", "(", "current", ")", ")", "{", "descendants", ".", "push", "(", "current", ")", ";", "}", "for", "(", "let", "idx", "=", "0", ",", "len", "=", "current", ".", "childNodes", ".", "length", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "fnWalk", "(", "current", ".", "childNodes", "[", "idx", "]", ")", ";", "}", "}", ")", "(", "node", ")", ";", "return", "descendants", ";", "}" ]
listing descendant nodes @param {Node} node @param {Function} [pred] - predicate function
[ "listing", "descendant", "nodes" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L352-L367
2,598
summernote/summernote
src/js/base/core/dom.js
isLeftEdgeOf
function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }
javascript
function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; }
[ "function", "isLeftEdgeOf", "(", "node", ",", "ancestor", ")", "{", "while", "(", "node", "&&", "node", "!==", "ancestor", ")", "{", "if", "(", "position", "(", "node", ")", "!==", "0", ")", "{", "return", "false", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "return", "true", ";", "}" ]
returns whether node is left edge of ancestor or not. @param {Node} node @param {Node} ancestor @return {Boolean}
[ "returns", "whether", "node", "is", "left", "edge", "of", "ancestor", "or", "not", "." ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L453-L462
2,599
summernote/summernote
src/js/base/core/dom.js
prevPoint
function prevPoint(point, isSkipInnerOffset) { let node; let offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset, }; }
javascript
function prevPoint(point, isSkipInnerOffset) { let node; let offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset, }; }
[ "function", "prevPoint", "(", "point", ",", "isSkipInnerOffset", ")", "{", "let", "node", ";", "let", "offset", ";", "if", "(", "point", ".", "offset", "===", "0", ")", "{", "if", "(", "isEditable", "(", "point", ".", "node", ")", ")", "{", "return", "null", ";", "}", "node", "=", "point", ".", "node", ".", "parentNode", ";", "offset", "=", "position", "(", "point", ".", "node", ")", ";", "}", "else", "if", "(", "hasChildren", "(", "point", ".", "node", ")", ")", "{", "node", "=", "point", ".", "node", ".", "childNodes", "[", "point", ".", "offset", "-", "1", "]", ";", "offset", "=", "nodeLength", "(", "node", ")", ";", "}", "else", "{", "node", "=", "point", ".", "node", ";", "offset", "=", "isSkipInnerOffset", "?", "0", ":", "point", ".", "offset", "-", "1", ";", "}", "return", "{", "node", ":", "node", ",", "offset", ":", "offset", ",", "}", ";", "}" ]
returns previous boundaryPoint @param {BoundaryPoint} point @param {Boolean} isSkipInnerOffset @return {BoundaryPoint}
[ "returns", "previous", "boundaryPoint" ]
8dcafb8107453006b905ef697a529c42e76beb3f
https://github.com/summernote/summernote/blob/8dcafb8107453006b905ef697a529c42e76beb3f/src/js/base/core/dom.js#L529-L552